@atomiqlabs/chain-starknet 1.0.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 (136) hide show
  1. package/LICENSE +201 -0
  2. package/dist/get_serialized_block.d.ts +1 -0
  3. package/dist/get_serialized_block.js +28 -0
  4. package/dist/index.d.ts +34 -0
  5. package/dist/index.js +50 -0
  6. package/dist/starknet/StarknetChainType.d.ts +9 -0
  7. package/dist/starknet/StarknetChainType.js +2 -0
  8. package/dist/starknet/StarknetInitializer.d.ts +18 -0
  9. package/dist/starknet/StarknetInitializer.js +49 -0
  10. package/dist/starknet/base/StarknetAction.d.ts +27 -0
  11. package/dist/starknet/base/StarknetAction.js +73 -0
  12. package/dist/starknet/base/StarknetBase.d.ts +34 -0
  13. package/dist/starknet/base/StarknetBase.js +29 -0
  14. package/dist/starknet/base/StarknetModule.d.ts +14 -0
  15. package/dist/starknet/base/StarknetModule.js +13 -0
  16. package/dist/starknet/base/modules/ERC20Abi.d.ts +755 -0
  17. package/dist/starknet/base/modules/ERC20Abi.js +1032 -0
  18. package/dist/starknet/base/modules/StarknetAccounts.d.ts +6 -0
  19. package/dist/starknet/base/modules/StarknetAccounts.js +24 -0
  20. package/dist/starknet/base/modules/StarknetAddresses.d.ts +9 -0
  21. package/dist/starknet/base/modules/StarknetAddresses.js +26 -0
  22. package/dist/starknet/base/modules/StarknetBlocks.d.ts +19 -0
  23. package/dist/starknet/base/modules/StarknetBlocks.js +49 -0
  24. package/dist/starknet/base/modules/StarknetEvents.d.ts +44 -0
  25. package/dist/starknet/base/modules/StarknetEvents.js +88 -0
  26. package/dist/starknet/base/modules/StarknetFees.d.ts +55 -0
  27. package/dist/starknet/base/modules/StarknetFees.js +102 -0
  28. package/dist/starknet/base/modules/StarknetSignatures.d.ts +30 -0
  29. package/dist/starknet/base/modules/StarknetSignatures.js +71 -0
  30. package/dist/starknet/base/modules/StarknetTokens.d.ts +67 -0
  31. package/dist/starknet/base/modules/StarknetTokens.js +97 -0
  32. package/dist/starknet/base/modules/StarknetTransactions.d.ts +87 -0
  33. package/dist/starknet/base/modules/StarknetTransactions.js +226 -0
  34. package/dist/starknet/btcrelay/BtcRelayAbi.d.ts +250 -0
  35. package/dist/starknet/btcrelay/BtcRelayAbi.js +341 -0
  36. package/dist/starknet/btcrelay/StarknetBtcRelay.d.ts +166 -0
  37. package/dist/starknet/btcrelay/StarknetBtcRelay.js +323 -0
  38. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.d.ts +32 -0
  39. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.js +74 -0
  40. package/dist/starknet/btcrelay/headers/StarknetBtcStoredHeader.d.ts +52 -0
  41. package/dist/starknet/btcrelay/headers/StarknetBtcStoredHeader.js +113 -0
  42. package/dist/starknet/contract/StarknetContractBase.d.ts +13 -0
  43. package/dist/starknet/contract/StarknetContractBase.js +18 -0
  44. package/dist/starknet/contract/modules/StarknetContractEvents.d.ts +40 -0
  45. package/dist/starknet/contract/modules/StarknetContractEvents.js +77 -0
  46. package/dist/starknet/events/StarknetChainEvents.d.ts +19 -0
  47. package/dist/starknet/events/StarknetChainEvents.js +51 -0
  48. package/dist/starknet/events/StarknetChainEventsBrowser.d.ts +73 -0
  49. package/dist/starknet/events/StarknetChainEventsBrowser.js +210 -0
  50. package/dist/starknet/swaps/EscrowManagerAbi.d.ts +445 -0
  51. package/dist/starknet/swaps/EscrowManagerAbi.js +601 -0
  52. package/dist/starknet/swaps/StarknetSwapContract.d.ts +215 -0
  53. package/dist/starknet/swaps/StarknetSwapContract.js +452 -0
  54. package/dist/starknet/swaps/StarknetSwapData.d.ts +74 -0
  55. package/dist/starknet/swaps/StarknetSwapData.js +316 -0
  56. package/dist/starknet/swaps/StarknetSwapModule.d.ts +9 -0
  57. package/dist/starknet/swaps/StarknetSwapModule.js +12 -0
  58. package/dist/starknet/swaps/handlers/IHandler.d.ts +13 -0
  59. package/dist/starknet/swaps/handlers/IHandler.js +2 -0
  60. package/dist/starknet/swaps/handlers/claim/ClaimHandlers.d.ts +13 -0
  61. package/dist/starknet/swaps/handlers/claim/ClaimHandlers.js +13 -0
  62. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.d.ts +22 -0
  63. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.js +44 -0
  64. package/dist/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.d.ts +25 -0
  65. package/dist/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.js +48 -0
  66. package/dist/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.d.ts +26 -0
  67. package/dist/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.js +40 -0
  68. package/dist/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.d.ts +20 -0
  69. package/dist/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.js +29 -0
  70. package/dist/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.d.ts +64 -0
  71. package/dist/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.js +86 -0
  72. package/dist/starknet/swaps/handlers/refund/TimelockRefundHandler.d.ts +17 -0
  73. package/dist/starknet/swaps/handlers/refund/TimelockRefundHandler.js +27 -0
  74. package/dist/starknet/swaps/modules/StarknetLpVault.d.ts +69 -0
  75. package/dist/starknet/swaps/modules/StarknetLpVault.js +122 -0
  76. package/dist/starknet/swaps/modules/StarknetSwapClaim.d.ts +53 -0
  77. package/dist/starknet/swaps/modules/StarknetSwapClaim.js +100 -0
  78. package/dist/starknet/swaps/modules/StarknetSwapInit.d.ts +84 -0
  79. package/dist/starknet/swaps/modules/StarknetSwapInit.js +164 -0
  80. package/dist/starknet/swaps/modules/StarknetSwapRefund.d.ts +64 -0
  81. package/dist/starknet/swaps/modules/StarknetSwapRefund.js +131 -0
  82. package/dist/starknet/swaps/modules/SwapClaim.d.ts +54 -0
  83. package/dist/starknet/swaps/modules/SwapClaim.js +115 -0
  84. package/dist/starknet/swaps/modules/SwapInit.d.ts +79 -0
  85. package/dist/starknet/swaps/modules/SwapInit.js +174 -0
  86. package/dist/starknet/swaps/modules/SwapRefund.d.ts +63 -0
  87. package/dist/starknet/swaps/modules/SwapRefund.js +149 -0
  88. package/dist/starknet/wallet/StarknetKeypairWallet.d.ts +6 -0
  89. package/dist/starknet/wallet/StarknetKeypairWallet.js +26 -0
  90. package/dist/starknet/wallet/StarknetSigner.d.ts +12 -0
  91. package/dist/starknet/wallet/StarknetSigner.js +46 -0
  92. package/dist/utils/Utils.d.ts +38 -0
  93. package/dist/utils/Utils.js +255 -0
  94. package/package.json +39 -0
  95. package/src/index.ts +41 -0
  96. package/src/starknet/StarknetChainType.ts +20 -0
  97. package/src/starknet/StarknetInitializer.ts +75 -0
  98. package/src/starknet/base/StarknetAction.ts +90 -0
  99. package/src/starknet/base/StarknetBase.ts +56 -0
  100. package/src/starknet/base/StarknetModule.ts +20 -0
  101. package/src/starknet/base/modules/ERC20Abi.ts +1029 -0
  102. package/src/starknet/base/modules/StarknetAccounts.ts +26 -0
  103. package/src/starknet/base/modules/StarknetAddresses.ts +23 -0
  104. package/src/starknet/base/modules/StarknetBlocks.ts +59 -0
  105. package/src/starknet/base/modules/StarknetEvents.ts +105 -0
  106. package/src/starknet/base/modules/StarknetFees.ts +136 -0
  107. package/src/starknet/base/modules/StarknetSignatures.ts +91 -0
  108. package/src/starknet/base/modules/StarknetTokens.ts +116 -0
  109. package/src/starknet/base/modules/StarknetTransactions.ts +254 -0
  110. package/src/starknet/btcrelay/BtcRelayAbi.ts +338 -0
  111. package/src/starknet/btcrelay/StarknetBtcRelay.ts +415 -0
  112. package/src/starknet/btcrelay/headers/StarknetBtcHeader.ts +101 -0
  113. package/src/starknet/btcrelay/headers/StarknetBtcStoredHeader.ts +142 -0
  114. package/src/starknet/contract/StarknetContractBase.ts +29 -0
  115. package/src/starknet/contract/modules/StarknetContractEvents.ts +108 -0
  116. package/src/starknet/events/StarknetChainEvents.ts +63 -0
  117. package/src/starknet/events/StarknetChainEventsBrowser.ts +289 -0
  118. package/src/starknet/swaps/EscrowManagerAbi.ts +600 -0
  119. package/src/starknet/swaps/StarknetSwapContract.ts +694 -0
  120. package/src/starknet/swaps/StarknetSwapData.ts +441 -0
  121. package/src/starknet/swaps/StarknetSwapModule.ts +17 -0
  122. package/src/starknet/swaps/handlers/IHandler.ts +20 -0
  123. package/src/starknet/swaps/handlers/claim/ClaimHandlers.ts +23 -0
  124. package/src/starknet/swaps/handlers/claim/HashlockClaimHandler.ts +54 -0
  125. package/src/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.ts +73 -0
  126. package/src/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.ts +67 -0
  127. package/src/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.ts +49 -0
  128. package/src/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.ts +151 -0
  129. package/src/starknet/swaps/handlers/refund/TimelockRefundHandler.ts +39 -0
  130. package/src/starknet/swaps/modules/StarknetLpVault.ts +148 -0
  131. package/src/starknet/swaps/modules/StarknetSwapClaim.ts +142 -0
  132. package/src/starknet/swaps/modules/StarknetSwapInit.ts +226 -0
  133. package/src/starknet/swaps/modules/StarknetSwapRefund.ts +202 -0
  134. package/src/starknet/wallet/StarknetKeypairWallet.ts +34 -0
  135. package/src/starknet/wallet/StarknetSigner.ts +55 -0
  136. package/src/utils/Utils.ts +247 -0
