@atomiqlabs/chain-starknet 1.0.2 → 1.0.4

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 (38) hide show
  1. package/dist/starknet/StarknetInitializer.d.ts +1 -1
  2. package/dist/starknet/StarknetInitializer.js +4 -0
  3. package/dist/starknet/base/modules/StarknetSignatures.d.ts +0 -1
  4. package/dist/starknet/base/modules/StarknetSignatures.js +4 -3
  5. package/dist/starknet/btcrelay/StarknetBtcRelay.d.ts +0 -1
  6. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.d.ts +0 -1
  7. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.js +3 -3
  8. package/dist/starknet/btcrelay/headers/StarknetBtcStoredHeader.d.ts +0 -1
  9. package/dist/starknet/events/StarknetChainEvents.js +1 -0
  10. package/dist/starknet/swaps/StarknetSwapContract.d.ts +0 -1
  11. package/dist/starknet/swaps/StarknetSwapContract.js +3 -3
  12. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.d.ts +0 -1
  13. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.js +2 -2
  14. package/dist/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.d.ts +0 -1
  15. package/dist/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.d.ts +0 -1
  16. package/dist/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.js +2 -1
  17. package/dist/starknet/swaps/handlers/refund/TimelockRefundHandler.js +1 -1
  18. package/dist/utils/Utils.d.ts +0 -1
  19. package/dist/utils/Utils.js +5 -5
  20. package/package.json +3 -5
  21. package/src/starknet/StarknetInitializer.ts +5 -1
  22. package/src/starknet/base/modules/StarknetSignatures.ts +3 -3
  23. package/src/starknet/btcrelay/headers/StarknetBtcHeader.ts +3 -3
  24. package/src/starknet/events/StarknetChainEvents.ts +1 -0
  25. package/src/starknet/events/StarknetChainEventsBrowser.ts +1 -1
  26. package/src/starknet/swaps/StarknetSwapContract.ts +3 -3
  27. package/src/starknet/swaps/handlers/claim/HashlockClaimHandler.ts +2 -2
  28. package/src/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.ts +1 -0
  29. package/src/starknet/swaps/handlers/refund/TimelockRefundHandler.ts +1 -1
  30. package/src/utils/Utils.ts +5 -5
  31. package/dist/get_serialized_block.d.ts +0 -1
  32. package/dist/get_serialized_block.js +0 -28
  33. package/dist/starknet/swaps/modules/SwapClaim.d.ts +0 -54
  34. package/dist/starknet/swaps/modules/SwapClaim.js +0 -115
  35. package/dist/starknet/swaps/modules/SwapInit.d.ts +0 -79
  36. package/dist/starknet/swaps/modules/SwapInit.js +0 -174
  37. package/dist/starknet/swaps/modules/SwapRefund.d.ts +0 -63
  38. package/dist/starknet/swaps/modules/SwapRefund.js +0 -149
@@ -3,7 +3,7 @@ import { StarknetFees } from "./base/modules/StarknetFees";
3
3
  import { StarknetRetryPolicy } from "./base/StarknetBase";
4
4
  import { BaseTokenType, BitcoinNetwork, BitcoinRpc, ChainData, ChainInitializer } from "@atomiqlabs/base";
5
5
  import { StarknetChainType } from "./StarknetChainType";
6
- export type StarknetAssetsType = BaseTokenType<"ETH" | "STRK">;
6
+ export type StarknetAssetsType = BaseTokenType<"ETH" | "STRK" | "WBTC">;
7
7
  export declare const StarknetAssets: StarknetAssetsType;
8
8
  export type StarknetOptions = {
9
9
  rpcUrl: string | Provider;
@@ -18,6 +18,10 @@ exports.StarknetAssets = {
18
18
  address: "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d",
19
19
  decimals: 18,
20
20
  displayDecimals: 9
21
+ },
22
+ WBTC: {
23
+ address: "0x03fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac",
24
+ decimals: 8
21
25
  }
22
26
  };
23
27
  function initializeStarknet(options, bitcoinRpc, network) {
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Buffer } from "buffer";
3
2
  import { StarknetModule } from "../StarknetModule";
4
3
  import { StarknetSigner } from "../../wallet/StarknetSigner";
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StarknetSignatures = void 0;
4
- const createHash = require("create-hash");
4
+ const buffer_1 = require("buffer");
5
5
  const StarknetModule_1 = require("../StarknetModule");
6
6
  const starknet_1 = require("starknet");
7
7
  const Utils_1 = require("../../../utils/Utils");
8
+ const sha2_1 = require("@noble/hashes/sha2");
8
9
  const StarknetDomain = [
9
10
  { name: 'name', type: 'shortstring' },
10
11
  { name: 'version', type: 'shortstring' },
@@ -52,7 +53,7 @@ class StarknetSignatures extends StarknetModule_1.StarknetModule {
52
53
  * @param data data to sign
53
54
  */
54
55
  getDataSignature(signer, data) {
55
- const buff = createHash("sha256").update(data).digest();
56
+ const buff = buffer_1.Buffer.from((0, sha2_1.sha256)(data));
56
57
  return this.signTypedMessage(signer, DataHash, 'DataHash', { "Data hash": starknet_1.cairo.uint256((0, Utils_1.toHex)(buff)) });
57
58
  }
58
59
  /**
@@ -64,7 +65,7 @@ class StarknetSignatures extends StarknetModule_1.StarknetModule {
64
65
  * @param address public key of the signer
65
66
  */
66
67
  isValidDataSignature(data, signature, address) {
67
- const buff = createHash("sha256").update(data).digest();
68
+ const buff = buffer_1.Buffer.from((0, sha2_1.sha256)(data));
68
69
  return this.isValidSignature(signature, address, DataHash, 'DataHash', { "Data hash": starknet_1.cairo.uint256((0, Utils_1.toHex)(buff)) });
69
70
  }
70
71
  }
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Buffer } from "buffer";
3
2
  import { StarknetBtcHeader } from "./headers/StarknetBtcHeader";
4
3
  import { BitcoinRpc, BtcBlock, BtcRelay } from "@atomiqlabs/base";
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { BtcHeader } from "@atomiqlabs/base";
3
2
  import { Buffer } from "buffer";
4
3
  import { BigNumberish } from "starknet";
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StarknetBtcHeader = void 0;
4
4
  const buffer_1 = require("buffer");
5
5
  const Utils_1 = require("../../../utils/Utils");
