@atomiqlabs/sdk 8.6.0 → 8.6.3

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 (61) hide show
  1. package/dist/http/paramcoders/ParamDecoder.js +9 -4
  2. package/dist/http/paramcoders/ParamEncoder.js +6 -1
  3. package/dist/intermediaries/IntermediaryDiscovery.js +4 -3
  4. package/dist/storage/UnifiedSwapStorage.js +13 -8
  5. package/dist/swapper/Swapper.d.ts +1 -12
  6. package/dist/swapper/Swapper.js +31 -28
  7. package/dist/swapper/SwapperFactory.d.ts +1 -0
  8. package/dist/swapper/SwapperFactory.js +9 -4
  9. package/dist/swaps/ISwap.d.ts +8 -0
  10. package/dist/swaps/ISwap.js +8 -0
  11. package/dist/swaps/ISwapWrapper.d.ts +23 -1
  12. package/dist/swaps/ISwapWrapper.js +88 -28
  13. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +4 -1
  14. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +2 -2
  15. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +1 -1
  16. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +2 -2
  17. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +16 -6
  18. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +8 -2
  19. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +1 -1
  20. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +14 -4
  21. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +8 -6
  22. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +2 -1
  23. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +7 -5
  24. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +8 -2
  25. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +1 -1
  26. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +0 -6
  27. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +8 -3
  28. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +8 -2
  29. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +1 -0
  30. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +3 -2
  31. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +1 -3
  32. package/dist/swaps/trusted/ln/LnForGasWrapper.js +0 -1
  33. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +0 -1
  34. package/dist/utils/RetryUtils.d.ts +2 -1
  35. package/dist/utils/RetryUtils.js +3 -2
  36. package/package.json +1 -1
  37. package/src/http/paramcoders/ParamDecoder.ts +8 -4
  38. package/src/http/paramcoders/ParamEncoder.ts +5 -1
  39. package/src/intermediaries/IntermediaryDiscovery.ts +6 -4
  40. package/src/storage/UnifiedSwapStorage.ts +13 -8
  41. package/src/swapper/Swapper.ts +35 -28
  42. package/src/swapper/SwapperFactory.ts +12 -6
  43. package/src/swaps/ISwap.ts +8 -0
  44. package/src/swaps/ISwapWrapper.ts +104 -28
  45. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +5 -1
  46. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +3 -3
  47. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +17 -8
  48. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +8 -3
  49. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +13 -5
  50. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +8 -7
  51. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +9 -5
  52. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +7 -2
  53. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +1 -1
  54. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +0 -3
  55. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +7 -3
  56. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +7 -2
  57. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +5 -2
  58. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +1 -3
  59. package/src/swaps/trusted/ln/LnForGasWrapper.ts +0 -1
  60. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +0 -1
  61. package/src/utils/RetryUtils.ts +11 -4
@@ -2,6 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ParamDecoder = void 0;
4
4
  const buffer_1 = require("buffer");