@@ -0,0 +1,20 @@
1
+ import { StarknetSwapData } from "../../../StarknetSwapData";
2
+ import { StarknetGas } from "../../../../base/StarknetAction";
3
+ import { ChainSwapType } from "@atomiqlabs/base";
4
+ import { BigNumberish } from "starknet";
5
+ import { StarknetTx } from "../../../../base/modules/StarknetTransactions";
6
+ import { BitcoinCommitmentData, BitcoinWitnessData, IBitcoinClaimHandler } from "./IBitcoinClaimHandler";
7
+ export type BitcoinTxIdCommitmentData = {
8
+ txId: string;
9
+ };
10
+ export declare class BitcoinTxIdClaimHandler extends IBitcoinClaimHandler<BitcoinTxIdCommitmentData, BitcoinWitnessData> {
11
+ static readonly type: ChainSwapType;
12
+ static readonly gas: StarknetGas;
13
+ protected serializeCommitment(data: BitcoinTxIdCommitmentData & BitcoinCommitmentData): BigNumberish[];
14
+ getWitness(signer: string, swapData: StarknetSwapData, witnessData: BitcoinWitnessData, feeRate?: string): Promise<{
15
+ initialTxns: StarknetTx[];
16
+ witness: BigNumberish[];
17
+ }>;
18
+ getGas(data: StarknetSwapData): StarknetGas;
19
+ getType(): ChainSwapType;
20
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BitcoinTxIdClaimHandler = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const Utils_1 = require("../../../../../utils/Utils");
6
+ const IBitcoinClaimHandler_1 = require("./IBitcoinClaimHandler");
7
+ const logger = (0, Utils_1.getLogger)("BitcoinTxIdClaimHandler: ");
8
+ class BitcoinTxIdClaimHandler extends IBitcoinClaimHandler_1.IBitcoinClaimHandler {
9
+ serializeCommitment(data) {
10
+ return [
11
+ ...(0, Utils_1.bufferToU32Array)(Buffer.from(data.txId, "hex").reverse()),
12
+ ...super.serializeCommitment(data)
13
+ ];
14
+ }
15
+ getWitness(signer, swapData, witnessData, feeRate) {
16
+ if (!swapData.isClaimHandler(this.address))
17
+ throw new Error("Invalid claim handler");
18
+ return this._getWitness(signer, swapData, witnessData, { txId: witnessData.tx.txid });
19
+ }
20
+ getGas(data) {
21
+ return BitcoinTxIdClaimHandler.gas;
22
+ }
23
+ getType() {
24
+ return BitcoinTxIdClaimHandler.type;
25
+ }
26
+ }
27
+ exports.BitcoinTxIdClaimHandler = BitcoinTxIdClaimHandler;
28
+ BitcoinTxIdClaimHandler.type = base_1.ChainSwapType.CHAIN_TXID;
29
+ BitcoinTxIdClaimHandler.gas = { l1: 20000 };
@@ -0,0 +1,64 @@
1
+ import { IClaimHandler } from "../ClaimHandlers";
2
+ import { StarknetSwapData } from "../../../StarknetSwapData";
3
+ import { StarknetGas } from "../../../../base/StarknetAction";
4
+ import { ChainSwapType, RelaySynchronizer } from "@atomiqlabs/base";
5
+ import { BigNumberish } from "starknet";
6
+ import { StarknetBtcStoredHeader } from "../../../../btcrelay/headers/StarknetBtcStoredHeader";
7
+ import { StarknetTx } from "../../../../base/modules/StarknetTransactions";
8
+ import { StarknetBtcRelay } from "../../../../btcrelay/StarknetBtcRelay";
9
+ export type BitcoinCommitmentData = {
10
+ btcRelay: StarknetBtcRelay<any>;
11
+ confirmations: number;
12
+ };
13
+ export type BitcoinWitnessData = {
14
+ tx: {
15
+ blockhash: string;
16
+ confirmations: number;
17
+ txid: string;
18
+ hex: string;
19
+ height: number;
20
+ };
21
+ requiredConfirmations: number;
22
+ commitedHeader?: StarknetBtcStoredHeader;
23
+ btcRelay?: StarknetBtcRelay<any>;
24
+ synchronizer?: RelaySynchronizer<StarknetBtcStoredHeader, StarknetTx, any>;
25
+ };
26
+ export declare abstract class IBitcoinClaimHandler<C, W extends BitcoinWitnessData> implements IClaimHandler<C & BitcoinCommitmentData, W> {
27
+ readonly address: string;
28
+ constructor(address: string);
29
+ /**
30
+ * Gets committed header, identified by blockhash & blockheight, determines required BTC relay blockheight based on
31
+ * requiredConfirmations
32
+ * If synchronizer is passed & blockhash is not found, it produces transactions to sync up the btc relay to the
33
+ * current chain tip & adds them to the txs array
34
+ *
35
+ * @param signer
36
+ * @param btcRelay
37
+ * @param txBlockheight transaction blockheight
38
+ * @param requiredConfirmations required confirmation for the swap to be claimable with that TX
39
+ * @param blockhash blockhash of the block which includes the transaction
40
+ * @param txs solana transaction array, in case we need to synchronize the btc relay ourselves the synchronization
41
+ * txns are added here
42
+ * @param synchronizer optional synchronizer to use to synchronize the btc relay in case it is not yet synchronized
43
+ * to the required blockheight
44
+ * @param feeRate Fee rate to use for synchronization transactions
45
+ * @private
46
+ */
47
+ protected getCommitedHeaderAndSynchronize(signer: string, btcRelay: StarknetBtcRelay<any>, txBlockheight: number, requiredConfirmations: number, blockhash: string, txs: StarknetTx[], synchronizer?: RelaySynchronizer<StarknetBtcStoredHeader, StarknetTx, any>, feeRate?: string): Promise<StarknetBtcStoredHeader>;
48
+ static readonly address = "";
49
+ static readonly type: ChainSwapType;
50
+ static readonly gas: StarknetGas;
51
+ protected serializeCommitment(data: BitcoinCommitmentData): BigNumberish[];
52
+ getCommitment(data: C & BitcoinCommitmentData): BigNumberish;
53
+ protected _getWitness(signer: string, swapData: StarknetSwapData, { tx, btcRelay, commitedHeader, synchronizer, requiredConfirmations }: BitcoinWitnessData, commitment: C, feeRate?: string): Promise<{
54
+ initialTxns: StarknetTx[];
55
+ witness: BigNumberish[];
56
+ }>;
57
+ abstract getWitness(signer: string, data: StarknetSwapData, witnessData: W, feeRate?: string): Promise<{
58
+ initialTxns: StarknetTx[];
59
+ witness: BigNumberish[];
60
+ }>;
61
+ abstract getGas(data: StarknetSwapData): StarknetGas;
62
+ abstract getType(): ChainSwapType;
63
+ parseWitnessResult(result: BigNumberish[]): string;
64
+ }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IBitcoinClaimHandler = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const starknet_1 = require("starknet");
6
+ const Utils_1 = require("../../../../../utils/Utils");
7
+ const logger = (0, Utils_1.getLogger)("IBitcoinClaimHandler: ");
8
+ class IBitcoinClaimHandler {
9
+ constructor(address) {
10
+ this.address = address;
11
+ }
12
+ /**
13
+ * Gets committed header, identified by blockhash & blockheight, determines required BTC relay blockheight based on
14
+ * requiredConfirmations
15
+ * If synchronizer is passed & blockhash is not found, it produces transactions to sync up the btc relay to the
16
+ * current chain tip & adds them to the txs array
17
+ *
18
+ * @param signer
19
+ * @param btcRelay
20
+ * @param txBlockheight transaction blockheight
21
+ * @param requiredConfirmations required confirmation for the swap to be claimable with that TX
22
+ * @param blockhash blockhash of the block which includes the transaction
23
+ * @param txs solana transaction array, in case we need to synchronize the btc relay ourselves the synchronization
24
+ * txns are added here
25
+ * @param synchronizer optional synchronizer to use to synchronize the btc relay in case it is not yet synchronized
26
+ * to the required blockheight
27
+ * @param feeRate Fee rate to use for synchronization transactions
28
+ * @private
29
+ */
30
+ async getCommitedHeaderAndSynchronize(signer, btcRelay, txBlockheight, requiredConfirmations, blockhash, txs, synchronizer, feeRate) {
31
+ const requiredBlockheight = txBlockheight + requiredConfirmations - 1;
32
+ const result = await (0, Utils_1.tryWithRetries)(() => btcRelay.retrieveLogAndBlockheight({
33
+ blockhash: blockhash
34
+ }, requiredBlockheight));
35
+ if (result != null)
36
+ return result.header;
37
+ //Need to synchronize
38
+ if (synchronizer == null)
39
+ return null;
40
+ //TODO: We don't have to synchronize to tip, only to our required blockheight
41
+ const resp = await synchronizer.syncToLatestTxs(signer.toString(), feeRate);
42
+ logger.debug("getCommitedHeaderAndSynchronize(): BTC Relay not synchronized to required blockheight, " +
43
+ "synchronizing ourselves in " + resp.txs.length + " txs");
44
+ logger.debug("getCommitedHeaderAndSynchronize(): BTC Relay computed header map: ", resp.computedHeaderMap);
45
+ resp.txs.forEach(tx => txs.push(tx));
46
+ //Retrieve computed header
47
+ return resp.computedHeaderMap[txBlockheight];
48
+ }
49
+ serializeCommitment(data) {
50
+ return [
51
+ data.confirmations,
52
+ data.btcRelay.contract.address
53
+ ];
54
+ }
55
+ getCommitment(data) {
56
+ return starknet_1.hash.computePoseidonHashOnElements(this.serializeCommitment(data));
57
+ }
58
+ async _getWitness(signer, swapData, { tx, btcRelay, commitedHeader, synchronizer, requiredConfirmations }, commitment, feeRate) {
59
+ const serializedData = this.serializeCommitment({
60
+ ...commitment,
61
+ btcRelay,
62
+ confirmations: requiredConfirmations
63
+ });
64
+ const commitmentHash = starknet_1.hash.computePoseidonHashOnElements(serializedData);
65
+ if (!swapData.isClaimData(commitmentHash))
66
+ throw new Error("Invalid commit data");
67
+ const merkleProof = await btcRelay.bitcoinRpc.getMerkleProof(tx.txid, tx.blockhash);
68
+ logger.debug("getWitness(): merkle proof computed: ", merkleProof);
69
+ const txs = [];
70
+ if (commitedHeader == null)
71
+ commitedHeader = await this.getCommitedHeaderAndSynchronize(signer, btcRelay, tx.height, requiredConfirmations, tx.blockhash, txs, synchronizer, feeRate);
72
+ if (commitedHeader == null)
73
+ throw new Error("Cannot fetch committed header!");
74
+ serializedData.push(...commitedHeader.serialize());
75
+ serializedData.push(merkleProof.merkle.length, ...merkleProof.merkle.map(Utils_1.bufferToU32Array).flat());
76
+ serializedData.push(merkleProof.pos);
77
+ return { initialTxns: txs, witness: serializedData };
78
+ }
79
+ parseWitnessResult(result) {
80
+ return (0, Utils_1.u32ArrayToBuffer)(result).toString("hex");
81
+ }
82
+ }
83
+ exports.IBitcoinClaimHandler = IBitcoinClaimHandler;
84
+ IBitcoinClaimHandler.address = "";
85
+ IBitcoinClaimHandler.type = base_1.ChainSwapType.CHAIN_TXID;
86
+ IBitcoinClaimHandler.gas = { l1: 20000 };
@@ -0,0 +1,17 @@
1
+ import { StarknetTx } from "../../../base/modules/StarknetTransactions";
2
+ import { StarknetSwapData } from "../../StarknetSwapData";
3
+ import { BigNumberish } from "starknet";
4
+ import { IHandler } from "../IHandler";
5
+ import { StarknetGas } from "../../../base/StarknetAction";
6
+ export declare class TimelockRefundHandler implements IHandler<bigint, never> {
7
+ readonly address: string;
8
+ static readonly gas: StarknetGas;
9
+ constructor(address: string);
10
+ getCommitment(data: bigint): BigNumberish;
11
+ getWitness(signer: string, data: StarknetSwapData): Promise<{
12
+ initialTxns: StarknetTx[];
13
+ witness: BigNumberish[];
14
+ }>;
15
+ getGas(): StarknetGas;
16
+ static getExpiry(data: StarknetSwapData): bigint;
17
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimelockRefundHandler = void 0;
4
+ const Utils_1 = require("../../../../utils/Utils");
5
+ class TimelockRefundHandler {
6
+ constructor(address) {
7
+ this.address = address;
8
+ }
9
+ getCommitment(data) {
10
+ return data;
11
+ }
12
+ getWitness(signer, data) {
13
+ const expiry = TimelockRefundHandler.getExpiry(data);
14
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
15
+ if (expiry > currentTimestamp)
16
+ throw new Error("Not expired yet!");
17
+ return Promise.resolve({ initialTxns: [], witness: [] });
18
+ }
19
+ getGas() {
20
+ return TimelockRefundHandler.gas;
21
+ }
22
+ static getExpiry(data) {
23
+ return (0, Utils_1.bigNumberishToBuffer)(data.refundData, 32).readBigUInt64BE(24);
24
+ }
25
+ }
26
+ exports.TimelockRefundHandler = TimelockRefundHandler;
27
+ TimelockRefundHandler.gas = { l1: 500 };
@@ -0,0 +1,69 @@
1
+ import { IntermediaryReputationType } from "@atomiqlabs/base";
2
+ import { StarknetSwapModule } from "../StarknetSwapModule";
3
+ import { StarknetTx } from "../../base/modules/StarknetTransactions";
4
+ export declare class StarknetLpVault extends StarknetSwapModule {
5
+ private static readonly GasCosts;
6
+ /**
7
+ * Action for withdrawing funds from the LP vault
8
+ *
9
+ * @param signer
10
+ * @param token
11
+ * @param amount
12
+ * @constructor
13
+ * @private
14
+ */
15
+ private Withdraw;
16
+ /**
17
+ * Action for depositing funds to the LP vault
18
+ *
19
+ * @param signer
20
+ * @param token
21
+ * @param amount
22
+ * @constructor
23
+ * @private
24
+ */
25
+ private Deposit;
26
+ /**
27
+ * Returns intermediary's reputation & vault balance for a specific token
28
+ *
29
+ * @param address
30
+ * @param token
31
+ */
32
+ getIntermediaryData(address: string, token: string): Promise<{
33
+ balance: bigint;
34
+ reputation: IntermediaryReputationType;
35
+ }>;
36
+ /**
37
+ * Returns intermediary's reputation for a specific token
38
+ *
39
+ * @param address
40
+ * @param token
41
+ */
42
+ getIntermediaryReputation(address: string, token: string): Promise<IntermediaryReputationType>;
43
+ /**
44
+ * Returns the balance of the token an intermediary has in his LP vault
45
+ *
46
+ * @param address
47
+ * @param token
48
+ */
49
+ getIntermediaryBalance(address: string, token: string): Promise<bigint>;
50
+ /**
51
+ * Creates transactions for withdrawing funds from the LP vault, creates ATA if it doesn't exist and unwraps
52
+ * WSOL to SOL if required
53
+ *
54
+ * @param signer
55
+ * @param token
56
+ * @param amount
57
+ * @param feeRate
58
+ */
59
+ txsWithdraw(signer: string, token: string, amount: bigint, feeRate?: string): Promise<StarknetTx[]>;
60
+ /**
61
+ * Creates transaction for depositing funds into the LP vault, wraps SOL to WSOL if required
62
+ *
63
+ * @param signer
64
+ * @param token
65
+ * @param amount
66
+ * @param feeRate
67
+ */
68
+ txsDeposit(signer: string, token: string, amount: bigint, feeRate?: string): Promise<StarknetTx[]>;
69
+ }
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StarknetLpVault = void 0;
4
+ const Utils_1 = require("../../../utils/Utils");
5
+ const StarknetSwapModule_1 = require("../StarknetSwapModule");
6
+ const StarknetAction_1 = require("../../base/StarknetAction");
7
+ const starknet_1 = require("starknet");
8
+ class StarknetLpVault extends StarknetSwapModule_1.StarknetSwapModule {
9
+ /**
10
+ * Action for withdrawing funds from the LP vault
11
+ *
12
+ * @param signer
13
+ * @param token
14
+ * @param amount
15
+ * @constructor
16
+ * @private
17
+ */
18
+ Withdraw(signer, token, amount) {
19
+ return new StarknetAction_1.StarknetAction(signer, this.root, this.contract.populateTransaction.withdraw(token, starknet_1.cairo.uint256(amount), signer), StarknetLpVault.GasCosts.WITHDRAW);
20
+ }
21
+ /**
22
+ * Action for depositing funds to the LP vault
23
+ *
24
+ * @param signer
25
+ * @param token
26
+ * @param amount
27
+ * @constructor
28
+ * @private
29
+ */
30
+ Deposit(signer, token, amount) {
31
+ return new StarknetAction_1.StarknetAction(signer, this.root, this.contract.populateTransaction.deposit(token, starknet_1.cairo.uint256(amount)), StarknetLpVault.GasCosts.WITHDRAW);
32
+ }
33
+ /**
34
+ * Returns intermediary's reputation & vault balance for a specific token
35
+ *
36
+ * @param address
37
+ * @param token
38
+ */
39
+ async getIntermediaryData(address, token) {
40
+ const [balance, reputation] = await Promise.all([
41
+ this.getIntermediaryBalance(address, token),
42
+ this.getIntermediaryReputation(address, token)
43
+ ]);
44
+ return { balance, reputation };
45
+ }
46
+ /**
47
+ * Returns intermediary's reputation for a specific token
48
+ *
49
+ * @param address
50
+ * @param token
51
+ */
52
+ async getIntermediaryReputation(address, token) {
53
+ const filter = Object.keys(this.root.claimHandlersByAddress).map(claimHandler => starknet_1.cairo.tuple(address, token, claimHandler));
54
+ const rawReputation = await this.provider.callContract(this.contract.populateTransaction.get_reputation(filter));
55
+ const length = (0, Utils_1.toBigInt)(rawReputation.shift());
56
+ if (Number(length) !== filter.length)
57
+ throw new Error("getIntermediaryReputation(): Invalid response length");
58
+ const result = {};
59
+ Object.keys(this.root.claimHandlersByAddress).forEach((address) => {
60
+ const handler = this.root.claimHandlersByAddress[address];
61
+ result[handler.getType()] = {
62
+ successVolume: (0, Utils_1.toBigInt)({ low: rawReputation.shift(), high: rawReputation.shift() }),
63
+ successCount: (0, Utils_1.toBigInt)(rawReputation.shift()),
64
+ coopCloseVolume: (0, Utils_1.toBigInt)({ low: rawReputation.shift(), high: rawReputation.shift() }),
65
+ coopCloseCount: (0, Utils_1.toBigInt)(rawReputation.shift()),
66
+ failVolume: (0, Utils_1.toBigInt)({ low: rawReputation.shift(), high: rawReputation.shift() }),
67
+ failCount: (0, Utils_1.toBigInt)(rawReputation.shift()),
68
+ };
69
+ });
70
+ return result;
71
+ }
72
+ /**
73
+ * Returns the balance of the token an intermediary has in his LP vault
74
+ *
75
+ * @param address
76
+ * @param token
77
+ */
78
+ async getIntermediaryBalance(address, token) {
79
+ const balance = (0, Utils_1.toBigInt)((await this.contract.get_balance([starknet_1.cairo.tuple(address, token)]))[0]);
80
+ this.logger.debug("getIntermediaryBalance(): token LP balance fetched, token: " + token.toString() +
81
+ " address: " + address + " amount: " + (balance == null ? "null" : balance.toString()));
82
+ return balance;
83
+ }
84
+ /**
85
+ * Creates transactions for withdrawing funds from the LP vault, creates ATA if it doesn't exist and unwraps
86
+ * WSOL to SOL if required
87
+ *
88
+ * @param signer
89
+ * @param token
90
+ * @param amount
91
+ * @param feeRate
92
+ */
93
+ async txsWithdraw(signer, token, amount, feeRate) {
94
+ const action = await this.Withdraw(signer, token, amount);
95
+ feeRate ?? (feeRate = await this.root.Fees.getFeeRate());
96
+ this.logger.debug("txsWithdraw(): withdraw TX created, token: " + token.toString() +
97
+ " amount: " + amount.toString(10));
98
+ return [await action.tx(feeRate)];
99
+ }
100
+ /**
101
+ * Creates transaction for depositing funds into the LP vault, wraps SOL to WSOL if required
102
+ *
103
+ * @param signer
104
+ * @param token
105
+ * @param amount
106
+ * @param feeRate
107
+ */
108
+ async txsDeposit(signer, token, amount, feeRate) {
109
+ //Approve first
110
+ const action = await this.root.Tokens.Approve(signer, this.contract.address, token, amount);
111
+ action.add(this.Deposit(signer, token, amount));
112
+ feeRate ?? (feeRate = await this.root.Fees.getFeeRate());
113
+ this.logger.debug("txsDeposit(): deposit TX created, token: " + token.toString() +
114
+ " amount: " + amount.toString(10));
115
+ return [await action.tx(feeRate)];
116
+ }
117
+ }
118
+ exports.StarknetLpVault = StarknetLpVault;
119
+ StarknetLpVault.GasCosts = {
120
+ WITHDRAW: { l1: 750, l2: 0 },
121
+ DEPOSIT: { l1: 750, l2: 0 }
122
+ };
@@ -0,0 +1,53 @@
1
+ import { RelaySynchronizer } from "@atomiqlabs/base";
2
+ import { StarknetSwapModule } from "../StarknetSwapModule";
3
+ import { StarknetSwapData } from "../StarknetSwapData";
4
+ import { StarknetTx } from "../../base/modules/StarknetTransactions";
5
+ import { StarknetBtcStoredHeader } from "../../btcrelay/headers/StarknetBtcStoredHeader";
6
+ export declare class StarknetSwapClaim extends StarknetSwapModule {
7
+ private static readonly GasCosts;
8
+ /**
9
+ * Claim action which uses the provided witness for claiming the swap
10
+ *
11
+ * @param signer
12
+ * @param swapData
13
+ * @param witness
14
+ * @param claimHandlerGas
15
+ * @constructor
16
+ * @private
17
+ */
18
+ private Claim;
19
+ /**
20
+ * Creates transactions claiming the swap using a secret (for HTLC swaps)
21
+ *
22
+ * @param signer
23
+ * @param swapData swap to claim
24
+ * @param secret hex encoded secret pre-image to the HTLC hash
25
+ * @param checkExpiry whether to check if the swap is already expired (trying to claim an expired swap with a secret
26
+ * is dangerous because we might end up revealing the secret to the counterparty without being able to claim the swap)
27
+ * @param feeRate fee rate to use for the transaction
28
+ */
29
+ txsClaimWithSecret(signer: string, swapData: StarknetSwapData, secret: string, checkExpiry?: boolean, feeRate?: string): Promise<StarknetTx[]>;
30
+ /**
31
+ * Creates transaction claiming the swap using a confirmed transaction data (for BTC on-chain swaps)
32
+ *
33
+ * @param signer
34
+ * @param swapData swap to claim
35
+ * @param tx bitcoin transaction that satisfies the swap condition
36
+ * @param requiredConfirmations
37
+ * @param vout vout of the bitcoin transaction that satisfies the swap condition
38
+ * @param commitedHeader commited header data from btc relay (fetched internally if null)
39
+ * @param synchronizer optional synchronizer to use in case we need to sync up the btc relay ourselves
40
+ * @param feeRate fee rate to be used for the transactions
41
+ */
42
+ txsClaimWithTxData(signer: string, swapData: StarknetSwapData, tx: {
43
+ blockhash: string;
44
+ confirmations: number;
45
+ txid: string;
46
+ hex: string;
47
+ height: number;
48
+ }, requiredConfirmations: number, vout: number, commitedHeader?: StarknetBtcStoredHeader, synchronizer?: RelaySynchronizer<StarknetBtcStoredHeader, StarknetTx, any>, feeRate?: string): Promise<StarknetTx[] | null>;
49
+ /**
50
+ * Get the estimated starknet transaction fee of the claim transaction
51
+ */
52
+ getClaimFee(swapData: StarknetSwapData, feeRate?: string): Promise<bigint>;
53
+ }
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StarknetSwapClaim = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const Utils_1 = require("../../../utils/Utils");
6
+ const StarknetSwapModule_1 = require("../StarknetSwapModule");
7
+ const StarknetAction_1 = require("../../base/StarknetAction");
8
+ const StarknetFees_1 = require("../../base/modules/StarknetFees");
9
+ class StarknetSwapClaim extends StarknetSwapModule_1.StarknetSwapModule {
10
+ /**
11
+ * Claim action which uses the provided witness for claiming the swap
12
+ *
13
+ * @param signer
14
+ * @param swapData
15
+ * @param witness
16
+ * @param claimHandlerGas
17
+ * @constructor
18
+ * @private
19
+ */
20
+ Claim(signer, swapData, witness, claimHandlerGas) {
21
+ return new StarknetAction_1.StarknetAction(signer, this.root, this.contract.populateTransaction.claim(swapData.toEscrowStruct(), witness), (0, StarknetAction_1.sumStarknetGas)(swapData.payOut ? StarknetSwapClaim.GasCosts.CLAIM_PAY_OUT : StarknetSwapClaim.GasCosts.CLAIM, claimHandlerGas));
22
+ }
23
+ /**
24
+ * Creates transactions claiming the swap using a secret (for HTLC swaps)
25
+ *
26
+ * @param signer
27
+ * @param swapData swap to claim
28
+ * @param secret hex encoded secret pre-image to the HTLC hash
29
+ * @param checkExpiry whether to check if the swap is already expired (trying to claim an expired swap with a secret
30
+ * is dangerous because we might end up revealing the secret to the counterparty without being able to claim the swap)
31
+ * @param feeRate fee rate to use for the transaction
32
+ */
33
+ async txsClaimWithSecret(signer, swapData, secret, checkExpiry, feeRate) {
34
+ //We need to be sure that this transaction confirms in time, otherwise we reveal the secret to the counterparty
35
+ // and won't claim the funds
36
+ if (checkExpiry && await this.root.isExpired(swapData.claimer.toString(), swapData)) {
37
+ throw new base_1.SwapDataVerificationError("Not enough time to reliably pay the invoice");
38
+ }
39
+ const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
40
+ if (claimHandler == null)
41
+ throw new base_1.SwapDataVerificationError("Unknown claim handler!");
42
+ if (claimHandler.getType() !== base_1.ChainSwapType.HTLC)
43
+ throw new base_1.SwapDataVerificationError("Invalid claim handler!");
44
+ feeRate ?? (feeRate = await this.root.Fees.getFeeRate());
45
+ const { initialTxns, witness } = await claimHandler.getWitness(signer, swapData, secret, feeRate);
46
+ const action = this.Claim(signer, swapData, witness, claimHandler.getGas(swapData));
47
+ await action.addToTxs(initialTxns, feeRate);
48
+ this.logger.debug("txsClaimWithSecret(): creating claim transaction, swap: " + swapData.getClaimHash() + " witness: ", witness.map(Utils_1.toHex));
49
+ return initialTxns;
50
+ }
51
+ /**
52
+ * Creates transaction claiming the swap using a confirmed transaction data (for BTC on-chain swaps)
53
+ *
54
+ * @param signer
55
+ * @param swapData swap to claim
56
+ * @param tx bitcoin transaction that satisfies the swap condition
57
+ * @param requiredConfirmations
58
+ * @param vout vout of the bitcoin transaction that satisfies the swap condition
59
+ * @param commitedHeader commited header data from btc relay (fetched internally if null)
60
+ * @param synchronizer optional synchronizer to use in case we need to sync up the btc relay ourselves
61
+ * @param feeRate fee rate to be used for the transactions
62
+ */
63
+ async txsClaimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, feeRate) {
64
+ const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
65
+ if (claimHandler == null)
66
+ throw new base_1.SwapDataVerificationError("Unknown claim handler!");
67
+ if (claimHandler.getType() !== base_1.ChainSwapType.CHAIN_NONCED &&
68
+ claimHandler.getType() !== base_1.ChainSwapType.CHAIN_TXID &&
69
+ claimHandler.getType() !== base_1.ChainSwapType.CHAIN)
70
+ throw new base_1.SwapDataVerificationError("Invalid claim handler!");
71
+ feeRate ?? (feeRate = await this.root.Fees.getFeeRate());
72
+ const { initialTxns, witness } = await claimHandler.getWitness(signer, swapData, {
73
+ tx,
74
+ vout,
75
+ requiredConfirmations,
76
+ commitedHeader,
77
+ btcRelay: this.root.btcRelay,
78
+ synchronizer,
79
+ }, feeRate);
80
+ const action = this.Claim(signer, swapData, witness, claimHandler.getGas(swapData));
81
+ await action.addToTxs(initialTxns, feeRate);
82
+ return initialTxns;
83
+ }
84
+ /**
85
+ * Get the estimated starknet transaction fee of the claim transaction
86
+ */
87
+ async getClaimFee(swapData, feeRate) {
88
+ feeRate ?? (feeRate = await this.root.Fees.getFeeRate());
89
+ let gasRequired = swapData.payOut ? StarknetSwapClaim.GasCosts.CLAIM_PAY_OUT : StarknetSwapClaim.GasCosts.CLAIM;
90
+ const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
91
+ if (claimHandler != null)
92
+ gasRequired = (0, StarknetAction_1.sumStarknetGas)(gasRequired, claimHandler.getGas(swapData));
93
+ return StarknetFees_1.StarknetFees.getGasFee(gasRequired.l1, feeRate);
94
+ }
95
+ }
96
+ exports.StarknetSwapClaim = StarknetSwapClaim;
97
+ StarknetSwapClaim.GasCosts = {
98
+ CLAIM: { l1: 500, l2: 0 },
99
+ CLAIM_PAY_OUT: { l1: 1000, l2: 0 }
100
+ };