@chainflip/bitcoin 1.2.7 → 2.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,319 +1,7 @@
1
- 'use strict';
1
+ const require_address = require('./address.cjs');
2
+ const require_deposit = require('./deposit.cjs');
2
3
 
3
- var assertion = require('@chainflip/utils/assertion');
4
- var bytes = require('@chainflip/utils/bytes');
5
- var bitcoin = require('bitcoinjs-lib');
6
- var base58 = require('@chainflip/utils/base58');
7
- var chainflip = require('@chainflip/utils/chainflip');
8
- var consts = require('@chainflip/utils/consts');
9
- var ss58 = require('@chainflip/utils/ss58');
10
- var BigNumber2 = require('bignumber.js');
11
- var url = require('@chainflip/utils/url');
12
- var zod = require('zod');
13
- var scaleTs = require('scale-ts');
14
-
15
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
-
17
- function _interopNamespace(e) {
18
- if (e && e.__esModule) return e;
19
- var n = Object.create(null);
20
- if (e) {
21
- Object.keys(e).forEach(function (k) {
22
- if (k !== 'default') {
23
- var d = Object.getOwnPropertyDescriptor(e, k);
24
- Object.defineProperty(n, k, d.get ? d : {
25
- enumerable: true,
26
- get: function () { return e[k]; }
27
- });
28
- }
29
- });
30
- }
31
- n.default = e;
32
- return Object.freeze(n);
33
- }
34
-
35
- var bitcoin__namespace = /*#__PURE__*/_interopNamespace(bitcoin);
36
- var base58__namespace = /*#__PURE__*/_interopNamespace(base58);
37
- var ss58__namespace = /*#__PURE__*/_interopNamespace(ss58);
38
- var BigNumber2__default = /*#__PURE__*/_interopDefault(BigNumber2);
39
-
40
- // src/address.ts
41
-
42
- // src/consts.ts
43
- var networkMap = {
44
- mainnet: "mainnet",
45
- perseverance: "testnet",
46
- sisyphos: "testnet",
47
- testnet: "testnet",
48
- backspin: "regtest",
49
- regtest: "regtest"
50
- };
51
-
52
- // src/address.ts
53
- var p2pkhAddressVersion = {
54
- mainnet: 0,
55
- testnet: 111,
56
- regtest: 111
57
- };
58
- var p2shAddressVersion = {
59
- mainnet: 5,
60
- testnet: 196,
61
- regtest: 196
62
- };
63
- var networkHrp = {
64
- mainnet: "bc",
65
- testnet: "tb",
66
- regtest: "bcrt"
67
- };
68
- var segwitVersions = {
69
- P2WPKH: 0,
70
- P2WSH: 0,
71
- Taproot: 1
72
- };
73
- var byteLikeToUint8Array = (data) => typeof data === "string" ? bytes.hexToBytes(data) : new Uint8Array(data);
74
- var encodeAddress = (data, kind, cfOrBtcnetwork) => {
75
- const btcNetwork = networkMap[cfOrBtcnetwork];
76
- assertion.assert(btcNetwork, `Invalid network: ${cfOrBtcnetwork}`);
77
- assertion.assert(data.length % 2 === 0, "bytes must have an even number of characters");
78
- assertion.assert(
79
- typeof data !== "string" || /^(0x)?[0-9a-f]*$/.test(data),
80
- "bytes are not a valid hex string"
81
- );
82
- const bytes = byteLikeToUint8Array(data);
83
- switch (kind) {
84
- case "P2PKH":
85
- case "P2SH": {
86
- const version = (kind === "P2SH" ? p2shAddressVersion : p2pkhAddressVersion)[btcNetwork];
87
- return bitcoin__namespace.address.toBase58Check(bytes, version);
88
- }
89
- case "P2WPKH":
90
- case "P2WSH":
91
- case "Taproot":
92
- return bitcoin__namespace.address.toBech32(bytes, segwitVersions[kind], networkHrp[btcNetwork]);
93
- default:
94
- throw new Error(`Invalid address type: ${kind}`);
95
- }
96
- };
97
- var decodeAddress = (address2, cfOrBtcNetwork) => {
98
- const network = networkMap[cfOrBtcNetwork];
99
- if (/^[13mn2]/.test(address2)) {
100
- const { hash, version } = bitcoin__namespace.address.fromBase58Check(address2);
101
- if (version === p2pkhAddressVersion[network]) {
102
- return { type: "P2PKH", data: hash, version };
103
- }
104
- if (version === p2shAddressVersion[network]) {
105
- return { type: "P2SH", data: hash, version };
106
- }
107
- throw new TypeError(`Invalid version: ${version}`);
108
- }
109
- if (/^(bc|tb|bcrt)1/.test(address2)) {
110
- const { data, prefix, version } = bitcoin__namespace.address.fromBech32(address2);
111
- assertion.assert(prefix === networkHrp[network], `Invalid prefix: ${prefix}`);
112
- let type;
113
- if (version === 0 && data.length === 20) {
114
- type = "P2WPKH";
115
- } else if (version === 0) {
116
- type = "P2WSH";
117
- } else if (version === 1) {
118
- type = "Taproot";
119
- } else {
120
- throw new TypeError(`Invalid version: ${version}`);
121
- }
122
- return { hrp: prefix, data, type, version };
123
- }
124
- throw new TypeError(`Invalid address "${address2}" for network "${network}"`);
125
- };
126
- var isValidAddressForNetwork = (address2, cfOrBtcNetwork) => {
127
- try {
128
- decodeAddress(address2, cfOrBtcNetwork);
129
- return true;
130
- } catch {
131
- return false;
132
- }
133
- };
134
- var hexString = zod.z.string().regex(/^([0-9a-f]{2})+$/, { message: "expected hex string" });
135
- var vout = zod.z.object({
136
- value: zod.z.number().transform((n) => BigInt(new BigNumber2__default.default(n).shiftedBy(8).toFixed(0))),
137
- n: zod.z.number()
138
- });
139
- var nulldataVout = zod.z.object({
140
- scriptPubKey: zod.z.object({
141
- type: zod.z.literal("nulldata"),
142
- // remove OP_RETURN and PUSH_BYTES_XX
143
- hex: hexString.transform((x) => bytes.hexToBytes(`0x${x.slice(4)}`))
144
- })
145
- }).and(vout);
146
- var addressVout = zod.z.object({
147
- scriptPubKey: zod.z.object({
148
- type: zod.z.enum([
149
- "witness_v1_taproot",
150
- "witness_v0_scripthash",
151
- "witness_v0_keyhash",
152
- "pubkeyhash",
153
- "scripthash"
154
- ]),
155
- address: zod.z.string()
156
- })
157
- }).and(vout);
158
- var txSchema = zod.z.object({
159
- vout: zod.z.tuple([addressVout, nulldataVout, addressVout]),
160
- blockhash: hexString.nullish()
161
- });
162
- var blockSchema = zod.z.object({
163
- height: zod.z.number()
164
- });
165
- var responseSchemas = {
166
- getrawtransaction: txSchema,
167
- getblock: blockSchema
168
- };
169
- var rpcResponse = zod.z.union([
170
- zod.z.object({ result: zod.z.null(), error: zod.z.object({ code: zod.z.number(), message: zod.z.string() }) }),
171
- zod.z.object({ result: zod.z.unknown(), error: zod.z.null() })
172
- ]);
173
- var makeRequest = async (rpcUrl, method, params) => {
174
- const { url: url$1, headers } = url.parseUrlWithBasicAuth(rpcUrl);
175
- const res = await fetch(url$1, {
176
- method: "POST",
177
- headers: {
178
- ...headers,
179
- "Content-Type": "application/json"
180
- },
181
- body: JSON.stringify({
182
- jsonrpc: "2.0",
183
- id: 1,
184
- method,
185
- params
186
- })
187
- });
188
- const text = await res.text();
189
- let json;
190
- try {
191
- json = JSON.parse(text);
192
- } catch {
193
- if (res.status !== 200) {
194
- throw new Error(`HTTP error [${res.status}]: ${text || res.statusText}`);
195
- }
196
- throw new Error(`Invalid JSON response: ${text}`);
197
- }
198
- const result = rpcResponse.parse(json);
199
- if (result.error) {
200
- if (result.error.code === -5) return null;
201
- throw new Error(`RPC error [${result.error.code}]: ${result.error.message}`);
202
- }
203
- const parseResult = responseSchemas[method].safeParse(result.result);
204
- if (!parseResult.success) {
205
- if (method === "getrawtransaction") return null;
206
- throw parseResult.error;
207
- }
208
- return parseResult.data;
209
- };
210
- var addressByteLengths = {
211
- Bitcoin: void 0,
212
- Arbitrum: 20,
213
- Ethereum: 20,
214
- Solana: 32,
215
- Polkadot: 32,
216
- Assethub: 32
217
- };
218
- var createSwapDataCodecV0 = (asset) => scaleTs.Struct({
219
- version: scaleTs.u8,
220
- destinationAsset: scaleTs.u8,
221
- destinationAddress: scaleTs.Bytes(addressByteLengths[chainflip.assetConstants[asset].chain]),
222
- parameters: scaleTs.Struct({
223
- retryDuration: scaleTs.u16,
224
- minOutputAmount: scaleTs.u128,
225
- numberOfChunks: scaleTs.u16,
226
- chunkInterval: scaleTs.u16,
227
- boostFee: scaleTs.u8,
228
- brokerFee: scaleTs.u8,
229
- affiliates: scaleTs.Vector(scaleTs.Struct({ accountIndex: scaleTs.u8, commissionBps: scaleTs.u8 }))
230
- })
231
- });
232
- var createSwapDataCodecV1 = (asset) => scaleTs.Struct({
233
- version: scaleTs.u8,
234
- destinationAsset: scaleTs.u8,
235
- destinationAddress: scaleTs.Bytes(addressByteLengths[chainflip.assetConstants[asset].chain]),
236
- parameters: scaleTs.Struct({
237
- retryDuration: scaleTs.u16,
238
- minOutputAmount: scaleTs.u128,
239
- maxOraclePriceSlippage: scaleTs.u8,
240
- numberOfChunks: scaleTs.u16,
241
- chunkInterval: scaleTs.u16,
242
- boostFee: scaleTs.u8,
243
- brokerFee: scaleTs.u8,
244
- affiliates: scaleTs.Vector(scaleTs.Struct({ accountIndex: scaleTs.u8, commissionBps: scaleTs.u8 }))
245
- })
246
- });
247
-
248
- // src/deposit.ts
249
- var encodeChainAddress = (data, asset) => {
250
- switch (chainflip.assetConstants[asset].chain) {
251
- case "Solana":
252
- return base58__namespace.encode(data);
253
- case "Assethub":
254
- case "Polkadot":
255
- return ss58__namespace.encode({ data, ss58Format: consts.POLKADOT_SS58_PREFIX });
256
- case "Ethereum":
257
- case "Arbitrum":
258
- return bytes.bytesToHex(data);
259
- case "Bitcoin":
260
- return new TextDecoder().decode(data);
261
- }
262
- };
263
- var contractIdToInternalAsset = Object.fromEntries(
264
- Object.entries(chainflip.assetContractId).map(([asset, id]) => [id, asset])
265
- );
266
- var parseVaultSwapData = (data) => {
267
- const version = data[0];
268
- const contractId = data[1];
269
- const outputAsset = contractIdToInternalAsset[contractId];
270
- let destinationAddress;
271
- let parameters;
272
- if (version === 1) {
273
- ({ destinationAddress, parameters } = createSwapDataCodecV1(outputAsset).dec(data));
274
- } else if (version === 0) {
275
- ({ destinationAddress, parameters } = createSwapDataCodecV0(outputAsset).dec(data));
276
- } else {
277
- throw new Error("unsupported version");
278
- }
279
- assertion.assert(outputAsset, "unknown asset contract id");
280
- return {
281
- ...parameters,
282
- outputAsset,
283
- destinationAddress: encodeChainAddress(destinationAddress, outputAsset)
284
- };
285
- };
286
- var getX128PriceFromAmounts = (depositAmount, minOutputAmount) => BigInt(
287
- new BigNumber2__default.default(minOutputAmount.toString()).div(depositAmount.toString()).multipliedBy(new BigNumber2__default.default(2).pow(128)).toFixed(0, BigNumber2__default.default.ROUND_FLOOR)
288
- );
289
- var findVaultSwapData = async (url, txId) => {
290
- const tx = await makeRequest(url, "getrawtransaction", [txId, true]);
291
- if (!tx) return null;
292
- const data = parseVaultSwapData(tx.vout[1].scriptPubKey.hex);
293
- const amount = tx.vout[0].value;
294
- const block = tx.blockhash ? await makeRequest(url, "getblock", [tx.blockhash, true]).catch(() => null) : null;
295
- return {
296
- inputAsset: "Btc",
297
- amount,
298
- depositAddress: tx.vout[0].scriptPubKey.address,
299
- refundParams: {
300
- refundAddress: tx.vout[2].scriptPubKey.address,
301
- retryDuration: data.retryDuration,
302
- minPrice: getX128PriceFromAmounts(amount, data.minOutputAmount),
303
- maxOraclePriceSlippage: "maxOraclePriceSlippage" in data ? data.maxOraclePriceSlippage : null
304
- },
305
- destinationAddress: data.destinationAddress,
306
- outputAsset: data.outputAsset,
307
- brokerFee: { account: null, commissionBps: data.brokerFee },
308
- affiliateFees: data.affiliates,
309
- ccmDepositMetadata: null,
310
- maxBoostFee: data.boostFee,
311
- dcaParams: data.numberOfChunks === 1 && data.chunkInterval === 2 ? null : { chunkInterval: data.chunkInterval, numberOfChunks: data.numberOfChunks },
312
- depositChainBlockHeight: block && block.height
313
- };
314
- };
315
-
316
- exports.decodeAddress = decodeAddress;
317
- exports.encodeAddress = encodeAddress;
318
- exports.findVaultSwapData = findVaultSwapData;
319
- exports.isValidAddressForNetwork = isValidAddressForNetwork;
4
+ exports.decodeAddress = require_address.decodeAddress;
5
+ exports.encodeAddress = require_address.encodeAddress;
6
+ exports.findVaultSwapData = require_deposit.findVaultSwapData;
7
+ exports.isValidAddressForNetwork = require_address.isValidAddressForNetwork;
package/dist/index.d.ts CHANGED
@@ -1,35 +1,4 @@
1
- import { ChainflipNetwork } from '@chainflip/utils/chainflip';
2
- import { VaultSwapData } from '@chainflip/utils/types';
3
-
4
- type BitcoinNetwork = 'mainnet' | 'testnet' | 'regtest';
5
-
6
- type Bytelike = Uint8Array | number[] | `0x${string}`;
7
- declare const networkHrp: {
8
- readonly mainnet: "bc";
9
- readonly testnet: "tb";
10
- readonly regtest: "bcrt";
11
- };
12
- type HRP = (typeof networkHrp)[keyof typeof networkHrp];
13
- type Base58AddressType = 'P2SH' | 'P2PKH';
14
- type DecodedBase58Address = {
15
- type: Base58AddressType;
16
- data: Uint8Array;
17
- version: number;
18
- };
19
- type DecodedSegwitAddress = {
20
- hrp: HRP;
21
- data: Uint8Array;
22
- type: SegwitAddressType;
23
- version: number;
24
- };
25
- type SegwitAddressType = 'P2WPKH' | 'P2WSH' | 'Taproot';
26
- declare const encodeAddress: (data: Bytelike, kind: Base58AddressType | SegwitAddressType, cfOrBtcnetwork: BitcoinNetwork | ChainflipNetwork) => string;
27
- declare const decodeAddress: (address: string, cfOrBtcNetwork: BitcoinNetwork | ChainflipNetwork) => DecodedBase58Address | DecodedSegwitAddress;
28
- declare const isValidAddressForNetwork: (address: string, cfOrBtcNetwork: BitcoinNetwork | ChainflipNetwork) => boolean;
29
-
30
- type BitcoinVaultSwapData = VaultSwapData<null> & {
31
- depositAddress: string;
32
- };
33
- declare const findVaultSwapData: (url: string, txId: string) => Promise<BitcoinVaultSwapData | null>;
34
-
35
- export { type Base58AddressType, type BitcoinNetwork, type BitcoinVaultSwapData, type Bytelike, type DecodedBase58Address, type DecodedSegwitAddress, type HRP, type SegwitAddressType, decodeAddress, encodeAddress, findVaultSwapData, isValidAddressForNetwork };
1
+ import { BitcoinNetwork } from "./consts.js";
2
+ import { Base58AddressType, Bytelike, DecodedBase58Address, DecodedSegwitAddress, HRP, SegwitAddressType, decodeAddress, encodeAddress, isValidAddressForNetwork } from "./address.js";
3
+ import { BitcoinVaultSwapData, findVaultSwapData } from "./deposit.js";
4
+ export { Base58AddressType, type BitcoinNetwork, type BitcoinVaultSwapData, Bytelike, DecodedBase58Address, DecodedSegwitAddress, HRP, SegwitAddressType, decodeAddress, encodeAddress, findVaultSwapData, isValidAddressForNetwork };
package/dist/index.js CHANGED
@@ -1,289 +1,4 @@
1
- import { assert } from '@chainflip/utils/assertion';
2
- import { hexToBytes, bytesToHex } from '@chainflip/utils/bytes';
3
- import * as bitcoin from 'bitcoinjs-lib';
4
- import * as base58 from '@chainflip/utils/base58';
5
- import { assetContractId, assetConstants } from '@chainflip/utils/chainflip';
6
- import { POLKADOT_SS58_PREFIX } from '@chainflip/utils/consts';
7
- import * as ss58 from '@chainflip/utils/ss58';
8
- import BigNumber2 from 'bignumber.js';
9
- import { parseUrlWithBasicAuth } from '@chainflip/utils/url';
10
- import { z } from 'zod';
11
- import { Struct, Bytes, u8, Vector, u16, u128 } from 'scale-ts';
1
+ import { decodeAddress, encodeAddress, isValidAddressForNetwork } from "./address.js";
2
+ import { findVaultSwapData } from "./deposit.js";
12
3
 