5
+ function ensureBuffer(input) {
6
+ if (input instanceof buffer_1.Buffer)
7
+ return input;
8
+ return buffer_1.Buffer.from(input);
9
+ }
5
10
  class ParamDecoder {
6
11
  constructor() {
7
12
  this.frameData = [];
@@ -48,8 +53,8 @@ class ParamDecoder {
48
53
  leavesBuffer = null;
49
54
  }
50
55
  else {
51
- this.frameHeader = leavesBuffer.subarray(0, 4);
52
- leavesBuffer = leavesBuffer.subarray(4);
56
+ this.frameHeader = ensureBuffer(leavesBuffer.subarray(0, 4));
57
+ leavesBuffer = ensureBuffer(leavesBuffer.subarray(4));
53
58
  }
54
59
  }
55
60
  else if (this.frameHeader.length < 4) {
@@ -60,14 +65,14 @@ class ParamDecoder {
60
65
  }
61
66
  else {
62
67
  this.frameHeader = buffer_1.Buffer.concat([this.frameHeader, leavesBuffer.subarray(0, requiredLen)]);
63
- leavesBuffer = leavesBuffer.subarray(requiredLen);
68
+ leavesBuffer = ensureBuffer(leavesBuffer.subarray(requiredLen));
64
69
  }
65
70
  }
66
71
  if (leavesBuffer == null)
67
72
  continue;
68
73
  if (this.frameHeader == null || this.frameHeader.length < 4)
69
74
  continue;
70
- const frameLength = this.frameHeader.readUint32LE();
75
+ const frameLength = this.frameHeader.readUint32LE != null ? this.frameHeader.readUint32LE() : this.frameHeader.readUInt32LE();
71
76
  const requiredLen = frameLength - this.frameDataLength;
72
77
  if (leavesBuffer.length <= requiredLen) {
73
78
  this.frameData.push(leavesBuffer);
@@ -15,7 +15,12 @@ class ParamEncoder {
15
15
  writeParams(data) {
16
16
  const serialized = buffer_1.Buffer.from(JSON.stringify(data));
17
17
  const frameLengthBuffer = buffer_1.Buffer.alloc(4);
18
- frameLengthBuffer.writeUint32LE(serialized.length);
18
+ if (frameLengthBuffer.writeUint32LE != null) {
19
+ frameLengthBuffer.writeUint32LE(serialized.length);
20
+ }
21
+ else {
22
+ frameLengthBuffer.writeUInt32LE(serialized.length);
23
+ }
19
24
  return this.writeFN(buffer_1.Buffer.concat([
20
25
  frameLengthBuffer,
21
26
  serialized
@@ -129,7 +129,7 @@ class IntermediaryDiscovery extends events_1.EventEmitter {
129
129
  * @param abortSignal
130
130
  */
131
131
  async getNodeInfo(url, abortSignal) {
132
- const response = await (0, RetryUtils_1.tryWithRetries)(() => IntermediaryAPI_1.IntermediaryAPI.getIntermediaryInfo(url, this.httpRequestTimeout, abortSignal), { maxRetries: 3, delay: 100, exponential: true }, undefined, abortSignal);
132
+ const response = await (0, RetryUtils_1.tryWithRetries)(() => IntermediaryAPI_1.IntermediaryAPI.getIntermediaryInfo(url, this.httpRequestTimeout, abortSignal), { maxRetries: 3, delay: 100, exponential: true }, undefined, abortSignal, "debug");
133
133
  abortSignal?.throwIfAborted();
134
134
  const promises = [];
135
135
  const addresses = {};
@@ -142,7 +142,7 @@ class IntermediaryDiscovery extends events_1.EventEmitter {
142
142
  addresses[chain] = address;
143
143
  }
144
144
  catch (e) {
145
- logger.warn("Failed to verify " + chain + " signature for intermediary: " + url);
145
+ logger.warn("getNodeInfo(): Failed to verify " + chain + " signature for intermediary: " + url);
146
146
  }
147
147
  })());
148
148
  }
@@ -191,7 +191,8 @@ class IntermediaryDiscovery extends events_1.EventEmitter {
191
191
  return new Intermediary_1.Intermediary(url, nodeInfo.addresses, services);
192
192
  }
193
193
  catch (e) {
194
- logger.warn("fetchIntermediaries(): Error contacting intermediary " + url + ": ", e);
194
+ logger.warn("fetchIntermediaries(): Intermediary " + url + ` is unreachable due to ${e.name ?? e.message} error, skipping...`);
195
+ logger.debug("fetchIntermediaries(): Error contacting intermediary " + url + ": ", e);
195
196
  return null;
196
197
  }
197
198
  }
@@ -64,6 +64,7 @@ class UnifiedSwapStorage {
64
64
  const value = reviver(rawObj);
65
65
  if (value == null)
66
66
  return;
67
+ value._persisted = true;
67
68
  if (!this.noWeakRefMap)
68
69
  this.weakRefCache.set(rawObj.id, new WeakRef(value));
69
70
  result.push(value);
@@ -75,37 +76,41 @@ class UnifiedSwapStorage {
75
76
  *
76
77
  * @param value Swap to save
77
78
  */
78
- save(value) {
79
+ async save(value) {
79
80
  if (!this.noWeakRefMap)
80
81
  this.weakRefCache.set(value.getId(), new WeakRef(value));
81
- return this.storage.save(value.serialize());
82
+ await this.storage.save(value.serialize());
83
+ value._persisted = true;
82
84
  }
83
85
  /**
84
86
  * Saves multiple swaps to storage in a batch operation
85
87
  * @param values Array of swaps to save
86
88
  */
87
- saveAll(values) {
89
+ async saveAll(values) {
88
90
  if (!this.noWeakRefMap)
89
91
  values.forEach(value => this.weakRefCache.set(value.getId(), new WeakRef(value)));
90
- return this.storage.saveAll(values.map(obj => obj.serialize()));
92
+ await this.storage.saveAll(values.map(obj => obj.serialize()));
93
+ values.forEach(value => value._persisted = true);
91
94
  }
92
95
  /**
93
96
  * Removes a swap from storage
94
97
  * @param value Swap to remove
95
98
  */
96
- remove(value) {
99
+ async remove(value) {
97
100
  if (!this.noWeakRefMap)
98
101
  this.weakRefCache.delete(value.getId());
99
- return this.storage.remove(value.serialize());
102
+ await this.storage.remove(value.serialize());
103
+ value._persisted = false;
100
104
  }
101
105
  /**
102
106
  * Removes multiple swaps from storage in a batch operation
103
107
  * @param values Array of swaps to remove
104
108
  */
105
- removeAll(values) {
109
+ async removeAll(values) {
106
110
  if (!this.noWeakRefMap)
107
111
  values.forEach(value => this.weakRefCache.delete(value.getId()));
108
- return this.storage.removeAll(values.map(obj => obj.serialize()));
112
+ await this.storage.removeAll(values.map(obj => obj.serialize()));
113
+ values.forEach(value => value._persisted = false);
109
114
  }
110
115
  }
111
116
  exports.UnifiedSwapStorage = UnifiedSwapStorage;
@@ -174,17 +174,6 @@ type MultiChainData<T extends MultiChain> = {
174
174
  type CtorMultiChainData<T extends MultiChain> = {
175
175
  [chainIdentifier in keyof T]: ChainData<T[chainIdentifier]>;
176
176
  };
177
- type SwapperCtorTokens<T extends MultiChain = MultiChain> = {
178
- ticker: string;
179
- name: string;
180
- chains: {
181
- [chainId in ChainIds<T>]?: {
182
- address: string;
183
- decimals: number;
184
- displayDecimals?: number;
185
- };
186
- };
187
- }[];
188
177
  /**
189
178
  * Type extracting chain identifiers from a MultiChain type
190
179
  * @category Core
@@ -263,7 +252,7 @@ export declare class Swapper<T extends MultiChain> extends EventEmitter<{
263
252
  /**
264
253
  * @internal
265
254
  */
266
- constructor(bitcoinRpc: BitcoinRpcWithAddressIndex<any>, lightningApi: LightningNetworkApi, bitcoinSynchronizer: (btcRelay: BtcRelay<any, any, any>) => RelaySynchronizer<any, any, any>, chainsData: CtorMultiChainData<T>, pricing: ISwapPrice<T>, tokens: SwapperCtorTokens<T>, messenger: Messenger, options?: SwapperOptions);
255
+ constructor(bitcoinRpc: BitcoinRpcWithAddressIndex<any>, lightningApi: LightningNetworkApi, bitcoinSynchronizer: (btcRelay: BtcRelay<any, any, any>) => RelaySynchronizer<any, any, any>, chainsData: CtorMultiChainData<T>, pricing: ISwapPrice<T>, tokens: SCToken[], messenger: Messenger, options?: SwapperOptions);
267
256
  private _init;
268
257
  private initPromise?;
269
258
  private initialized;
@@ -82,22 +82,10 @@ class Swapper extends events_1.EventEmitter {
82
82
  this._tokens = {};
83
83
  this._tokensByTicker = {};
84
84
  for (let tokenData of tokens) {
85
- for (let chainId in tokenData.chains) {
86
- const chainData = tokenData.chains[chainId];
87
- this._tokens[chainId] ??= {};
88
- this._tokensByTicker[chainId] ??= {};
89
- this._tokens[chainId][chainData.address] = this._tokensByTicker[chainId][tokenData.ticker] = {
90
- chain: "SC",
91
- chainId,
92
- ticker: tokenData.ticker,
93
- name: tokenData.name,
94
- decimals: chainData.decimals,
95
- displayDecimals: chainData.displayDecimals,
96
- address: chainData.address,
97
- equals: (other) => other.chainId === chainId && other.ticker === tokenData.ticker && other.address === chainData.address,
98
- toString: () => `${chainId}-${tokenData.ticker}`
99
- };
100
- }
85
+ const chainId = tokenData.chainId;
86
+ this._tokens[chainId] ??= {};
87
+ this._tokensByTicker[chainId] ??= {};
88
+ this._tokens[chainId][tokenData.address] = this._tokensByTicker[chainId][tokenData.ticker] = tokenData;
101
89
  }
102
90
  this.swapStateListener = (swap) => {
103
91
  this.emit("swapState", swap);
@@ -112,35 +100,42 @@ class Swapper extends events_1.EventEmitter {
112
100
  wrappers[SwapType_1.SwapType.TO_BTCLN] = new ToBTCLNWrapper_1.ToBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, {
113
101
  getRequestTimeout: this.options.getRequestTimeout,
114
102
  postRequestTimeout: this.options.postRequestTimeout,
103
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
115
104
  });
116
105
  wrappers[SwapType_1.SwapType.TO_BTC] = new ToBTCWrapper_1.ToBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, this._bitcoinRpc, {
117
106
  getRequestTimeout: this.options.getRequestTimeout,
118
107
  postRequestTimeout: this.options.postRequestTimeout,
108
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
119
109
  bitcoinNetwork: this._btcNetwork
120
110
  });
121
111
  wrappers[SwapType_1.SwapType.FROM_BTCLN] = new FromBTCLNWrapper_1.FromBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, {
122
112
  getRequestTimeout: this.options.getRequestTimeout,
123
113
  postRequestTimeout: this.options.postRequestTimeout,
114
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
124
115
  unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
125
116
  });
126
117
  wrappers[SwapType_1.SwapType.FROM_BTC] = new FromBTCWrapper_1.FromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, btcRelay, synchronizer, this._bitcoinRpc, {
127
118
  getRequestTimeout: this.options.getRequestTimeout,
128
119
  postRequestTimeout: this.options.postRequestTimeout,
120
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
129
121
  bitcoinNetwork: this._btcNetwork
130
122
  });
131
123
  wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN] = new LnForGasWrapper_1.LnForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], {
132
124
  getRequestTimeout: this.options.getRequestTimeout,
133
- postRequestTimeout: this.options.postRequestTimeout
125
+ postRequestTimeout: this.options.postRequestTimeout,
126
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
134
127
  });
135
128
  wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC] = new OnchainForGasWrapper_1.OnchainForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], bitcoinRpc, {
136
129
  getRequestTimeout: this.options.getRequestTimeout,
137
130
  postRequestTimeout: this.options.postRequestTimeout,
131
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
138
132
  bitcoinNetwork: this._btcNetwork
139
133
  });
140
134
  if (spvVaultContract != null) {
141
135
  wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC] = new SpvFromBTCWrapper_1.SpvFromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, spvVaultContract, pricing, this._tokens[chainId], spvVaultWithdrawalDataConstructor, btcRelay, synchronizer, bitcoinRpc, {
142
136
  getRequestTimeout: this.options.getRequestTimeout,
143
137
  postRequestTimeout: this.options.postRequestTimeout,
138
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
144
139
  bitcoinNetwork: this._btcNetwork
145
140
  });
146
141
  }
@@ -148,6 +143,7 @@ class Swapper extends events_1.EventEmitter {
148
143
  wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO] = new FromBTCLNAutoWrapper_1.FromBTCLNAutoWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, this.messenger, {
149
144
  getRequestTimeout: this.options.getRequestTimeout,
150
145
  postRequestTimeout: this.options.postRequestTimeout,
146
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
151
147
  unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
152
148
  });
