@atomiqlabs/sdk 1.3.19 → 2.1.0-beta.0

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 (49) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +545 -501
  3. package/dist/SmartChainAssets.d.ts +73 -59
  4. package/dist/SmartChainAssets.js +75 -55
  5. package/dist/SwapperFactory.d.ts +49 -0
  6. package/dist/SwapperFactory.js +84 -0
  7. package/dist/Utils.d.ts +11 -0
  8. package/dist/Utils.js +37 -0
  9. package/dist/fs-storage/FileSystemStorageManager.d.ts +15 -0
  10. package/dist/fs-storage/FileSystemStorageManager.js +60 -0
  11. package/dist/fs-storage/index.d.ts +1 -0
  12. package/dist/fs-storage/index.js +17 -0
  13. package/dist/index.d.ts +5 -4
  14. package/dist/index.js +21 -20
  15. package/dist/storage/LocalStorageManager.d.ts +24 -0
  16. package/dist/storage/LocalStorageManager.js +68 -0
  17. package/package.json +31 -32
  18. package/src/SmartChainAssets.js +75 -0
  19. package/src/SmartChainAssets.ts +76 -62
  20. package/src/SwapperFactory.js +96 -0
  21. package/src/SwapperFactory.ts +171 -0
  22. package/src/Utils.js +37 -0
  23. package/src/Utils.ts +31 -0
  24. package/src/example/BrowserExample.js +199 -0
  25. package/src/example/BrowserExample.ts +141 -120
  26. package/src/example/NodeJSExample.js +206 -0
  27. package/src/example/NodeJSExample.ts +150 -120
  28. package/src/fs-storage/FileSystemStorageManager.ts +71 -0
  29. package/src/fs-storage/index.ts +1 -0
  30. package/src/index.js +21 -0
  31. package/src/index.ts +5 -4
  32. package/src/storage/LocalStorageManager.js +72 -0
  33. package/src/storage/LocalStorageManager.ts +81 -0
  34. package/dist/MultichainSwapper.d.ts +0 -46
  35. package/dist/MultichainSwapper.js +0 -83
  36. package/dist/chains/ChainInitializer.d.ts +0 -13
  37. package/dist/chains/ChainInitializer.js +0 -2
  38. package/dist/chains/solana/SolanaChainInitializer.d.ts +0 -41
  39. package/dist/chains/solana/SolanaChainInitializer.js +0 -60
  40. package/dist/chains/solana/SolanaChains.d.ts +0 -14
  41. package/dist/chains/solana/SolanaChains.js +0 -18
  42. package/dist/example/BrowserExample.d.ts +0 -1
  43. package/dist/example/BrowserExample.js +0 -104
  44. package/dist/example/NodeJSExample.d.ts +0 -1
  45. package/dist/example/NodeJSExample.js +0 -104
  46. package/src/MultichainSwapper.ts +0 -156
  47. package/src/chains/ChainInitializer.ts +0 -16
  48. package/src/chains/solana/SolanaChainInitializer.ts +0 -99
  49. package/src/chains/solana/SolanaChains.ts +0 -16
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ var __1 = require("../");
40
+ var chain_starknet_1 = require("@atomiqlabs/chain-starknet");
41
+ var chain_solana_1 = require("@atomiqlabs/chain-solana");
42
+ var solanaRpc = "https://api.mainnet-beta.solana.com";
43
+ var starknetRpc = "https://starknet-mainnet.public.blastapi.io/rpc/v0_7";
44
+ //We initialize a swapper factory, this is important such that we can pick and choose which chains
45
+ // we want to support and only install those specific libraries, here Solana & Starknet are used
46
+ //NOTE: The "as const" keyword is important here as to let typescript properly infer the
47
+ // generic type of the SwapperFactory, allowing you to have code-completion for Tokens and TokenResolver
48
+ var Factory = new __1.SwapperFactory([chain_solana_1.SolanaInitializer, chain_starknet_1.StarknetInitializer]);
49
+ var Tokens = Factory.Tokens;
50
+ function setupSwapper() {
51
+ return __awaiter(this, void 0, void 0, function () {
52
+ var swapper, solanaSwapper, signer;
53
+ return __generator(this, function (_a) {
54
+ switch (_a.label) {
55
+ case 0:
56
+ swapper = Factory.newSwapper({
57
+ chains: {
58
+ SOLANA: {
59
+ rpcUrl: solanaRpc
60
+ },
61
+ STARKNET: {
62
+ rpcUrl: starknetRpc
63
+ }
64
+ },
65
+ //The following line is important for running on backend node.js,
66
+ // because the SDK by default uses browser's Indexed DB, which is not available in node
67
+ swapStorage: function (chainId) { return null; },
68
+ noEvents: true,
69
+ noTimers: true,
70
+ dontCheckPastSwaps: true,
71
+ dontFetchLPs: true
72
+ });
73
+ //Initialize the swapper
74
+ return [4 /*yield*/, swapper.init()];
75
+ case 1:
76
+ //Initialize the swapper
77
+ _a.sent();
78
+ solanaSwapper = swapper.withChain("SOLANA");
79
+ signer = solanaSwapper.randomSigner();
80
+ //Or in React, using solana wallet adapter
81
+ //const signer = new SolanaKeypairWallet(useAnchorWallet());
82
+ //Extract a swapper with a defined signer
83
+ return [2 /*return*/, solanaSwapper.withSigner(signer)];
84
+ }
85
+ });
86
+ });
87
+ }
88
+ function createToBtcSwap() {
89
+ return __awaiter(this, void 0, void 0, function () {
90
+ var solanaSwapper, fromToken, toToken, exactIn, amount, recipientBtcAddress, swap, inputTokenAmount, inputValueInUsd, outputTokenAmount, outputValueInUsd, paymentSuccess, bitcoinTxId;
91
+ return __generator(this, function (_a) {
92
+ switch (_a.label) {
93
+ case 0: return [4 /*yield*/, setupSwapper()];
94
+ case 1:
95
+ solanaSwapper = _a.sent();
96
+ fromToken = Tokens.SOLANA.SOL;
97
+ toToken = Tokens.BITCOIN.BTC;
98
+ exactIn = false;
99
+ amount = (0, __1.fromHumanReadableString)("0.0001", toToken);
100
+ recipientBtcAddress = "bc1qtw67hj77rt8zrkkg3jgngutu0yfgt9czjwusxt";
101
+ return [4 /*yield*/, solanaSwapper.create(fromToken, toToken, amount, exactIn, recipientBtcAddress)];
102
+ case 2:
103
+ swap = _a.sent();
104
+ inputTokenAmount = swap.getInput().amount;
105
+ return [4 /*yield*/, swap.getInput().usdValue()];
106
+ case 3:
107
+ inputValueInUsd = _a.sent();
108
+ outputTokenAmount = swap.getOutput().amount;
109
+ return [4 /*yield*/, swap.getOutput().usdValue()];
110
+ case 4:
111
+ outputValueInUsd = _a.sent();
112
+ //Initiate the swap by locking up the SOL
113
+ return [4 /*yield*/, swap.commit()];
114
+ case 5:
115
+ //Initiate the swap by locking up the SOL
116
+ _a.sent();
117
+ return [4 /*yield*/, swap.waitForPayment()];
118
+ case 6:
119
+ paymentSuccess = _a.sent();
120
+ if (!paymentSuccess) return [3 /*break*/, 7];
121
+ bitcoinTxId = swap.getBitcoinTxId();
122
+ return [3 /*break*/, 9];
123
+ case 7:
124
+ //If payment is unsuccessful we can refund and get our funds back
125
+ return [4 /*yield*/, swap.refund()];
126
+ case 8:
127
+ //If payment is unsuccessful we can refund and get our funds back
128
+ _a.sent();
129
+ _a.label = 9;
130
+ case 9: return [2 /*return*/];
131
+ }
132
+ });
133
+ });
134
+ }
135
+ function createFromBtcSwap() {
136
+ return __awaiter(this, void 0, void 0, function () {
137
+ var solanaSwapper, fromToken, toToken, exactIn, amount, swap, inputTokenAmount, inputValueInUsd, outputTokenAmount, outputValueInUsd, qrCodeData, bitcoinAddress, timeout, e_1;
138
+ return __generator(this, function (_a) {
139
+ switch (_a.label) {
140
+ case 0: return [4 /*yield*/, setupSwapper()];
141
+ case 1:
142
+ solanaSwapper = _a.sent();
143
+ fromToken = Tokens.BITCOIN.BTC;
144
+ toToken = Tokens.SOLANA.SOL;
145
+ exactIn = true;
146
+ amount = BigInt(10000);
147
+ return [4 /*yield*/, solanaSwapper.create(fromToken, toToken, amount, exactIn)];
148
+ case 2:
149
+ swap = _a.sent();
150
+ inputTokenAmount = swap.getInput().amount;
151
+ return [4 /*yield*/, swap.getInput().usdValue()];
152
+ case 3:
153
+ inputValueInUsd = _a.sent();
154
+ outputTokenAmount = swap.getOutput().amount;
155
+ return [4 /*yield*/, swap.getOutput().usdValue()];
156
+ case 4:
157
+ outputValueInUsd = _a.sent();
158
+ //Initiate the swap, this will prompt a Solana transaction, as we need to open the BTC swap address
159
+ return [4 /*yield*/, swap.commit()];
160
+ case 5:
161
+ //Initiate the swap, this will prompt a Solana transaction, as we need to open the BTC swap address
162
+ _a.sent();
163
+ qrCodeData = swap.getQrData();
164
+ bitcoinAddress = swap.getBitcoinAddress();
165
+ timeout = swap.getTimeoutTime();
166
+ console.log("Please send exactly " + inputTokenAmount + " BTC to " + bitcoinAddress);
167
+ //Waits for bitcoin transaction to be received
168
+ return [4 /*yield*/, swap.waitForBitcoinTransaction(null, null, function (txId, //Transaction ID received
169
+ confirmations, //Current confirmation count of the transaction
170
+ targetConfirmations, //Required confirmations for the transaction to be accepted
171
+ transactionETAms //Estimated time in milliseconds till the transaction is accepted
172
+ ) {
173
+ //This callback receives periodic updates about the incoming transaction
174
+ console.log("Tx received: " + txId + " confirmations: " + confirmations + "/" + targetConfirmations + " ETA: " + transactionETAms + " ms");
175
+ })];
176
+ case 6:
177
+ //Waits for bitcoin transaction to be received
178
+ _a.sent(); //This returns as soon as the transaction is accepted
179
+ _a.label = 7;
180
+ case 7:
181
+ _a.trys.push([7, 9, , 11]);
182
+ return [4 /*yield*/, swap.waitTillClaimed((0, __1.timeoutSignal)(30 * 1000))];
183
+ case 8:
184
+ _a.sent();
185
+ return [3 /*break*/, 11];
186
+ case 9:
187
+ e_1 = _a.sent();
188
+ //Claim ourselves when automatic claim doesn't happen in 30 seconds
189
+ return [4 /*yield*/, swap.claim()];
190
+ case 10:
191
+ //Claim ourselves when automatic claim doesn't happen in 30 seconds
192
+ _a.sent();
193
+ return [3 /*break*/, 11];
194
+ case 11: return [2 /*return*/];
195
+ }
196
+ });
197
+ });
198
+ }
199
+ function main() {
200
+ return __awaiter(this, void 0, void 0, function () {
201
+ return __generator(this, function (_a) {
202
+ return [2 /*return*/];
203
+ });
204
+ });
205
+ }
206
+ main();
@@ -1,120 +1,150 @@
1
- import {SolanaKeypairWallet, SolanaSigner, SolanaSwapperWithSigner, MultichainSwapper, Tokens} from "../";
2
- import {Keypair} from "@solana/web3.js";
3
- import * as BN from "bn.js";
4
- import {FileSystemStorageManager} from "@atomiqlabs/sdk-lib/dist/fs-storage";
5
-
6
- const solanaRpc = "https://api.mainnet-beta.solana.com";
7
-
8
- let solanaSwapper: SolanaSwapperWithSigner;
9
-
10
- async function setupSwapper() {
11
- //Setup the multichain swapper
12
- const swapper: MultichainSwapper = new MultichainSwapper({
13
- chains: {
14
- SOLANA: {
15
- rpcUrl: solanaRpc
16
- }
17
- },
18
- //The following line is important for running on backend node.js,
19
- // because the SDK by default uses browser's Indexed DB
20
- storageCtor: (name: string) => new FileSystemStorageManager(name)
21
- });
22
- await swapper.init();
23
-
24
- //Create new random keypair wallet
25
- const wallet = new SolanaKeypairWallet(Keypair.generate()); //This is just a dummy, you should load the wallet from file, or etc.
26
-
27
- const signer: SolanaSigner = new SolanaSigner(wallet);
28
- //Extract a Solana specific swapper (used for swapping between Solana and Bitcoin) with a defined signer
29
- solanaSwapper = swapper.withChain("SOLANA").withSigner(signer);
30
- }
31
-
32
- async function createToBtcSwap() {
33
- const exactIn = false; //exactIn = false, so we specify the output amount
34
- const amount = new BN(10000); //Amount in BTC base units - sats
35
- const recipientBtcAddress = "bc1qtw67hj77rt8zrkkg3jgngutu0yfgt9czjwusxt"; //BTC address of the recipient
36
-
37
- const swap = await solanaSwapper.create(
38
- Tokens.SOLANA.SOL,
39
- Tokens.BITCOIN.BTC,
40
- amount,
41
- exactIn,
42
- recipientBtcAddress
43
- );
44
-
45
- //Input amounts
46
- const inputTokenAmount = swap.getInput().amount;
47
- const inputValueInUsd = await swap.getInput().usdValue();
48
-
49
- //Output amounts
50
- const outputTokenAmount = swap.getOutput().amount;
51
- const outputValueInUsd = await swap.getOutput().usdValue();
52
-
53
- //Initiate the swap by locking up the SOL
54
- await swap.commit();
55
- //Wait for bitcoin payout to happen
56
- const paymentSuccess = await swap.waitForPayment();
57
- if(paymentSuccess) {
58
- //Payment was successful, we can get the transaction id
59
- const bitcoinTxId = swap.getBitcoinTxId();
60
- } else {
61
- //If payment is unsuccessful we can refund and get our funds back
62
- await swap.refund();
63
- }
64
- }
65
-
66
- async function createFromBtcSwap() {
67
- const fromToken = Tokens.BITCOIN.BTC;
68
- const toToken = Tokens.SOLANA.SOL;
69
- const exactIn = true; //exactIn = true, so we specify the input amount
70
- const amount = new BN(10000); //Amount in BTC base units - sats
71
-
72
- const swap = await solanaSwapper.create(
73
- fromToken,
74
- toToken,
75
- amount,
76
- exactIn
77
- );
78
-
79
- //Input amounts
80
- const inputTokenAmount = swap.getInput().amount; //Human readable input token amount with decimals
81
- const inputValueInUsd = await swap.getInput().usdValue(); //Fetches the USD value of the input
82
-
83
- //Output amounts
84
- const outputTokenAmount = swap.getOutput().amount; //Human readable output token amount with decimals
85
- const outputValueInUsd = await swap.getOutput().usdValue(); //Fetches the USD value of the output
86
-
87
- //Initiate the swap, this will prompt a Solana transaction, as we need to open the BTC swap address
88
- await swap.commit();
89
-
90
- const qrCodeData = swap.getQrData(); //Data that can be displayed as QR code - URL with the address and amount
91
- const bitcoinAddress = swap.getBitcoinAddress(); //Bitcoin address to send the BTC to - exact amount needs to be sent!
92
- const timeout = swap.getTimeoutTime(); //The BTC should be sent before the timeout
93
-
94
- console.log("Please send exactly "+inputTokenAmount+" BTC to "+bitcoinAddress);
95
-
96
- //Waits for bitcoin transaction to be received
97
- await swap.waitForBitcoinTransaction(
98
- null, null,
99
- (
100
- txId: string, //Transaction ID received
101
- confirmations: number, //Current confirmation count of the transaction
102
- targetConfirmations: number, //Required confirmations for the transaction to be accepted
103
- transactionETAms: number //Estimated time in milliseconds till the transaction is accepted
104
- ) => {
105
- //This callback receives periodic updates about the incoming transaction
106
- console.log("Tx received: "+txId+" confirmations: "+confirmations+"/"+targetConfirmations+" ETA: "+transactionETAms+" ms");
107
- }
108
- ); //This returns as soon as the transaction is accepted
109
-
110
- //Swap will get automatically claimed by the watchtowers
111
- await swap.waitTillClaimed();
112
- }
113
-
114
- async function main() {
115
- await setupSwapper();
116
- // await createToBtcSwap();
117
- // await createFromBtcSwap();
118
- }
119
-
120
- main();
1
+ import {fromHumanReadableString, SwapperFactory, timeoutSignal} from "../";
2
+ import {FileSystemStorageManager} from "@atomiqlabs/sdk-lib/dist/fs-storage";
3
+ import {StarknetInitializer, StarknetInitializerType} from "@atomiqlabs/chain-starknet";
4
+ import {SolanaInitializer, SolanaInitializerType} from "@atomiqlabs/chain-solana";
5
+ import {IndexedDBUnifiedStorage} from "@atomiqlabs/sdk-lib";
6
+
7
+ const solanaRpc = "https://api.mainnet-beta.solana.com";
8
+ const starknetRpc = "https://starknet-mainnet.public.blastapi.io/rpc/v0_7";
9
+
10
+ //We initialize a swapper factory, this is important such that we can pick and choose which chains
11
+ // we want to support and only install those specific libraries, here Solana & Starknet are used
12
+ //NOTE: The "as const" keyword is important here as to let typescript properly infer the
13
+ // generic type of the SwapperFactory, allowing you to have code-completion for Tokens and TokenResolver
14
+ const Factory = new SwapperFactory<[SolanaInitializerType, StarknetInitializerType]>([SolanaInitializer, StarknetInitializer] as const);
15
+ const Tokens = Factory.Tokens;
16
+
17
+ async function setupSwapper() {
18
+ //Setup the multichain swapper
19
+ const swapper = Factory.newSwapper({
20
+ chains: {
21
+ SOLANA: {
22
+ rpcUrl: solanaRpc
23
+ },
24
+ STARKNET: {
25
+ rpcUrl: starknetRpc
26
+ }
27
+ },
28
+ //The following line is important for running on backend node.js,
29
+ // because the SDK by default uses browser's Indexed DB, which is not available in node
30
+ swapStorage: (chainId: string) => null,
31
+ noEvents: true,
32
+ noTimers: true,
33
+ dontCheckPastSwaps: true,
34
+ dontFetchLPs: true
35
+ });
36
+ //Initialize the swapper
37
+ await swapper.init();
38
+
39
+ //Extract a Solana specific swapper (used for swapping between Solana and Bitcoin)
40
+ const solanaSwapper = swapper.withChain<"SOLANA">("SOLANA");
41
+
42
+ //Create new random keypair wallet
43
+ const signer = solanaSwapper.randomSigner(); //This is just a dummy, you should load the wallet from file, or etc.
44
+ //Or in React, using solana wallet adapter
45
+ //const signer = new SolanaKeypairWallet(useAnchorWallet());
46
+
47
+ //Extract a swapper with a defined signer
48
+ return solanaSwapper.withSigner(signer);
49
+ }
50
+
51
+ async function createToBtcSwap() {
52
+ //In real use-cases you would setup the swapper just once, not for every swap!
53
+ const solanaSwapper = await setupSwapper();
54
+
55
+ const fromToken = Tokens.SOLANA.SOL;
56
+ const toToken = Tokens.BITCOIN.BTC;
57
+ const exactIn = false; //exactIn = false, so we specify the output amount
58
+ const amount = fromHumanReadableString("0.0001", toToken); //Amount in BTC base units - sats, you can also use fromHumanReadable helper methods
59
+ const recipientBtcAddress = "bc1qtw67hj77rt8zrkkg3jgngutu0yfgt9czjwusxt"; //BTC address of the recipient
60
+
61
+ const swap = await solanaSwapper.create(
62
+ fromToken,
63
+ toToken,
64
+ amount,
65
+ exactIn,
66
+ recipientBtcAddress
67
+ );
68
+
69
+ //Input amounts
70
+ const inputTokenAmount = swap.getInput().amount;
71
+ const inputValueInUsd = await swap.getInput().usdValue();
72
+
73
+ //Output amounts
74
+ const outputTokenAmount = swap.getOutput().amount;
75
+ const outputValueInUsd = await swap.getOutput().usdValue();
76
+
77
+ //Initiate the swap by locking up the SOL
78
+ await swap.commit();
79
+ //Wait for bitcoin payout to happen
80
+ const paymentSuccess = await swap.waitForPayment();
81
+ if(paymentSuccess) {
82
+ //Payment was successful, we can get the transaction id
83
+ const bitcoinTxId = swap.getBitcoinTxId();
84
+ } else {
85
+ //If payment is unsuccessful we can refund and get our funds back
86
+ await swap.refund();
87
+ }
88
+ }
89
+
90
+ async function createFromBtcSwap() {
91
+ const solanaSwapper = await setupSwapper();
92
+
93
+ const fromToken = Tokens.BITCOIN.BTC;
94
+ const toToken = Tokens.SOLANA.SOL;
95
+ const exactIn = true; //exactIn = true, so we specify the input amount
96
+ const amount = BigInt(10000); //Amount in BTC base units - sats
97
+
98
+ const swap = await solanaSwapper.create(
99
+ fromToken,
100
+ toToken,
101
+ amount,
102
+ exactIn
103
+ );
104
+
105
+ //Input amounts
106
+ const inputTokenAmount = swap.getInput().amount; //Human readable input token amount with decimals
107
+ const inputValueInUsd = await swap.getInput().usdValue(); //Fetches the USD value of the input
108
+
109
+ //Output amounts
110
+ const outputTokenAmount = swap.getOutput().amount; //Human readable output token amount with decimals
111
+ const outputValueInUsd = await swap.getOutput().usdValue(); //Fetches the USD value of the output
112
+
113
+ //Initiate the swap, this will prompt a Solana transaction, as we need to open the BTC swap address
114
+ await swap.commit();
115
+
116
+ const qrCodeData = swap.getQrData(); //Data that can be displayed as QR code - URL with the address and amount
117
+ const bitcoinAddress = swap.getBitcoinAddress(); //Bitcoin address to send the BTC to - exact amount needs to be sent!
118
+ const timeout = swap.getTimeoutTime(); //The BTC should be sent before the timeout
119
+
120
+ console.log("Please send exactly "+inputTokenAmount+" BTC to "+bitcoinAddress);
121
+
122
+ //Waits for bitcoin transaction to be received
123
+ await swap.waitForBitcoinTransaction(
124
+ null, null,
125
+ (
126
+ txId: string, //Transaction ID received
127
+ confirmations: number, //Current confirmation count of the transaction
128
+ targetConfirmations: number, //Required confirmations for the transaction to be accepted
129
+ transactionETAms: number //Estimated time in milliseconds till the transaction is accepted
130
+ ) => {
131
+ //This callback receives periodic updates about the incoming transaction
132
+ console.log("Tx received: "+txId+" confirmations: "+confirmations+"/"+targetConfirmations+" ETA: "+transactionETAms+" ms");
133
+ }
134
+ ); //This returns as soon as the transaction is accepted
135
+
136
+ //Swap should get automatically claimed by the watchtowers, if not we can call swap.claim()
137
+ try {
138
+ await swap.waitTillClaimed(timeoutSignal(30*1000));
139
+ } catch (e) {
140
+ //Claim ourselves when automatic claim doesn't happen in 30 seconds
141
+ await swap.claim();
142
+ }
143
+ }
144
+
145
+ async function main() {
146
+ // await createToBtcSwap();
147
+ // await createFromBtcSwap();
148
+ }
149
+
150
+ main();
@@ -0,0 +1,71 @@
1
+ import {StorageObject, IStorageManager} from "@atomiqlabs/base";
2
+ import * as fs from "fs/promises";
3
+
4
+ /**
5
+ * StorageManager using local filesystem to persists data, creates a new file for every save object
6
+ */
7
+ export class FileSystemStorageManager<T extends StorageObject> implements IStorageManager<T> {
8
+
9
+ private readonly directory: string;
10
+ data: {
11
+ [key: string]: T
12
+ } = {};
13
+
14
+ constructor(directory: string) {
15
+ this.directory = directory;
16
+ }
17
+
18
+ async init(): Promise<void> {
19
+ try {
20
+ await fs.mkdir(this.directory);
21
+ } catch (e) {}
22
+ }
23
+
24
+ async saveData(hash: string, object: T): Promise<void> {
25
+
26
+ try {
27
+ await fs.mkdir(this.directory)
28
+ } catch (e) {}
29
+
30
+ this.data[hash] = object;
31
+
32
+ const cpy = object.serialize();
33
+
34
+ await fs.writeFile(this.directory+"/"+hash+".json", JSON.stringify(cpy));
35
+
36
+ }
37
+
38
+ async removeData(hash: string): Promise<void> {
39
+ const paymentHash = hash;
40
+ try {
41
+ if(this.data[paymentHash]!=null) delete this.data[paymentHash];
42
+ await fs.rm(this.directory+"/"+paymentHash+".json");
43
+ } catch (e) {
44
+ console.error("FileSystemStorageManager: removeData(): Error: ", e);
45
+ }
46
+ }
47
+
48
+ async loadData(type: new(data: any) => T): Promise<T[]> {
49
+ let files;
50
+ try {
51
+ files = await fs.readdir(this.directory);
52
+ } catch (e) {
53
+ console.error("FileSystemStorageManager: loadData(): Error: ", e);
54
+ return [];
55
+ }
56
+
57
+ const arr = [];
58
+
59
+ for(let file of files) {
60
+ const paymentHash = file.split(".")[0];
61
+ const result = await fs.readFile(this.directory+"/"+file);
62
+ const obj = JSON.parse(result.toString());
63
+ const parsed = new type(obj);
64
+ arr.push(parsed);
65
+ this.data[paymentHash] = parsed;
66
+ }
67
+
68
+ return arr;
69
+ }
70
+
71
+ }
@@ -0,0 +1 @@
1
+ export * from "./FileSystemStorageManager";
package/src/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("@atomiqlabs/base"), exports);
18
+ __exportStar(require("@atomiqlabs/sdk-lib"), exports);
19
+ __exportStar(require("./SwapperFactory"), exports);
20
+ __exportStar(require("./Utils"), exports);
21
+ __exportStar(require("./storage/LocalStorageManager"), exports);
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
- export * from "./MultichainSwapper";
2
- export * from "@atomiqlabs/base";
3
- export * from "@atomiqlabs/sdk-lib";
4
- export * from "@atomiqlabs/chain-solana";
1
+ export * from "@atomiqlabs/base";
2
+ export * from "@atomiqlabs/sdk-lib";
3
+ export * from "./SwapperFactory";
4
+ export * from "./Utils";
5
+ export * from "./storage/LocalStorageManager";