13
- // src/address.ts
14
-
15
- // src/consts.ts
16
- var networkMap = {
17
- mainnet: "mainnet",
18
- perseverance: "testnet",
19
- sisyphos: "testnet",
20
- testnet: "testnet",
21
- backspin: "regtest",
22
- regtest: "regtest"
23
- };
24
-
25
- // src/address.ts
26
- var p2pkhAddressVersion = {
27
- mainnet: 0,
28
- testnet: 111,
29
- regtest: 111
30
- };
31
- var p2shAddressVersion = {
32
- mainnet: 5,
33
- testnet: 196,
34
- regtest: 196
35
- };
36
- var networkHrp = {
37
- mainnet: "bc",
38
- testnet: "tb",
39
- regtest: "bcrt"
40
- };
41
- var segwitVersions = {
42
- P2WPKH: 0,
43
- P2WSH: 0,
44
- Taproot: 1
45
- };
46
- var byteLikeToUint8Array = (data) => typeof data === "string" ? hexToBytes(data) : new Uint8Array(data);
47
- var encodeAddress = (data, kind, cfOrBtcnetwork) => {
48
- const btcNetwork = networkMap[cfOrBtcnetwork];
49
- assert(btcNetwork, `Invalid network: ${cfOrBtcnetwork}`);
50
- assert(data.length % 2 === 0, "bytes must have an even number of characters");
51
- assert(
52
- typeof data !== "string" || /^(0x)?[0-9a-f]*$/.test(data),
53
- "bytes are not a valid hex string"
54
- );
55
- const bytes = byteLikeToUint8Array(data);
56
- switch (kind) {
57
- case "P2PKH":
58
- case "P2SH": {
59
- const version = (kind === "P2SH" ? p2shAddressVersion : p2pkhAddressVersion)[btcNetwork];
60
- return bitcoin.address.toBase58Check(bytes, version);
61
- }
62
- case "P2WPKH":
63
- case "P2WSH":
64
- case "Taproot":
65
- return bitcoin.address.toBech32(bytes, segwitVersions[kind], networkHrp[btcNetwork]);
66
- default:
67
- throw new Error(`Invalid address type: ${kind}`);
68
- }
69
- };
70
- var decodeAddress = (address2, cfOrBtcNetwork) => {
71
- const network = networkMap[cfOrBtcNetwork];
72
- if (/^[13mn2]/.test(address2)) {
73
- const { hash, version } = bitcoin.address.fromBase58Check(address2);
74
- if (version === p2pkhAddressVersion[network]) {
75
- return { type: "P2PKH", data: hash, version };
76
- }
77
- if (version === p2shAddressVersion[network]) {
78
- return { type: "P2SH", data: hash, version };
79
- }
80
- throw new TypeError(`Invalid version: ${version}`);
81
- }
82
- if (/^(bc|tb|bcrt)1/.test(address2)) {
83
- const { data, prefix, version } = bitcoin.address.fromBech32(address2);
84
- assert(prefix === networkHrp[network], `Invalid prefix: ${prefix}`);
85
- let type;
86
- if (version === 0 && data.length === 20) {
87
- type = "P2WPKH";
88
- } else if (version === 0) {
89
- type = "P2WSH";
90
- } else if (version === 1) {
91
- type = "Taproot";
92
- } else {
93
- throw new TypeError(`Invalid version: ${version}`);
94
- }
95
- return { hrp: prefix, data, type, version };
96
- }
97
- throw new TypeError(`Invalid address "${address2}" for network "${network}"`);
98
- };
99
- var isValidAddressForNetwork = (address2, cfOrBtcNetwork) => {
100
- try {
101
- decodeAddress(address2, cfOrBtcNetwork);
102
- return true;
103
- } catch {
104
- return false;
105
- }
106
- };
107
- var hexString = z.string().regex(/^([0-9a-f]{2})+$/, { message: "expected hex string" });
108
- var vout = z.object({
109
- value: z.number().transform((n) => BigInt(new BigNumber2(n).shiftedBy(8).toFixed(0))),
110
- n: z.number()
111
- });
112
- var nulldataVout = z.object({
113
- scriptPubKey: z.object({
114
- type: z.literal("nulldata"),
115
- // remove OP_RETURN and PUSH_BYTES_XX
116
- hex: hexString.transform((x) => hexToBytes(`0x${x.slice(4)}`))
117
- })
118
- }).and(vout);
119
- var addressVout = z.object({
120
- scriptPubKey: z.object({
121
- type: z.enum([
122
- "witness_v1_taproot",
123
- "witness_v0_scripthash",
124
- "witness_v0_keyhash",
125
- "pubkeyhash",
126
- "scripthash"
127
- ]),
128
- address: z.string()
129
- })
130
- }).and(vout);
131
- var txSchema = z.object({
132
- vout: z.tuple([addressVout, nulldataVout, addressVout]),
133
- blockhash: hexString.nullish()
134
- });
135
- var blockSchema = z.object({
136
- height: z.number()
137
- });
138
- var responseSchemas = {
139
- getrawtransaction: txSchema,
140
- getblock: blockSchema
141
- };
142
- var rpcResponse = z.union([
143
- z.object({ result: z.null(), error: z.object({ code: z.number(), message: z.string() }) }),
144
- z.object({ result: z.unknown(), error: z.null() })
145
- ]);
146
- var makeRequest = async (rpcUrl, method, params) => {
147
- const { url, headers } = parseUrlWithBasicAuth(rpcUrl);
148
- const res = await fetch(url, {
149
- method: "POST",
150
- headers: {
151
- ...headers,
152
- "Content-Type": "application/json"
153
- },
154
- body: JSON.stringify({
155
- jsonrpc: "2.0",
156
- id: 1,
157
- method,
158
- params
159
- })
160
- });
161
- const text = await res.text();
162
- let json;
163
- try {
164
- json = JSON.parse(text);
165
- } catch {
166
- if (res.status !== 200) {
167
- throw new Error(`HTTP error [${res.status}]: ${text || res.statusText}`);
168
- }
169
- throw new Error(`Invalid JSON response: ${text}`);
170
- }
171
- const result = rpcResponse.parse(json);
172
- if (result.error) {
173
- if (result.error.code === -5) return null;
174
- throw new Error(`RPC error [${result.error.code}]: ${result.error.message}`);
175
- }
176
- const parseResult = responseSchemas[method].safeParse(result.result);
177
- if (!parseResult.success) {
178
- if (method === "getrawtransaction") return null;
179
- throw parseResult.error;
180
- }
181
- return parseResult.data;
182
- };
183
- var addressByteLengths = {
184
- Bitcoin: void 0,
185
- Arbitrum: 20,
186
- Ethereum: 20,
187
- Solana: 32,
188
- Polkadot: 32,
189
- Assethub: 32
190
- };
191
- var createSwapDataCodecV0 = (asset) => Struct({
192
- version: u8,
193
- destinationAsset: u8,
194
- destinationAddress: Bytes(addressByteLengths[assetConstants[asset].chain]),
195
- parameters: Struct({
196
- retryDuration: u16,
197
- minOutputAmount: u128,
198
- numberOfChunks: u16,
199
- chunkInterval: u16,
200
- boostFee: u8,
201
- brokerFee: u8,
202
- affiliates: Vector(Struct({ accountIndex: u8, commissionBps: u8 }))
203
- })
204
- });
205
- var createSwapDataCodecV1 = (asset) => Struct({
206
- version: u8,
207
- destinationAsset: u8,
208
- destinationAddress: Bytes(addressByteLengths[assetConstants[asset].chain]),
209
- parameters: Struct({
210
- retryDuration: u16,
211
- minOutputAmount: u128,
212
- maxOraclePriceSlippage: u8,
213
- numberOfChunks: u16,
214
- chunkInterval: u16,
215
- boostFee: u8,
216
- brokerFee: u8,
217
- affiliates: Vector(Struct({ accountIndex: u8, commissionBps: u8 }))
218
- })
219
- });
220
-
221
- // src/deposit.ts
222
- var encodeChainAddress = (data, asset) => {
223
- switch (assetConstants[asset].chain) {
224
- case "Solana":
225
- return base58.encode(data);
226
- case "Assethub":
227
- case "Polkadot":
228
- return ss58.encode({ data, ss58Format: POLKADOT_SS58_PREFIX });
229
- case "Ethereum":
230
- case "Arbitrum":
231
- return bytesToHex(data);
232
- case "Bitcoin":
233
- return new TextDecoder().decode(data);
234
- }
235
- };
236
- var contractIdToInternalAsset = Object.fromEntries(
237
- Object.entries(assetContractId).map(([asset, id]) => [id, asset])
238
- );
239
- var parseVaultSwapData = (data) => {
240
- const version = data[0];
241
- const contractId = data[1];
242
- const outputAsset = contractIdToInternalAsset[contractId];
243
- let destinationAddress;
244
- let parameters;
245
- if (version === 1) {
246
- ({ destinationAddress, parameters } = createSwapDataCodecV1(outputAsset).dec(data));
247
- } else if (version === 0) {
248
- ({ destinationAddress, parameters } = createSwapDataCodecV0(outputAsset).dec(data));
249
- } else {
250
- throw new Error("unsupported version");
251
- }
252
- assert(outputAsset, "unknown asset contract id");
253
- return {
254
- ...parameters,
255
- outputAsset,
256
- destinationAddress: encodeChainAddress(destinationAddress, outputAsset)
257
- };
258
- };
259
- var getX128PriceFromAmounts = (depositAmount, minOutputAmount) => BigInt(
260
- new BigNumber2(minOutputAmount.toString()).div(depositAmount.toString()).multipliedBy(new BigNumber2(2).pow(128)).toFixed(0, BigNumber2.ROUND_FLOOR)
261
- );
262
- var findVaultSwapData = async (url, txId) => {
263
- const tx = await makeRequest(url, "getrawtransaction", [txId, true]);
264
- if (!tx) return null;
265
- const data = parseVaultSwapData(tx.vout[1].scriptPubKey.hex);
266
- const amount = tx.vout[0].value;
267
- const block = tx.blockhash ? await makeRequest(url, "getblock", [tx.blockhash, true]).catch(() => null) : null;
268
- return {
269
- inputAsset: "Btc",
270
- amount,
271
- depositAddress: tx.vout[0].scriptPubKey.address,
272
- refundParams: {
273
- refundAddress: tx.vout[2].scriptPubKey.address,
274
- retryDuration: data.retryDuration,
275
- minPrice: getX128PriceFromAmounts(amount, data.minOutputAmount),
276
- maxOraclePriceSlippage: "maxOraclePriceSlippage" in data ? data.maxOraclePriceSlippage : null
277
- },
278
- destinationAddress: data.destinationAddress,
279
- outputAsset: data.outputAsset,
280
- brokerFee: { account: null, commissionBps: data.brokerFee },
281
- affiliateFees: data.affiliates,
282
- ccmDepositMetadata: null,
283
- maxBoostFee: data.boostFee,
284
- dcaParams: data.numberOfChunks === 1 && data.chunkInterval === 2 ? null : { chunkInterval: data.chunkInterval, numberOfChunks: data.numberOfChunks },
285
- depositChainBlockHeight: block && block.height
286
- };
287
- };
288
-
289
- export { decodeAddress, encodeAddress, findVaultSwapData, isValidAddressForNetwork };
4
+ export { decodeAddress, encodeAddress, findVaultSwapData, isValidAddressForNetwork };