153
149
  }
@@ -186,7 +182,7 @@ class Swapper extends events_1.EventEmitter {
186
182
  });
187
183
  }
188
184
  async _init() {
189
- this.logger.debug("init(): Initializing swapper, sdk-lib version 16.1.3");
185
+ this.logger.debug("init(): Initializing swapper...");
190
186
  const abortController = new AbortController();
191
187
  const promises = [];
192
188
  let automaticClockDriftCorrectionPromise = undefined;
@@ -222,7 +218,11 @@ class Swapper extends events_1.EventEmitter {
222
218
  const chainPromises = [];
223
219
  for (let chainIdentifier in this._chains) {
224
220
  chainPromises.push((async () => {
225
- const { swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this._chains[chainIdentifier];
221
+ const { chainInterface, swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this._chains[chainIdentifier];
222
+ const _chainInterface = chainInterface;
223
+ if (_chainInterface.verifyNetwork != null) {
224
+ await _chainInterface.verifyNetwork(this.bitcoinNetwork);
225
+ }
226
226
  await swapContract.start();
227
227
  this.logger.debug("init(): Intialized swap contract: " + chainIdentifier);
228
228
  await unifiedSwapStorage.init();
@@ -268,8 +268,10 @@ class Swapper extends events_1.EventEmitter {
268
268
  async init() {
269
269
  if (this.initialized)
270
270
  return;
271
- if (this.initPromise != null)
271
+ if (this.initPromise != null) {
272
272
  await this.initPromise;
273
+ return;
274
+ }
273
275
  try {
274
276
  const promise = this._init();
275
277
  this.initPromise = promise;
@@ -446,10 +448,7 @@ class Swapper extends events_1.EventEmitter {
446
448
  if (swapLimitsChanged)
447
449
  this.emit("swapLimitsChanged");
448
450
  const quote = quotes[0].quote;
449
- if (this.options.saveUninitializedSwaps) {
450
- quote._setInitiated();
451
- await quote._save();
452
- }
451
+ await quote._save();
453
452
  return quote;
454
453
  }
455
454
  catch (e) {
@@ -732,7 +731,7 @@ class Swapper extends events_1.EventEmitter {
732
731
  * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
733
732
  * @throws {Error} If no trusted intermediary specified
734
733
  */
735
- createTrustedLNForGasSwap(chainIdentifier, recipient, amount, trustedIntermediaryOrUrl) {
734
+ async createTrustedLNForGasSwap(chainIdentifier, recipient, amount, trustedIntermediaryOrUrl) {
736
735
  if (this._chains[chainIdentifier] == null)
737
736
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
738
737
  if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
@@ -741,7 +740,9 @@ class Swapper extends events_1.EventEmitter {
741
740
  const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
742
741
  if (useUrl == null)
743
742
  throw new Error("No trusted intermediary specified!");
744
- return this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(recipient, amount, useUrl);
743
+ const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(recipient, amount, useUrl);
744
+ await swap._save();
745
+ return swap;
745
746
  }
746
747
  /**
747
748
  * Creates a trusted Bitcoin -> Smart chain ({@link SwapType.TRUSTED_FROM_BTC}) gas swap
@@ -753,7 +754,7 @@ class Swapper extends events_1.EventEmitter {
753
754
  * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
754
755
  * @throws {Error} If no trusted intermediary specified
755
756
  */
756
- createTrustedOnchainForGasSwap(chainIdentifier, recipient, amount, refundAddress, trustedIntermediaryOrUrl) {
757
+ async createTrustedOnchainForGasSwap(chainIdentifier, recipient, amount, refundAddress, trustedIntermediaryOrUrl) {
757
758
  if (this._chains[chainIdentifier] == null)
758
759
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
759
760
  if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
@@ -762,7 +763,9 @@ class Swapper extends events_1.EventEmitter {
762
763
  const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
763
764
  if (useUrl == null)
764
765
  throw new Error("No trusted intermediary specified!");
765
- return this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(recipient, amount, useUrl, refundAddress);
766
+ const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(recipient, amount, useUrl, refundAddress);
767
+ await swap._save();
768
+ return swap;
766
769
  }
767
770
  /**
768
771
  * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (exactIn=true)
@@ -113,6 +113,7 @@ export declare class SwapperFactory<T extends readonly ChainInitializer<any, Cha
113
113
  * Token resolvers for various smart chains supported by the SDK, allow fetching tokens based on their addresses
114
114
  */
115
115
  TokenResolver: TypedTokenResolvers<T>;
116
+ private smartChainTokens;
116
117
  constructor(initializers: T);
117
118
  /**
118
119
  * Returns a new swapper instance with the passed options.
@@ -64,21 +64,26 @@ class SwapperFactory {
64
64
  * Token resolvers for various smart chains supported by the SDK, allow fetching tokens based on their addresses
65
65
  */
66
66
  this.TokenResolver = {};
67
+ this.smartChainTokens = [];
67
68
  this.initializers = initializers;
68
69
  initializers.forEach(initializer => {
69
70
  const addressMap = {};
70
71
  const tokens = (this.Tokens[initializer.chainId] = {});
71
72
  for (let ticker in initializer.tokens) {
72
73
  const assetData = initializer.tokens[ticker];
73
- tokens[ticker] = addressMap[assetData.address] = {
74
+ const token = {
74
75
  chain: "SC",
75
76
  chainId: initializer.chainId,
76
- address: assetData.address,
77
+ ticker,
77
78
  name: SmartChainAssets_1.SmartChainAssets[ticker]?.name ?? ticker,
78
79
  decimals: assetData.decimals,
79
80
  displayDecimals: assetData.displayDecimals,
80
- ticker
81
+ address: assetData.address,
82
+ equals: (other) => other.chainId === initializer.chainId && other.ticker === ticker && other.address === assetData.address,
83
+ toString: () => `${initializer.chainId}-${ticker}`
81
84
  };
85
+ this.smartChainTokens.push(token);
86
+ tokens[ticker] = addressMap[assetData.address] = token;
82
87
  }
83
88
  this.TokenResolver[initializer.chainId] = {
84
89
  getToken: (address) => addressMap[address]
@@ -140,7 +145,7 @@ class SwapperFactory {
140
145
  };
141
146
  }), options.getPriceFn)) :
142
147
  RedundantSwapPrice_1.RedundantSwapPrice.createFromTokenMap(options.pricingFeeDifferencePPM ?? 10000n, pricingAssets);
143
- return new Swapper_1.Swapper(bitcoinRpc, bitcoinRpc, (btcRelay) => new btc_mempool_1.MempoolBtcRelaySynchronizer(btcRelay, bitcoinRpc), chains, swapPricing, pricingAssets, options.messenger, options);
148
+ return new Swapper_1.Swapper(bitcoinRpc, bitcoinRpc, (btcRelay) => new btc_mempool_1.MempoolBtcRelaySynchronizer(btcRelay, bitcoinRpc), chains, swapPricing, this.smartChainTokens, options.messenger, options);
144
149
  }
145
150
  /**
146
151
  * Returns a new and already initialized swapper instance with the passed options. There is no need
@@ -111,6 +111,14 @@ export declare abstract class ISwap<T extends ChainType = ChainType, D extends S
111
111
  * @internal
112
112
  */
113
113
  _randomNonce: string;
114
+ /**
115
+ * Whether the swap is saved in the persistent storage or not.
116
+ *
117
+ * @remarks This field itself is not persisted but is instead derived during runtime
118
+ *
119
+ * @internal
120
+ */
121
+ _persisted: boolean;
114
122
  /**
115
123
  * Event emitter emitting `"swapState"` event when swap's state changes
116
124
  */
@@ -49,6 +49,14 @@ class ISwap {
49
49
  * @internal
50
50
  */
51
51
  this._state = 0;
52
+ /**
53
+ * Whether the swap is saved in the persistent storage or not.
54
+ *
55
+ * @remarks This field itself is not persisted but is instead derived during runtime
56
+ *
57
+ * @internal
58
+ */
59
+ this._persisted = false;
52
60
  /**
53
61
  * Event emitter emitting `"swapState"` event when swap's state changes
54
62
  */
@@ -9,6 +9,8 @@ import { SwapType } from "../enums/SwapType";
9
9
  import { UnifiedSwapStorage } from "../storage/UnifiedSwapStorage";
10
10
  import { SCToken } from "../types/Token";
11
11
  import { PriceInfoType } from "../types/PriceInfoType";
12
+ export declare const DEFAULT_MAX_PARALLEL_SWAP_TICKS = 50;
13
+ export declare const DEFAULT_MAX_PARALLEL_SWAP_SYNCS = 50;
12
14
  /**
13
15
  * Options for swap wrapper configuration
14
16
  *
@@ -17,6 +19,18 @@ import { PriceInfoType } from "../types/PriceInfoType";
17
19
  export type ISwapWrapperOptions = {
18
20
  getRequestTimeout?: number;
19
21
  postRequestTimeout?: number;
22
+ /**
23
+ * How many swaps to call `_tick()` for in parallel
24
+ */
25
+ maxParallelSwapTicks?: number;
26
+ /**
27
+ * How many swaps to call `_sync()` for in parallel
28
+ */
29
+ maxParallelSwapSyncs?: number;
30
+ /**
31
+ * Whether to save swaps that are not initialized into the persistent storage
32
+ */
33
+ saveUninitializedSwaps?: boolean;
20
34
  };
21
35
  /**
22
36
  * Token configuration for wrapper constructors
@@ -86,6 +100,11 @@ export declare abstract class ISwapWrapper<T extends ChainType, D extends SwapTy
86
100
  * @internal
87
101
  */
88
102
  protected tickInterval?: NodeJS.Timeout;
103
+ /**
104
+ * An internal abort controller for the running tick handler
105
+ * @internal
106
+ */
107
+ protected tickAbortController?: AbortController;
89
108
  /**
90
109
  * States of the swaps in pending (non-final state), these are checked automatically on initial swap synchronization
91
110
  * @internal
@@ -215,6 +234,8 @@ export declare abstract class ISwapWrapper<T extends ChainType, D extends SwapTy
215
234
  /**
216
235
  * Runs checks on all the known pending swaps, syncing their state from on-chain data
217
236
  *
237
+ * @remarks Doesn't work properly if you pass non-persisted swaps
238
+ *
218
239
  * @param pastSwaps Optional array of past swaps to check, otherwise all relevant swaps will be fetched
219
240
  * from the persistent storage
220
241
  * @param noSave Whether to skip saving the swap changes in the persistent storage
@@ -228,8 +249,9 @@ export declare abstract class ISwapWrapper<T extends ChainType, D extends SwapTy
228
249
  *
229
250
  * @param swaps Optional array of swaps to invoke `_tick()` on, otherwise all relevant swaps will be fetched
230
251
  * from the persistent storage
252
+ * @param abortSignal Abort signal
231
253
  */
232
- tick(swaps?: D["Swap"][]): Promise<void>;
254
+ tick(swaps?: D["Swap"][], abortSignal?: AbortSignal): Promise<void>;
233
255
  /**
234
256
  * Returns the smart chain's native token used to pay for fees
235
257
  * @internal