6
- const createHash = require("create-hash");
6
+ const sha2_1 = require("@noble/hashes/sha2");
7
7
  class StarknetBtcHeader {
8
8
  constructor(obj) {
9
9
  this.reversed_version = Number(obj.reversed_version);
@@ -36,13 +36,13 @@ class StarknetBtcHeader {
36
36
  if (this.hash != null)
37
37
  return this.hash;
38
38
  const buffer = buffer_1.Buffer.alloc(80);
39
- buffer.writeUInt32BE(this.reversed_version);
39
+ buffer.writeUInt32BE(this.reversed_version, 0);
40
40
  (0, Utils_1.u32ArrayToBuffer)(this.previous_blockhash).copy(buffer, 4);
41
41
  (0, Utils_1.u32ArrayToBuffer)(this.merkle_root).copy(buffer, 36);
42
42
  buffer.writeUInt32BE(this.reversed_timestamp, 68);
43
43
  buffer.writeUInt32BE(this.nbits, 72);
44
44
  buffer.writeUInt32BE(this.nonce, 76);
45
- return createHash("sha256").update(createHash("sha256").update(buffer).digest()).digest();
45
+ return buffer_1.Buffer.from((0, sha2_1.sha256)((0, sha2_1.sha256)(buffer)));
46
46
  }
47
47
  serialize() {
48
48
  return [
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { BtcStoredHeader } from "@atomiqlabs/base";
3
2
  import { StarknetBtcHeader, StarknetBtcHeaderType } from "./StarknetBtcHeader";
4
3
  import { Buffer } from "buffer";
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StarknetChainEvents = void 0;
4
4
  const StarknetChainEventsBrowser_1 = require("./StarknetChainEventsBrowser");
5
+ //@ts-ignore
5
6
  const fs = require("fs/promises");
6
7
  const BLOCKHEIGHT_FILENAME = "/strk-blockheight.txt";
7
8
  class StarknetChainEvents extends StarknetChainEventsBrowser_1.StarknetChainEventsBrowser {
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { ChainSwapType, IntermediaryReputationType, RelaySynchronizer, SignatureData, SwapCommitStatus, SwapContract, TransactionConfirmationOptions } from "@atomiqlabs/base";
3
2
  import { Buffer } from "buffer";
4
3
  import { EscrowManagerAbi } from "./EscrowManagerAbi";
@@ -17,7 +17,7 @@ const StarknetSwapInit_1 = require("./modules/StarknetSwapInit");
17
17
  const StarknetSwapRefund_1 = require("./modules/StarknetSwapRefund");
18
18
  const ClaimHandlers_1 = require("./handlers/claim/ClaimHandlers");
19
19
  const StarknetSwapClaim_1 = require("./modules/StarknetSwapClaim");
20
- const createHash = require("create-hash");
20
+ const sha2_1 = require("@noble/hashes/sha2");
21
21
  const ESCROW_STATE_COMMITTED = 1;
22
22
  const ESCROW_STATE_CLAIMED = 2;
23
23
  const ESCROW_STATE_REFUNDED = 3;
@@ -216,10 +216,10 @@ class StarknetSwapContract extends StarknetContractBase_1.StarknetContractBase {
216
216
  getExtraData(outputScript, amount, confirmations, nonce) {
217
217
  if (nonce == null)
218
218
  nonce = 0n;
219
- const txoHash = createHash("sha256").update(buffer_1.Buffer.concat([
219
+ const txoHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.concat([
220
220
  base_1.BigIntBufferUtils.toBuffer(amount, "le", 8),
221
221
  outputScript
222
- ])).digest();
222
+ ])));
223
223
  return buffer_1.Buffer.concat([
224
224
  txoHash,
225
225
  base_1.BigIntBufferUtils.toBuffer(nonce, "be", 8),
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { StarknetSwapData } from "../../StarknetSwapData";
3
2
  import { BigNumberish } from "starknet";
4
3
  import { ChainSwapType } from "@atomiqlabs/base";
@@ -5,7 +5,7 @@ const Utils_1 = require("../../../../utils/Utils");
5
5
  const starknet_1 = require("starknet");
6
6
  const base_1 = require("@atomiqlabs/base");
7
7
  const buffer_1 = require("buffer");
8
- const createHash = require("create-hash");
8
+ const sha2_1 = require("@noble/hashes/sha2");
9
9
  class HashlockClaimHandler {
10
10
  constructor(address) {
11
11
  this.address = address;
@@ -23,7 +23,7 @@ class HashlockClaimHandler {
23
23
  const buffer = buffer_1.Buffer.from(witnessData, "hex");
24
24
  if (buffer.length !== 32)
25
25
  throw new Error("Invalid hash secret: buff length");
26
- const witnessSha256 = createHash("sha256").update(buffer).digest();
26
+ const witnessSha256 = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer));
27
27
  if (!data.isClaimData((0, Utils_1.toHex)(this.getCommitment(witnessSha256))))
28
28
  throw new Error("Invalid hash secret: poseidon hash doesn't match");
29
29
  const witnessArray = (0, Utils_1.bufferToU32Array)(buffer);
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { StarknetSwapData } from "../../../StarknetSwapData";
3
2
  import { StarknetGas } from "../../../../base/StarknetAction";
4
3
  import { ChainSwapType } from "@atomiqlabs/base";
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { StarknetSwapData } from "../../../StarknetSwapData";
3
2
  import { StarknetGas } from "../../../../base/StarknetAction";
4
3
  import { ChainSwapType } from "@atomiqlabs/base";
@@ -4,11 +4,12 @@ exports.BitcoinTxIdClaimHandler = void 0;
4
4
  const base_1 = require("@atomiqlabs/base");
5
5
  const Utils_1 = require("../../../../../utils/Utils");
6
6
  const IBitcoinClaimHandler_1 = require("./IBitcoinClaimHandler");
7
+ const buffer_1 = require("buffer");
7
8
  const logger = (0, Utils_1.getLogger)("BitcoinTxIdClaimHandler: ");
8
9
  class BitcoinTxIdClaimHandler extends IBitcoinClaimHandler_1.IBitcoinClaimHandler {
9
10
  serializeCommitment(data) {
10
11
  return [
11
- ...(0, Utils_1.bufferToU32Array)(Buffer.from(data.txId, "hex").reverse()),
12
+ ...(0, Utils_1.bufferToU32Array)(buffer_1.Buffer.from(data.txId, "hex").reverse()),
12
13
  ...super.serializeCommitment(data)
13
14
  ];
14
15
  }
@@ -20,7 +20,7 @@ class TimelockRefundHandler {
20
20
  return TimelockRefundHandler.gas;
21
21
  }
22
22
  static getExpiry(data) {
23
- return (0, Utils_1.bigNumberishToBuffer)(data.refundData, 32).readBigUInt64BE(24);
23
+ return (0, Utils_1.bigNumberishToBuffer)(data.refundData, 32).readBigUInt64BE(24).valueOf();
24
24
  }
25
25
  }
26
26
  exports.TimelockRefundHandler = TimelockRefundHandler;
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { BigNumberish, Uint256 } from "starknet";
3
2
  import { StarknetTx } from "../starknet/base/modules/StarknetTransactions";
4
3
  import { Buffer } from "buffer";
@@ -164,7 +164,7 @@ function bigNumberishToBuffer(value, length) {
164
164
  }
165
165
  const buff = buffer_1.Buffer.from(value.padStart(length * 2, "0"), "hex");
166
166
  if (buff.length > length)
167
- return buff.subarray(buff.length - length);
167
+ return buff.slice(buff.length - length);
168
168
  return buff;
169
169
  }
170
170
  exports.bigNumberishToBuffer = bigNumberishToBuffer;
@@ -204,22 +204,22 @@ exports.bytes31SpanToBuffer = bytes31SpanToBuffer;
204
204
  function bufferToBytes31Span(buffer, startIndex = 0, endIndex = buffer.length) {
205
205
  const values = [];
206
206
  for (let i = startIndex + 31; i < endIndex; i += 31) {
207
- values.push(BigInt("0x" + buffer.subarray(i - 31, i).toString("hex")));
207
+ values.push(BigInt("0x" + buffer.slice(i - 31, i).toString("hex")));
208
208
  }
209
209
  if (endIndex > startIndex + (values.length * 31))
210
- values.push(BigInt("0x" + buffer.subarray(startIndex + (values.length * 31), endIndex).toString("hex")));
210
+ values.push(BigInt("0x" + buffer.slice(startIndex + (values.length * 31), endIndex).toString("hex")));
211
211
  return values;
212
212
  }
213
213
  exports.bufferToBytes31Span = bufferToBytes31Span;
214
214
  function bufferToByteArray(buffer, startIndex = 0, endIndex = buffer.length) {
215
215
  const values = [];
216
216
  for (let i = startIndex + 31; i < endIndex; i += 31) {
217
- values.push(BigInt("0x" + buffer.subarray(i - 31, i).toString("hex")));
217
+ values.push(BigInt("0x" + buffer.slice(i - 31, i).toString("hex")));
218
218
  }
219
219
  let pendingWord = BigInt(0);
220
220
  let pendingWordLen = BigInt(endIndex - (startIndex + (values.length * 31)));
221
221
  if (pendingWordLen !== BigInt(0)) {
222
- pendingWord = BigInt("0x" + buffer.subarray(startIndex + (values.length * 31), endIndex).toString("hex"));
222
+ pendingWord = BigInt("0x" + buffer.slice(startIndex + (values.length * 31), endIndex).toString("hex"));
223
223
  }
224
224
  return [
225
225
  BigInt(values.length),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atomiqlabs/chain-starknet",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Starknet specific base implementation",
5
5
  "main": "./dist/index.js",
6
6
  "types:": "./dist/index.d.ts",
@@ -23,17 +23,15 @@
23
23
  "license": "ISC",
24
24
  "dependencies": {
25
25
  "@atomiqlabs/base": "^8.0.0",
26
+ "@noble/hashes": "^1.7.1",
26
27
  "@scure/btc-signer": "1.6.0",
27
28
  "abi-wan-kanabi": "2.2.4",
28
- "buffer": "6.0.3",
29
- "create-hash": "1.2.0",
30
- "randombytes": "2.1.0"
29
+ "buffer": "6.0.3"
31
30
  },
32
31
  "peerDependencies": {
33
32
  "starknet": "^6.11.0"
34
33
  },
35
34
  "devDependencies": {
36
- "@types/create-hash": "1.2.6",
37
35
  "typescript": "4.9.5"
38
36
  }
39
37
  }
@@ -8,7 +8,7 @@ import {BaseTokenType, BitcoinNetwork, BitcoinRpc, ChainData, ChainInitializer}
8
8
  import {StarknetChainType} from "./StarknetChainType";
9
9
  import {StarknetSwapData} from "./swaps/StarknetSwapData";
10
10
 
11
- export type StarknetAssetsType = BaseTokenType<"ETH" | "STRK">;
11
+ export type StarknetAssetsType = BaseTokenType<"ETH" | "STRK" | "WBTC">;
12
12
  export const StarknetAssets: StarknetAssetsType = {
13
13
  ETH: {
14
14
  address: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
@@ -19,6 +19,10 @@ export const StarknetAssets: StarknetAssetsType = {
19
19
  address: "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d",
20
20
  decimals: 18,
21
21
  displayDecimals: 9
22
+ },
23
+ WBTC: {
24
+ address: "0x03fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac",
25
+ decimals: 8
22
26
  }
23
27
  } as const;
24
28
 
@@ -1,4 +1,3 @@
1
- import * as createHash from "create-hash";
2
1
  import {Buffer} from "buffer";
3
2
  import {StarknetModule} from "../StarknetModule";
4
3
  import {StarknetSigner} from "../../wallet/StarknetSigner";
@@ -11,6 +10,7 @@ import {
11
10
  } from "starknet";
12
11
  import {StarknetBase} from "../StarknetBase";
13
12
  import {toHex} from "../../../utils/Utils";
13
+ import {sha256} from "@noble/hashes/sha2";
14
14
 
15
15
  const StarknetDomain = [
16
16
  { name: 'name', type: 'shortstring' },
@@ -71,7 +71,7 @@ export class StarknetSignatures extends StarknetModule {
71
71
  * @param data data to sign
72
72
  */
73
73
  public getDataSignature(signer: StarknetSigner, data: Buffer): Promise<string> {
74
- const buff = createHash("sha256").update(data).digest();
74
+ const buff = Buffer.from(sha256(data));
75
75
  return this.signTypedMessage(signer, DataHash, 'DataHash', {"Data hash": cairo.uint256(toHex(buff))});
76
76
  }
77
77
 
@@ -84,7 +84,7 @@ export class StarknetSignatures extends StarknetModule {
84
84
  * @param address public key of the signer
85
85
  */
86
86
  public isValidDataSignature(data: Buffer, signature: string, address: string): Promise<boolean> {
87
- const buff = createHash("sha256").update(data).digest();
87
+ const buff = Buffer.from(sha256(data));
88
88
  return this.isValidSignature(signature, address, DataHash, 'DataHash', {"Data hash": cairo.uint256(toHex(buff))});
89
89
  }
90
90
 
@@ -2,7 +2,7 @@ import {BtcHeader} from "@atomiqlabs/base";
2
2
  import {Buffer} from "buffer";
3
3
  import {BigNumberish} from "starknet";
4
4
  import {toHex, u32ArrayToBuffer, u32ReverseEndianness} from "../../../utils/Utils";
5
- import * as createHash from "create-hash";
5
+ import {sha256} from "@noble/hashes/sha2";
6
6
 
7
7
  export type StarknetBtcHeaderType = {
8
8
  reversed_version: BigNumberish;
@@ -61,13 +61,13 @@ export class StarknetBtcHeader implements BtcHeader {
61
61
  getHash(): Buffer {
62
62
  if(this.hash!=null) return this.hash;
63
63
  const buffer = Buffer.alloc(80);
64
- buffer.writeUInt32BE(this.reversed_version);
64
+ buffer.writeUInt32BE(this.reversed_version, 0);
65
65
  u32ArrayToBuffer(this.previous_blockhash).copy(buffer, 4);
66
66
  u32ArrayToBuffer(this.merkle_root).copy(buffer, 36);
67
67
  buffer.writeUInt32BE(this.reversed_timestamp, 68);
68
68
  buffer.writeUInt32BE(this.nbits, 72);
69
69
  buffer.writeUInt32BE(this.nonce, 76);
70
- return createHash("sha256").update(createHash("sha256").update(buffer).digest()).digest();
70
+ return Buffer.from(sha256(sha256(buffer)));
71
71
  }
72
72
 
73
73
  serialize(): BigNumberish[] {
@@ -1,4 +1,5 @@
1
1
  import {StarknetChainEventsBrowser} from "./StarknetChainEventsBrowser";
2
+ //@ts-ignore
2
3
  import * as fs from "fs/promises";
3
4
  import {StarknetSwapContract} from "../swaps/StarknetSwapContract";
4
5
 
@@ -50,7 +50,7 @@ export class StarknetChainEventsBrowser implements ChainEvents<StarknetSwapData>
50
50
  protected stopped: boolean;
51
51
  protected pollIntervalSeconds: number;
52
52
 
53
- private timeout: NodeJS.Timeout;
53
+ private timeout: number;
54
54
 
55
55
  constructor(starknetSwapContract: StarknetSwapContract, pollIntervalSeconds: number = 5) {
56
56
  this.provider = starknetSwapContract.provider;
@@ -28,7 +28,7 @@ import {claimHandlersList, IClaimHandler} from "./handlers/claim/ClaimHandlers";
28
28
  import {StarknetSwapClaim} from "./modules/StarknetSwapClaim";
29
29
  import {IHandler} from "./handlers/IHandler";
30
30
  import {StarknetBtcStoredHeader} from "../btcrelay/headers/StarknetBtcStoredHeader";
31
- import * as createHash from "create-hash";
31
+ import {sha256} from "@noble/hashes/sha2";
32
32
 
33
33
  const ESCROW_STATE_COMMITTED = 1;
34
34
  const ESCROW_STATE_CLAIMED = 2;
@@ -285,10 +285,10 @@ export class StarknetSwapContract
285
285
 
286
286
  getExtraData(outputScript: Buffer, amount: bigint, confirmations: number, nonce?: bigint): Buffer {
287
287
  if(nonce==null) nonce = 0n;
288
- const txoHash = createHash("sha256").update(Buffer.concat([
288
+ const txoHash = Buffer.from(sha256(Buffer.concat([
289
289
  BigIntBufferUtils.toBuffer(amount, "le", 8),
290
290
  outputScript
291
- ])).digest();
291
+ ])));
292
292
  return Buffer.concat([
293
293
  txoHash,
294
294
  BigIntBufferUtils.toBuffer(nonce, "be", 8),
@@ -4,7 +4,7 @@ import {BigNumberish, hash} from "starknet";
4
4
  import {ChainSwapType} from "@atomiqlabs/base";
5
5
  import {StarknetGas} from "../../../base/StarknetAction";
6
6
  import {Buffer} from "buffer";
7
- import * as createHash from "create-hash";
7
+ import {sha256} from "@noble/hashes/sha2";
8
8
  import {StarknetTx} from "../../../base/modules/StarknetTransactions";
9
9
  import {IClaimHandler} from "./ClaimHandlers";
10
10
 
@@ -32,7 +32,7 @@ export class HashlockClaimHandler implements IClaimHandler<Buffer, string> {
32
32
  const buffer = Buffer.from(witnessData, "hex");
33
33
  if(buffer.length!==32) throw new Error("Invalid hash secret: buff length");
34
34
 
35
- const witnessSha256 = createHash("sha256").update(buffer).digest()
35
+ const witnessSha256 = Buffer.from(sha256(buffer));
36
36
  if(!data.isClaimData(toHex(this.getCommitment(witnessSha256)))) throw new Error("Invalid hash secret: poseidon hash doesn't match");
37
37
 
38
38
  const witnessArray = bufferToU32Array(buffer);
@@ -5,6 +5,7 @@ import {BigNumberish} from "starknet";
5
5
  import {StarknetTx} from "../../../../base/modules/StarknetTransactions";
6
6
  import {bufferToU32Array, getLogger} from "../../../../../utils/Utils";
7
7
  import {BitcoinCommitmentData, BitcoinWitnessData, IBitcoinClaimHandler} from "./IBitcoinClaimHandler";
8
+ import {Buffer} from "buffer";
8
9
 
9
10
  export type BitcoinTxIdCommitmentData = {
10
11
  txId: string
@@ -33,7 +33,7 @@ export class TimelockRefundHandler implements IHandler<bigint, never> {
33
33
  }
34
34
 
35
35
  public static getExpiry(data: StarknetSwapData): bigint {
36
- return bigNumberishToBuffer(data.refundData, 32).readBigUInt64BE(24);
36
+ return bigNumberishToBuffer(data.refundData, 32).readBigUInt64BE(24).valueOf();
37
37
  }
38
38
 
39
39
  }
@@ -164,7 +164,7 @@ export function bigNumberishToBuffer(value: BigNumberish | Uint256, length: numb
164
164
  value = value.toString(16);
165
165
  }
166
166
  const buff = Buffer.from(value.padStart(length*2, "0"), "hex");
167
- if(buff.length > length) return buff.subarray(buff.length-length);
167
+ if(buff.length > length) return buff.slice(buff.length-length);
168
168
  return buff;
169
169
  }
170
170
 
@@ -200,21 +200,21 @@ export function bytes31SpanToBuffer(span: BigNumberish[], length: number): Buffe
200
200
  export function bufferToBytes31Span(buffer: Buffer, startIndex: number = 0, endIndex: number = buffer.length): BigNumberish[] {
201
201
  const values: BigNumberish[] = [];
202
202
  for(let i=startIndex+31;i<endIndex;i+=31) {
203
- values.push(BigInt("0x"+buffer.subarray(i-31, i).toString("hex")));
203
+ values.push(BigInt("0x"+buffer.slice(i-31, i).toString("hex")));
204
204
  }
205
- if(endIndex > startIndex + (values.length*31)) values.push(BigInt("0x"+buffer.subarray(startIndex + (values.length*31), endIndex).toString("hex")));
205
+ if(endIndex > startIndex + (values.length*31)) values.push(BigInt("0x"+buffer.slice(startIndex + (values.length*31), endIndex).toString("hex")));
206
206
  return values;
207
207
  }
208
208
 
209
209
  export function bufferToByteArray(buffer: Buffer, startIndex: number = 0, endIndex: number = buffer.length): BigNumberish[] {
210
210
  const values: BigNumberish[] = [];
211
211
  for(let i=startIndex+31;i<endIndex;i+=31) {
212
- values.push(BigInt("0x"+buffer.subarray(i-31, i).toString("hex")));
212
+ values.push(BigInt("0x"+buffer.slice(i-31, i).toString("hex")));
213
213
  }
214
214
  let pendingWord: BigNumberish = BigInt(0);
215
215
  let pendingWordLen: BigNumberish = BigInt(endIndex - (startIndex + (values.length*31)));
216
216
  if(pendingWordLen !== BigInt(0)) {
217
- pendingWord = BigInt("0x"+buffer.subarray(startIndex + (values.length*31), endIndex).toString("hex"));
217
+ pendingWord = BigInt("0x"+buffer.slice(startIndex + (values.length*31), endIndex).toString("hex"));
218
218
  }
219
219
  return [
220
220
  BigInt(values.length),
@@ -1 +0,0 @@
1
- export {};
@@ -1,28 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const Utils_1 = require("./utils/Utils");
13
- const buffer_1 = require("buffer");
14
- const StarknetBtcHeader_1 = require("./starknet/btcrelay/headers/StarknetBtcHeader");
15
- function main() {
16
- return __awaiter(this, void 0, void 0, function* () {
17
- const blockheader = new StarknetBtcHeader_1.StarknetBtcHeader({
18
- reversed_version: (0, Utils_1.u32ReverseEndianness)(e.getVersion()),
19
- previous_blockhash: (0, Utils_1.bufferToU32Array)(buffer_1.Buffer.from(e.getPrevBlockhash(), "hex").reverse()),
20
- merkle_root: (0, Utils_1.bufferToU32Array)(buffer_1.Buffer.from(e.getMerkleRoot(), "hex").reverse()),
21
- reversed_timestamp: (0, Utils_1.u32ReverseEndianness)(e.getTimestamp()),
22
- nbits: (0, Utils_1.u32ReverseEndianness)(e.getNbits()),
23
- nonce: (0, Utils_1.u32ReverseEndianness)(e.getNonce()),
24
- hash: buffer_1.Buffer.from(e.getHash(), "hex").reverse()
25
- });
26
- });
27
- }
28
- main();
@@ -1,54 +0,0 @@
1
- import { RelaySynchronizer } from "@atomiqlabs/base";
2
- import * as BN from "bn.js";
3
- import { StarknetSwapModule } from "../StarknetSwapModule";
4
- import { StarknetSwapData } from "../StarknetSwapData";
5
- import { StarknetTx } from "../../base/modules/StarknetTransactions";
6
- import { StarknetBtcStoredHeader } from "../../btcrelay/headers/StarknetBtcStoredHeader";
7
- export declare class SwapClaim extends StarknetSwapModule {
8
- private static readonly GasCosts;
9
- /**
10
- * Claim action which uses the provided witness for claiming the swap
11
- *
12
- * @param signer
13
- * @param swapData
14
- * @param witness
15
- * @param claimHandlerGas
16
- * @constructor
17
- * @private
18
- */
19
- private Claim;
20
- /**
21
- * Creates transactions claiming the swap using a secret (for HTLC swaps)
22
- *
23
- * @param signer
24
- * @param swapData swap to claim
25
- * @param secret hex encoded secret pre-image to the HTLC hash
26
- * @param checkExpiry whether to check if the swap is already expired (trying to claim an expired swap with a secret
27
- * is dangerous because we might end up revealing the secret to the counterparty without being able to claim the swap)
28
- * @param feeRate fee rate to use for the transaction
29
- */
30
- txsClaimWithSecret(signer: string, swapData: StarknetSwapData, secret: string, checkExpiry?: boolean, feeRate?: string): Promise<StarknetTx[]>;
31
- /**
32
- * Creates transaction claiming the swap using a confirmed transaction data (for BTC on-chain swaps)
33
- *
34
- * @param signer
35
- * @param swapData swap to claim
36
- * @param tx bitcoin transaction that satisfies the swap condition
37
- * @param requiredConfirmations
38
- * @param vout vout of the bitcoin transaction that satisfies the swap condition
39
- * @param commitedHeader commited header data from btc relay (fetched internally if null)
40
- * @param synchronizer optional synchronizer to use in case we need to sync up the btc relay ourselves
41
- * @param feeRate fee rate to be used for the transactions
42
- */
43
- txsClaimWithTxData(signer: string, swapData: StarknetSwapData, tx: {
44
- blockhash: string;
45
- confirmations: number;
46
- txid: string;
47
- hex: string;
48
- height: number;
49
- }, requiredConfirmations: number, vout: number, commitedHeader?: StarknetBtcStoredHeader, synchronizer?: RelaySynchronizer<StarknetBtcStoredHeader, StarknetTx, any>, feeRate?: string): Promise<StarknetTx[] | null>;
50
- /**
51
- * Get the estimated starknet transaction fee of the claim transaction
52
- */
53
- getClaimFee(swapData: StarknetSwapData, feeRate?: string): Promise<BN>;
54
- }
@@ -1,115 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SwapClaim = void 0;
13
- const base_1 = require("@atomiqlabs/base");
14
- const Utils_1 = require("../../../utils/Utils");
15
- const StarknetSwapModule_1 = require("../StarknetSwapModule");
16
- const StarknetAction_1 = require("../../base/StarknetAction");
17
- const StarknetFees_1 = require("../../base/modules/StarknetFees");
18
- class SwapClaim extends StarknetSwapModule_1.StarknetSwapModule {
19
- /**
20
- * Claim action which uses the provided witness for claiming the swap
21
- *
22
- * @param signer
23
- * @param swapData
24
- * @param witness
25
- * @param claimHandlerGas
26
- * @constructor
27
- * @private
28
- */
29
- Claim(signer, swapData, witness, claimHandlerGas) {
30
- return new StarknetAction_1.StarknetAction(signer, this.root, this.contract.populateTransaction.claim(swapData.toEscrowStruct(), witness), (0, StarknetAction_1.sumStarknetGas)(swapData.payOut ? SwapClaim.GasCosts.CLAIM_PAY_OUT : SwapClaim.GasCosts.CLAIM, claimHandlerGas));
31
- }
32
- /**
33
- * Creates transactions claiming the swap using a secret (for HTLC swaps)
34
- *
35
- * @param signer
36
- * @param swapData swap to claim
37
- * @param secret hex encoded secret pre-image to the HTLC hash
38
- * @param checkExpiry whether to check if the swap is already expired (trying to claim an expired swap with a secret
39
- * is dangerous because we might end up revealing the secret to the counterparty without being able to claim the swap)
40
- * @param feeRate fee rate to use for the transaction
41
- */
42
- txsClaimWithSecret(signer, swapData, secret, checkExpiry, feeRate) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- //We need to be sure that this transaction confirms in time, otherwise we reveal the secret to the counterparty
45
- // and won't claim the funds
46
- if (checkExpiry && (yield this.root.isExpired(swapData.claimer.toString(), swapData))) {
47
- throw new base_1.SwapDataVerificationError("Not enough time to reliably pay the invoice");
48
- }
49
- const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
50
- if (claimHandler == null)
51
- throw new base_1.SwapDataVerificationError("Unknown claim handler!");
52
- if (claimHandler.getType() !== base_1.ChainSwapType.HTLC)
53
- throw new base_1.SwapDataVerificationError("Invalid claim handler!");
54
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
55
- const { initialTxns, witness } = yield claimHandler.getWitness(signer, swapData, secret, feeRate);
56
- const action = this.Claim(signer, swapData, witness, claimHandler.getGas(swapData));
57
- yield action.addToTxs(initialTxns, feeRate);
58
- this.logger.debug("txsClaimWithSecret(): creating claim transaction, swap: " + swapData.getClaimHash() + " witness: ", witness.map(Utils_1.toHex));
59
- return initialTxns;
60
- });
61
- }
62
- /**
63
- * Creates transaction claiming the swap using a confirmed transaction data (for BTC on-chain swaps)
64
- *
65
- * @param signer
66
- * @param swapData swap to claim
67
- * @param tx bitcoin transaction that satisfies the swap condition
68
- * @param requiredConfirmations
69
- * @param vout vout of the bitcoin transaction that satisfies the swap condition
70
- * @param commitedHeader commited header data from btc relay (fetched internally if null)
71
- * @param synchronizer optional synchronizer to use in case we need to sync up the btc relay ourselves
72
- * @param feeRate fee rate to be used for the transactions
73
- */
74
- txsClaimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, feeRate) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
77
- if (claimHandler == null)
78
- throw new base_1.SwapDataVerificationError("Unknown claim handler!");
79
- if (claimHandler.getType() !== base_1.ChainSwapType.CHAIN_NONCED &&
80
- claimHandler.getType() !== base_1.ChainSwapType.CHAIN_TXID &&
81
- claimHandler.getType() !== base_1.ChainSwapType.CHAIN)
82
- throw new base_1.SwapDataVerificationError("Invalid claim handler!");
83
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
84
- const { initialTxns, witness } = yield claimHandler.getWitness(signer, swapData, {
85
- tx,
86
- vout,
87
- requiredConfirmations,
88
- commitedHeader,
89
- btcRelay: this.root.btcRelay,
90
- synchronizer,
91
- }, feeRate);
92
- const action = this.Claim(signer, swapData, witness, claimHandler.getGas(swapData));
93
- yield action.addToTxs(initialTxns, feeRate);
94
- return initialTxns;
95
- });
96
- }
97
- /**
98
- * Get the estimated starknet transaction fee of the claim transaction
99
- */
100
- getClaimFee(swapData, feeRate) {
101
- return __awaiter(this, void 0, void 0, function* () {
102
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
103
- let gasRequired = swapData.payOut ? SwapClaim.GasCosts.CLAIM_PAY_OUT : SwapClaim.GasCosts.CLAIM;
104
- const claimHandler = this.root.claimHandlersByAddress[swapData.claimHandler.toLowerCase()];
105
- if (claimHandler != null)
106
- gasRequired = (0, StarknetAction_1.sumStarknetGas)(gasRequired, claimHandler.getGas(swapData));
107
- return StarknetFees_1.StarknetFees.getGasFee(gasRequired.l1, feeRate);
108
- });
109
- }
110
- }
111
- exports.SwapClaim = SwapClaim;
112
- SwapClaim.GasCosts = {
113
- CLAIM: { l1: 500, l2: 0 },
114
- CLAIM_PAY_OUT: { l1: 1000, l2: 0 }
115
- };
@@ -1,79 +0,0 @@
1
- import * as BN from "bn.js";
2
- import { StarknetSwapData } from "../StarknetSwapData";
3
- import { StarknetSwapModule } from "../StarknetSwapModule";
4
- import { StarknetSigner } from "../../wallet/StarknetSigner";
5
- import { StarknetTx } from "../../base/modules/StarknetTransactions";
6
- export declare class SwapInit extends StarknetSwapModule {
7
- private static readonly GasCosts;
8
- /**
9
- * bare Init action based on the data passed in swapData
10
- *
11
- * @param swapData
12
- * @param timeout
13
- * @param signature
14
- * @private
15
- */
16
- private Init;
17
- /**
18
- * Returns auth prefix to be used with a specific swap, payIn=true & payIn=false use different prefixes (these
19
- * actually have no meaning for the smart contract/solana program in the Solana case)
20
- *
21
- * @param swapData
22
- * @private
23
- */
24
- private getAuthPrefix;
25
- /**
26
- * Signs swap initialization authorization, using data from preFetchedBlockData if provided & still valid (subject
27
- * to SIGNATURE_PREFETCH_DATA_VALIDITY)
28
- *
29
- * @param signer
30
- * @param swapData
31
- * @param authorizationTimeout
32
- * @public
33
- */
34
- signSwapInitialization(signer: StarknetSigner, swapData: StarknetSwapData, authorizationTimeout: number): Promise<{
35
- prefix: string;
36
- timeout: string;
37
- signature: string;
38
- }>;
39
- /**
40
- * Checks whether the provided signature data is valid, using preFetchedData if provided and still valid
41
- *
42
- * @param swapData
43
- * @param timeout
44
- * @param prefix
45
- * @param signature
46
- * @public
47
- */
48
- isSignatureValid(swapData: StarknetSwapData, timeout: string, prefix: string, signature: string): Promise<null>;
49
- /**
50
- * Gets expiry of the provided signature data, this is a minimum of slot expiry & swap signature expiry
51
- *
52
- * @param timeout
53
- * @public
54
- */
55
- getSignatureExpiry(timeout: string): Promise<number>;
56
- /**
57
- * Checks whether signature is expired for good, uses expiry + grace period
58
- *
59
- * @param timeout
60
- * @public
61
- */
62
- isSignatureExpired(timeout: string): Promise<boolean>;
63
- /**
64
- * Creates init transaction with a valid signature from an LP
65
- *
66
- * @param swapData swap to initialize
67
- * @param timeout init signature timeout
68
- * @param prefix init signature prefix
69
- * @param signature init signature
70
- * @param skipChecks whether to skip signature validity checks
71
- * @param feeRate fee rate to use for the transaction
72
- */
73
- txsInit(swapData: StarknetSwapData, timeout: string, prefix: string, signature: string, skipChecks?: boolean, feeRate?: string): Promise<StarknetTx[]>;
74
- /**
75
- * Get the estimated solana fee of the init transaction, this includes the required deposit for creating swap PDA
76
- * and also deposit for ATAs
77
- */
78
- getInitFee(swapData?: StarknetSwapData, feeRate?: string): Promise<BN>;
79
- }
@@ -1,174 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SwapInit = void 0;
13
- const base_1 = require("@atomiqlabs/base");
14
- const BN = require("bn.js");
15
- const Utils_1 = require("../../../utils/Utils");
16
- const buffer_1 = require("buffer");
17
- const StarknetAction_1 = require("../../base/StarknetAction");
18
- const StarknetSwapModule_1 = require("../StarknetSwapModule");
19
- const StarknetFees_1 = require("../../base/modules/StarknetFees");
20
- const Initialize = [
21
- { name: 'Swap hash', type: 'felt' },
22
- { name: 'Timeout', type: 'timestamp' }
23
- ];
24
- class SwapInit extends StarknetSwapModule_1.StarknetSwapModule {
25
- /**
26
- * bare Init action based on the data passed in swapData
27
- *
28
- * @param swapData
29
- * @param timeout
30
- * @param signature
31
- * @private
32
- */
33
- Init(swapData, timeout, signature) {
34
- return new StarknetAction_1.StarknetAction(swapData.payIn ? swapData.offerer : swapData.claimer, this.root, this.contract.populateTransaction.initialize(swapData.toEscrowStruct(), signature, (0, Utils_1.toBigInt)(timeout), swapData.extraData == null || swapData.extraData === "" ? [] : (0, Utils_1.bufferToBytes31Span)(buffer_1.Buffer.from(swapData.extraData, "hex")).map(Utils_1.toHex)), swapData.payIn ? SwapInit.GasCosts.INIT_PAY_IN : SwapInit.GasCosts.INIT);
35
- }
36
- /**
37
- * Returns auth prefix to be used with a specific swap, payIn=true & payIn=false use different prefixes (these
38
- * actually have no meaning for the smart contract/solana program in the Solana case)
39
- *
40
- * @param swapData
41
- * @private
42
- */
43
- getAuthPrefix(swapData) {
44
- return swapData.isPayIn() ? "claim_initialize" : "initialize";
45
- }
46
- /**
47
- * Signs swap initialization authorization, using data from preFetchedBlockData if provided & still valid (subject
48
- * to SIGNATURE_PREFETCH_DATA_VALIDITY)
49
- *
50
- * @param signer
51
- * @param swapData
52
- * @param authorizationTimeout
53
- * @public
54
- */
55
- signSwapInitialization(signer, swapData, authorizationTimeout) {
56
- return __awaiter(this, void 0, void 0, function* () {
57
- const authTimeout = Math.floor(Date.now() / 1000) + authorizationTimeout;
58
- const signature = yield this.root.Signatures.signTypedMessage(signer, Initialize, "Initialize", {
59
- "Swap hash": (0, Utils_1.toHex)(swapData.getEscrowHash()),
60
- "Timeout": (0, Utils_1.toHex)(authTimeout)
61
- });
62
- return {
63
- prefix: this.getAuthPrefix(swapData),
64
- timeout: authorizationTimeout.toString(10),
65
- signature
66
- };
67
- });
68
- }
69
- /**
70
- * Checks whether the provided signature data is valid, using preFetchedData if provided and still valid
71
- *
72
- * @param swapData
73
- * @param timeout
74
- * @param prefix
75
- * @param signature
76
- * @public
77
- */
78
- isSignatureValid(swapData, timeout, prefix, signature) {
79
- return __awaiter(this, void 0, void 0, function* () {
80
- const sender = swapData.isPayIn() ? swapData.offerer : swapData.claimer;
81
- const signer = swapData.isPayIn() ? swapData.claimer : swapData.offerer;
82
- if (!swapData.isPayIn() && (yield this.root.isExpired(sender.toString(), swapData))) {
83
- throw new base_1.SignatureVerificationError("Swap will expire too soon!");
84
- }
85
- if (prefix !== this.getAuthPrefix(swapData))
86
- throw new base_1.SignatureVerificationError("Invalid prefix");
87
- const currentTimestamp = new BN(Math.floor(Date.now() / 1000));
88
- const timeoutBN = new BN(timeout);
89
- const isExpired = timeoutBN.sub(currentTimestamp).lt(new BN(this.root.authGracePeriod));
90
- if (isExpired)
91
- throw new base_1.SignatureVerificationError("Authorization expired!");
92
- const valid = yield this.root.Signatures.isValidSignature(signature, signer, Initialize, "Initialize", {
93
- "Swap hash": (0, Utils_1.toHex)(swapData.getEscrowHash()),
94
- "Timeout": (0, Utils_1.toHex)(timeoutBN)
95
- });
96
- if (!valid)
97
- throw new base_1.SignatureVerificationError("Invalid signature!");
98
- return null;
99
- });
100
- }
101
- /**
102
- * Gets expiry of the provided signature data, this is a minimum of slot expiry & swap signature expiry
103
- *
104
- * @param timeout
105
- * @public
106
- */
107
- getSignatureExpiry(timeout) {
108
- return __awaiter(this, void 0, void 0, function* () {
109
- const now = Date.now();
110
- const timeoutExpiryTime = (parseInt(timeout) - this.root.authGracePeriod) * 1000;
111
- if (timeoutExpiryTime < now)
112
- return 0;
113
- return timeoutExpiryTime;
114
- });
115
- }
116
- /**
117
- * Checks whether signature is expired for good, uses expiry + grace period
118
- *
119
- * @param timeout
120
- * @public
121
- */
122
- isSignatureExpired(timeout) {
123
- return __awaiter(this, void 0, void 0, function* () {
124
- return (parseInt(timeout) + this.root.authGracePeriod) * 1000 < Date.now();
125
- });
126
- }
127
- /**
128
- * Creates init transaction with a valid signature from an LP
129
- *
130
- * @param swapData swap to initialize
131
- * @param timeout init signature timeout
132
- * @param prefix init signature prefix
133
- * @param signature init signature
134
- * @param skipChecks whether to skip signature validity checks
135
- * @param feeRate fee rate to use for the transaction
136
- */
137
- txsInit(swapData, timeout, prefix, signature, skipChecks, feeRate) {
138
- return __awaiter(this, void 0, void 0, function* () {
139
- const sender = swapData.isPayIn() ? swapData.offerer : swapData.claimer;
140
- if (!skipChecks) {
141
- const [_, payStatus] = yield Promise.all([
142
- (0, Utils_1.tryWithRetries)(() => this.isSignatureValid(swapData, timeout, prefix, signature), this.retryPolicy, (e) => e instanceof base_1.SignatureVerificationError),
143
- (0, Utils_1.tryWithRetries)(() => this.root.getCommitStatus(sender, swapData), this.retryPolicy)
144
- ]);
145
- if (payStatus !== base_1.SwapCommitStatus.NOT_COMMITED)
146
- throw new base_1.SwapDataVerificationError("Invoice already being paid for or paid");
147
- }
148
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
149
- const initAction = this.Init(swapData, new BN(timeout), JSON.parse(signature));
150
- if (swapData.payIn)
151
- initAction.addAction(this.root.Tokens.Approve(sender, this.contract.address, swapData.token, swapData.amount), 0); //Add erc20 approve
152
- if (!swapData.getTotalDeposit().isZero())
153
- initAction.addAction(this.root.Tokens.Approve(sender, this.contract.address, swapData.feeToken, swapData.getTotalDeposit()), 0); //Add deposit erc20 approve
154
- this.logger.debug("txsInitPayIn(): create swap init TX, swap: " + swapData.getClaimHash() +
155
- " feerate: " + feeRate);
156
- return [yield initAction.tx(feeRate)];
157
- });
158
- }
159
- /**
160
- * Get the estimated solana fee of the init transaction, this includes the required deposit for creating swap PDA
161
- * and also deposit for ATAs
162
- */
163
- getInitFee(swapData, feeRate) {
164
- return __awaiter(this, void 0, void 0, function* () {
165
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
166
- return StarknetFees_1.StarknetFees.getGasFee(swapData.payIn ? SwapInit.GasCosts.INIT_PAY_IN.l1 : SwapInit.GasCosts.INIT.l1, feeRate);
167
- });
168
- }
169
- }
170
- exports.SwapInit = SwapInit;
171
- SwapInit.GasCosts = {
172
- INIT: { l1: 500, l2: 0 },
173
- INIT_PAY_IN: { l1: 1000, l2: 0 },
174
- };
@@ -1,63 +0,0 @@
1
- import * as BN from "bn.js";
2
- import { StarknetSwapModule } from "../StarknetSwapModule";
3
- import { StarknetSwapData } from "../StarknetSwapData";
4
- import { StarknetSwapContract } from "../StarknetSwapContract";
5
- import { StarknetTx } from "../../base/modules/StarknetTransactions";
6
- import { StarknetSigner } from "../../wallet/StarknetSigner";
7
- export declare class SwapRefund extends StarknetSwapModule {
8
- private static readonly GasCosts;
9
- /**
10
- * Action for generic Refund instruction
11
- *
12
- * @param signer
13
- * @param swapData
14
- * @param witness
15
- * @param handlerGas
16
- * @constructor
17
- * @private
18
- */
19
- private Refund;
20
- /**
21
- * Action for cooperative refunding with signature
22
- *
23
- * @param sender
24
- * @param swapData
25
- * @param timeout
26
- * @param signature
27
- * @constructor
28
- * @private
29
- */
30
- private RefundWithSignature;
31
- constructor(root: StarknetSwapContract);
32
- signSwapRefund(signer: StarknetSigner, swapData: StarknetSwapData, authorizationTimeout: number): Promise<{
33
- prefix: string;
34
- timeout: string;
35
- signature: string;
36
- }>;
37
- isSignatureValid(swapData: StarknetSwapData, timeout: string, prefix: string, signature: string): Promise<null>;
38
- /**
39
- * Creates transactions required for refunding timed out swap
40
- *
41
- * @param swapData swap data to refund
42
- * @param check whether to check if swap is already expired and refundable
43
- * @param feeRate fee rate to be used for the transactions
44
- * @param witnessData
45
- */
46
- txsRefund<T>(swapData: StarknetSwapData, check?: boolean, feeRate?: string, witnessData?: T): Promise<StarknetTx[]>;
47
- /**
48
- * Creates transactions required for refunding the swap with authorization signature, also unwraps WSOL to SOL
49
- *
50
- * @param swapData swap data to refund
51
- * @param timeout signature timeout
52
- * @param prefix signature prefix of the counterparty
53
- * @param signature signature of the counterparty
54
- * @param check whether to check if swap is committed before attempting refund
55
- * @param feeRate fee rate to be used for the transactions
56
- */
57
- txsRefundWithAuthorization(swapData: StarknetSwapData, timeout: string, prefix: string, signature: string, check?: boolean, feeRate?: string): Promise<StarknetTx[]>;
58
- /**
59
- * Get the estimated solana transaction fee of the refund transaction, in the worst case scenario in case where the
60
- * ATA needs to be initialized again (i.e. adding the ATA rent exempt lamports to the fee)
61
- */
62
- getRefundFee(swapData: StarknetSwapData, feeRate?: string): Promise<BN>;
63
- }
@@ -1,149 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SwapRefund = void 0;
13
- const base_1 = require("@atomiqlabs/base");
14
- const BN = require("bn.js");
15
- const Utils_1 = require("../../../utils/Utils");
16
- const StarknetSwapModule_1 = require("../StarknetSwapModule");
17
- const StarknetAction_1 = require("../../base/StarknetAction");
18
- const StarknetFees_1 = require("../../base/modules/StarknetFees");
19
- const Refund = [
20
- { name: 'Swap hash', type: 'felt' },
21
- { name: 'Timeout', type: 'timestamp' }
22
- ];
23
- class SwapRefund extends StarknetSwapModule_1.StarknetSwapModule {
24
- /**
25
- * Action for generic Refund instruction
26
- *
27
- * @param signer
28
- * @param swapData
29
- * @param witness
30
- * @param handlerGas
31
- * @constructor
32
- * @private
33
- */
34
- Refund(signer, swapData, witness, handlerGas) {
35
- return new StarknetAction_1.StarknetAction(signer, this.root, this.contract.populateTransaction.refund(swapData.toEscrowStruct(), witness), (0, StarknetAction_1.sumStarknetGas)(swapData.payIn ? SwapRefund.GasCosts.REFUND_PAY_OUT : SwapRefund.GasCosts.REFUND, handlerGas));
36
- }
37
- /**
38
- * Action for cooperative refunding with signature
39
- *
40
- * @param sender
41
- * @param swapData
42
- * @param timeout
43
- * @param signature
44
- * @constructor
45
- * @private
46
- */
47
- RefundWithSignature(sender, swapData, timeout, signature) {
48
- return new StarknetAction_1.StarknetAction(sender, this.root, this.contract.populateTransaction.cooperative_refund(swapData.toEscrowStruct(), signature, BigInt(timeout)), swapData.payIn ? SwapRefund.GasCosts.REFUND_PAY_OUT : SwapRefund.GasCosts.REFUND);
49
- }
50
- constructor(root) {
51
- super(root);
52
- }
53
- signSwapRefund(signer, swapData, authorizationTimeout) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const authPrefix = "refund";
56
- const authTimeout = Math.floor(Date.now() / 1000) + authorizationTimeout;
57
- const signature = yield this.root.Signatures.signTypedMessage(signer, Refund, "Refund", {
58
- "Swap hash": (0, Utils_1.toHex)(swapData.getEscrowHash()),
59
- "Timeout": (0, Utils_1.toHex)(authTimeout)
60
- });
61
- return {
62
- prefix: authPrefix,
63
- timeout: authTimeout.toString(10),
64
- signature: signature
65
- };
66
- });
67
- }
68
- isSignatureValid(swapData, timeout, prefix, signature) {
69
- return __awaiter(this, void 0, void 0, function* () {
70
- if (prefix !== "refund")
71
- throw new base_1.SignatureVerificationError("Invalid prefix");
72
- const expiryTimestamp = new BN(timeout);
73
- const currentTimestamp = new BN(Math.floor(Date.now() / 1000));
74
- const isExpired = expiryTimestamp.sub(currentTimestamp).lt(new BN(this.root.authGracePeriod));
75
- if (isExpired)
76
- throw new base_1.SignatureVerificationError("Authorization expired!");
77
- const valid = yield this.root.Signatures.isValidSignature(signature, swapData.claimer, Refund, "Refund", {
78
- "Swap hash": (0, Utils_1.toHex)(swapData.getEscrowHash()),
79
- "Timeout": (0, Utils_1.toHex)(expiryTimestamp)
80
- });
81
- if (!valid) {
82
- throw new base_1.SignatureVerificationError("Invalid signature!");
83
- }
84
- return null;
85
- });
86
- }
87
- /**
88
- * Creates transactions required for refunding timed out swap
89
- *
90
- * @param swapData swap data to refund
91
- * @param check whether to check if swap is already expired and refundable
92
- * @param feeRate fee rate to be used for the transactions
93
- * @param witnessData
94
- */
95
- txsRefund(swapData, check, feeRate, witnessData) {
96
- return __awaiter(this, void 0, void 0, function* () {
97
- const refundHandler = this.root.refundHandlersByAddress[swapData.refundHandler.toLowerCase()];
98
- if (refundHandler == null)
99
- throw new Error("Invalid refund handler");
100
- if (check && !(yield (0, Utils_1.tryWithRetries)(() => this.root.isRequestRefundable(swapData.offerer.toString(), swapData), this.retryPolicy))) {
101
- throw new base_1.SwapDataVerificationError("Not refundable yet!");
102
- }
103
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
104
- const { initialTxns, witness } = yield refundHandler.getWitness(swapData.offerer, swapData, witnessData, feeRate);
105
- const action = this.Refund(swapData.offerer, swapData, witness, refundHandler.getGas(swapData));
106
- yield action.addToTxs(initialTxns, feeRate);
107
- this.logger.debug("txsRefund(): creating refund transaction, swap: " + swapData.getClaimHash());
108
- return initialTxns;
109
- });
110
- }
111
- /**
112
- * Creates transactions required for refunding the swap with authorization signature, also unwraps WSOL to SOL
113
- *
114
- * @param swapData swap data to refund
115
- * @param timeout signature timeout
116
- * @param prefix signature prefix of the counterparty
117
- * @param signature signature of the counterparty
118
- * @param check whether to check if swap is committed before attempting refund
119
- * @param feeRate fee rate to be used for the transactions
120
- */
121
- txsRefundWithAuthorization(swapData, timeout, prefix, signature, check, feeRate) {
122
- return __awaiter(this, void 0, void 0, function* () {
123
- if (check && !(yield (0, Utils_1.tryWithRetries)(() => this.root.isCommited(swapData), this.retryPolicy))) {
124
- throw new base_1.SwapDataVerificationError("Not correctly committed");
125
- }
126
- yield (0, Utils_1.tryWithRetries)(() => this.isSignatureValid(swapData, timeout, prefix, signature), this.retryPolicy, (e) => e instanceof base_1.SignatureVerificationError);
127
- const action = this.RefundWithSignature(swapData.offerer, swapData, timeout, JSON.parse(signature));
128
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
129
- this.logger.debug("txsRefundWithAuthorization(): creating refund transaction, swap: " + swapData.getClaimHash() +
130
- " auth expiry: " + timeout + " signature: " + signature);
131
- return [yield action.tx(feeRate)];
132
- });
133
- }
134
- /**
135
- * Get the estimated solana transaction fee of the refund transaction, in the worst case scenario in case where the
136
- * ATA needs to be initialized again (i.e. adding the ATA rent exempt lamports to the fee)
137
- */
138
- getRefundFee(swapData, feeRate) {
139
- return __awaiter(this, void 0, void 0, function* () {
140
- feeRate !== null && feeRate !== void 0 ? feeRate : (feeRate = yield this.root.Fees.getFeeRate());
141
- return StarknetFees_1.StarknetFees.getGasFee(swapData.payIn ? SwapRefund.GasCosts.REFUND_PAY_OUT.l1 : SwapRefund.GasCosts.REFUND.l1, feeRate);
142
- });
143
- }
144
- }
145
- exports.SwapRefund = SwapRefund;
146
- SwapRefund.GasCosts = {
147
- REFUND: { l1: 750, l2: 0 },
148
- REFUND_PAY_OUT: { l1: 1250, l2: 0 }
149
- };