@pioneer-platform/chainflip-client 0.0.2

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.
@@ -0,0 +1,15 @@
1
+ import { type AssetValue, type GenericSwapParams } from "@swapkit/helpers";
2
+ import type { ETHToolbox } from "@swapkit/toolbox-evm";
3
+ import type { ChainflipToolbox } from "@swapkit/toolbox-substrate";
4
+ import type { SwapDepositResponse, WithdrawFeeResponse } from "./types.ts";
5
+ export declare const ChainflipBroker: (chainflipToolbox: Awaited<ReturnType<typeof ChainflipToolbox>>) => {
6
+ registerAsBroker: (address: string) => Promise<string | (() => void)>;
7
+ requestSwapDepositAddress: (chainflipTransaction: GenericSwapParams & {
8
+ brokerCommissionBPS: number;
9
+ }) => Promise<SwapDepositResponse>;
10
+ fundStateChainAccount: (stateChainAccount: string, amount: AssetValue, evmToolbox: ReturnType<typeof ETHToolbox>) => Promise<string>;
11
+ withdrawFee: (params: {
12
+ feeAsset: AssetValue;
13
+ recipient: string;
14
+ }) => Promise<WithdrawFeeResponse>;
15
+ };
package/lib/broker.js ADDED
@@ -0,0 +1,128 @@
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.ChainflipBroker = void 0;
13
+ const swap_1 = require("@chainflip/sdk/swap");
14
+ const helpers_1 = require("@swapkit/helpers");
15
+ const helpers_2 = require("@swapkit/helpers");
16
+ const keyring_1 = require("@polkadot/keyring");
17
+ const util_1 = require("@polkadot/util");
18
+ const chainflipGatewayABI_ts_1 = require("./chainflipGatewayABI.ts");
19
+ const chainToChainflipChain = new Map([
20
+ [helpers_2.Chain.Ethereum, swap_1.Chains.Ethereum],
21
+ [helpers_2.Chain.Bitcoin, swap_1.Chains.Bitcoin],
22
+ [helpers_2.Chain.Polkadot, swap_1.Chains.Polkadot],
23
+ ]);
24
+ const registerAsBroker = (toolbox, address) => {
25
+ var _a, _b;
26
+ const extrinsic = (_b = (_a = toolbox.api.tx.swapping) === null || _a === void 0 ? void 0 : _a.registerAsBroker) === null || _b === void 0 ? void 0 : _b.call(_a, address);
27
+ if (!extrinsic) {
28
+ throw new Error("chainflip_broker_register");
29
+ }
30
+ return toolbox.signAndBroadcast(extrinsic);
31
+ };
32
+ const requestSwapDepositAddress = (toolbox, { sellAsset, buyAsset, recipient, brokerCommissionBPS, }) => __awaiter(void 0, void 0, void 0, function* () {
33
+ const isBuyChainPolkadot = buyAsset.chain === helpers_2.Chain.Polkadot;
34
+ const recipientAddress = (0, helpers_1.wrapWithThrow)(() => {
35
+ return isBuyChainPolkadot
36
+ ? toolbox.encodeAddress(toolbox.decodeAddress(recipient), "hex")
37
+ : recipient;
38
+ }, "chainflip_broker_recipient_error");
39
+ return new Promise((resolve) => {
40
+ var _a, _b;
41
+ const tx = (_b = (_a = toolbox.api.tx.swapping) === null || _a === void 0 ? void 0 : _a.requestSwapDepositAddress) === null || _b === void 0 ? void 0 : _b.call(_a, sellAsset.ticker.toLowerCase(), buyAsset.ticker.toLowerCase(), { [buyAsset.chain.toLowerCase()]: recipientAddress }, helpers_1.SwapKitNumber.fromBigInt(BigInt(brokerCommissionBPS)).getBaseValue("number"), null, 0);
42
+ if (!tx) {
43
+ throw new Error("chainflip_broker_tx_error");
44
+ }
45
+ toolbox.signAndBroadcast(tx, (result) => __awaiter(void 0, void 0, void 0, function* () {
46
+ var _c, _d, _e;
47
+ if (!((_c = result.status) === null || _c === void 0 ? void 0 : _c.isFinalized)) {
48
+ return;
49
+ }
50
+ const depositChannelEvent = result.events.find((event) => event.event.method === "SwapDepositAddressReady");
51
+ if (!depositChannelEvent) {
52
+ throw new helpers_1.SwapKitError("chainflip_channel_error", "Could not find 'SwapDepositAddressReady' event");
53
+ }
54
+ const { event: { data: { depositAddress, sourceChainExpiryBlock, destinationAddress, channelId }, }, } = depositChannelEvent.toHuman();
55
+ const hash = (_e = (_d = result.status) === null || _d === void 0 ? void 0 : _d.toJSON) === null || _e === void 0 ? void 0 : _e.call(_d);
56
+ const header = yield toolbox.api.rpc.chain.getHeader(hash === null || hash === void 0 ? void 0 : hash.finalized);
57
+ const depositChannelId = `${header.number}-${chainToChainflipChain.get(sellAsset.chain)}-${channelId.replaceAll(",", "")}`;
58
+ resolve({
59
+ brokerCommissionBPS,
60
+ buyAsset,
61
+ depositAddress: Object.values(depositAddress)[0],
62
+ depositChannelId,
63
+ recipient: Object.values(destinationAddress)[0],
64
+ sellAsset,
65
+ srcChainExpiryBlock: Number(sourceChainExpiryBlock.replaceAll(",", "")),
66
+ });
67
+ }));
68
+ });
69
+ });
70
+ const withdrawFee = (toolbox, { feeAsset, recipient }) => {
71
+ const isFeeChainPolkadot = feeAsset.chain === helpers_2.Chain.Polkadot;
72
+ const recipientAddress = (0, helpers_1.wrapWithThrow)(() => {
73
+ return isFeeChainPolkadot
74
+ ? toolbox.encodeAddress(toolbox.decodeAddress(recipient), "hex")
75
+ : recipient;
76
+ }, "chainflip_broker_recipient_error");
77
+ return new Promise((resolve) => {
78
+ var _a, _b, _c;
79
+ const extrinsic = (_c = (_b = (_a = toolbox.api.tx) === null || _a === void 0 ? void 0 : _a.swapping) === null || _b === void 0 ? void 0 : _b.withdraw) === null || _c === void 0 ? void 0 : _c.call(_b, feeAsset.ticker.toLowerCase(), {
80
+ [feeAsset.chain.toLowerCase()]: recipientAddress,
81
+ });
82
+ if (!extrinsic) {
83
+ throw new Error("chainflip_broker_withdraw");
84
+ }
85
+ toolbox.signAndBroadcast(extrinsic, (result) => __awaiter(void 0, void 0, void 0, function* () {
86
+ var _d;
87
+ if (!((_d = result.status) === null || _d === void 0 ? void 0 : _d.isFinalized)) {
88
+ return;
89
+ }
90
+ const withdrawEvent = result.events.find((event) => event.event.method === "WithdrawalRequested");
91
+ if (!withdrawEvent) {
92
+ throw new helpers_1.SwapKitError("chainflip_channel_error", "Could not find 'WithdrawalRequested' event");
93
+ }
94
+ const { event: { data: { egressId, egressAsset, egressAmount, egressFee, destinationAddress }, }, } = withdrawEvent.toHuman();
95
+ resolve({
96
+ egressId,
97
+ egressAsset,
98
+ egressAmount,
99
+ egressFee,
100
+ destinationAddress,
101
+ });
102
+ }));
103
+ });
104
+ };
105
+ const fundStateChainAccount = (evmToolbox, chainflipToolbox, stateChainAccount, amount) => {
106
+ if (amount.symbol !== "FLIP") {
107
+ throw new Error("Only FLIP is supported");
108
+ }
109
+ if (!chainflipToolbox.validateAddress(stateChainAccount)) {
110
+ throw new Error("Invalid address");
111
+ }
112
+ const hexAddress = (0, util_1.isHex)(stateChainAccount)
113
+ ? stateChainAccount
114
+ : (0, util_1.u8aToHex)((0, keyring_1.decodeAddress)(stateChainAccount));
115
+ return evmToolbox.call({
116
+ abi: chainflipGatewayABI_ts_1.chainflipGateway,
117
+ contractAddress: "0x6995ab7c4d7f4b03f467cf4c8e920427d9621dbd",
118
+ funcName: "fundStateChainAccount",
119
+ funcParams: [hexAddress, amount],
120
+ });
121
+ };
122
+ const ChainflipBroker = (chainflipToolbox) => ({
123
+ registerAsBroker: (address) => registerAsBroker(chainflipToolbox, address),
124
+ requestSwapDepositAddress: (chainflipTransaction) => requestSwapDepositAddress(chainflipToolbox, chainflipTransaction),
125
+ fundStateChainAccount: (stateChainAccount, amount, evmToolbox) => fundStateChainAccount(evmToolbox, chainflipToolbox, stateChainAccount, amount),
126
+ withdrawFee: (params) => withdrawFee(chainflipToolbox, params),
127
+ });
128
+ exports.ChainflipBroker = ChainflipBroker;
@@ -0,0 +1,80 @@
1
+ export declare const chainflipGateway: ({
2
+ inputs: {
3
+ internalType: string;
4
+ name: string;
5
+ type: string;
6
+ }[];
7
+ stateMutability: string;
8
+ type: string;
9
+ anonymous?: undefined;
10
+ name?: undefined;
11
+ outputs?: undefined;
12
+ } | {
13
+ anonymous: boolean;
14
+ inputs: {
15
+ indexed: boolean;
16
+ internalType: string;
17
+ name: string;
18
+ type: string;
19
+ }[];
20
+ name: string;
21
+ type: string;
22
+ stateMutability?: undefined;
23
+ outputs?: undefined;
24
+ } | {
25
+ inputs: {
26
+ internalType: string;
27
+ name: string;
28
+ type: string;
29
+ }[];
30
+ name: string;
31
+ outputs: {
32
+ internalType: string;
33
+ name: string;
34
+ type: string;
35
+ }[];
36
+ stateMutability: string;
37
+ type: string;
38
+ anonymous?: undefined;
39
+ } | {
40
+ inputs: {
41
+ internalType: string;
42
+ name: string;
43
+ type: string;
44
+ }[];
45
+ name: string;
46
+ outputs: {
47
+ components: {
48
+ internalType: string;
49
+ name: string;
50
+ type: string;
51
+ }[];
52
+ internalType: string;
53
+ name: string;
54
+ type: string;
55
+ }[];
56
+ stateMutability: string;
57
+ type: string;
58
+ anonymous?: undefined;
59
+ } | {
60
+ inputs: ({
61
+ components: {
62
+ internalType: string;
63
+ name: string;
64
+ type: string;
65
+ }[];
66
+ internalType: string;
67
+ name: string;
68
+ type: string;
69
+ } | {
70
+ internalType: string;
71
+ name: string;
72
+ type: string;
73
+ components?: undefined;
74
+ })[];
75
+ name: string;
76
+ outputs: never[];
77
+ stateMutability: string;
78
+ type: string;
79
+ anonymous?: undefined;
80
+ })[];
@@ -0,0 +1,333 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.chainflipGateway = void 0;
4
+ exports.chainflipGateway = [
5
+ {
6
+ inputs: [
7
+ { internalType: "contract IKeyManager", name: "keyManager", type: "address" },
8
+ { internalType: "uint256", name: "minFunding", type: "uint256" },
9
+ { internalType: "uint48", name: "redemptionDelay", type: "uint48" },
10
+ ],
11
+ stateMutability: "nonpayable",
12
+ type: "constructor",
13
+ },
14
+ {
15
+ anonymous: false,
16
+ inputs: [
17
+ { indexed: false, internalType: "bool", name: "communityGuardDisabled", type: "bool" },
18
+ ],
19
+ name: "CommunityGuardDisabled",
20
+ type: "event",
21
+ },
22
+ {
23
+ anonymous: false,
24
+ inputs: [{ indexed: false, internalType: "address", name: "flip", type: "address" }],
25
+ name: "FLIPSet",
26
+ type: "event",
27
+ },
28
+ {
29
+ anonymous: false,
30
+ inputs: [
31
+ { indexed: false, internalType: "uint256", name: "oldSupply", type: "uint256" },
32
+ { indexed: false, internalType: "uint256", name: "newSupply", type: "uint256" },
33
+ { indexed: false, internalType: "uint256", name: "stateChainBlockNumber", type: "uint256" },
34
+ ],
35
+ name: "FlipSupplyUpdated",
36
+ type: "event",
37
+ },
38
+ {
39
+ anonymous: false,
40
+ inputs: [
41
+ { indexed: true, internalType: "bytes32", name: "nodeID", type: "bytes32" },
42
+ { indexed: false, internalType: "uint256", name: "amount", type: "uint256" },
43
+ { indexed: false, internalType: "address", name: "funder", type: "address" },
44
+ ],
45
+ name: "Funded",
46
+ type: "event",
47
+ },
48
+ {
49
+ anonymous: false,
50
+ inputs: [
51
+ { indexed: false, internalType: "address", name: "to", type: "address" },
52
+ { indexed: false, internalType: "uint256", name: "amount", type: "uint256" },
53
+ ],
54
+ name: "GovernanceWithdrawal",
55
+ type: "event",
56
+ },
57
+ {
58
+ anonymous: false,
59
+ inputs: [
60
+ { indexed: false, internalType: "uint256", name: "oldMinFunding", type: "uint256" },
61
+ { indexed: false, internalType: "uint256", name: "newMinFunding", type: "uint256" },
62
+ ],
63
+ name: "MinFundingChanged",
64
+ type: "event",
65
+ },
66
+ {
67
+ anonymous: false,
68
+ inputs: [
69
+ { indexed: true, internalType: "bytes32", name: "nodeID", type: "bytes32" },
70
+ { indexed: false, internalType: "uint256", name: "amount", type: "uint256" },
71
+ ],
72
+ name: "RedemptionExecuted",
73
+ type: "event",
74
+ },
75
+ {
76
+ anonymous: false,
77
+ inputs: [
78
+ { indexed: true, internalType: "bytes32", name: "nodeID", type: "bytes32" },
79
+ { indexed: false, internalType: "uint256", name: "amount", type: "uint256" },
80
+ ],
81
+ name: "RedemptionExpired",
82
+ type: "event",
83
+ },
84
+ {
85
+ anonymous: false,
86
+ inputs: [
87
+ { indexed: true, internalType: "bytes32", name: "nodeID", type: "bytes32" },
88
+ { indexed: false, internalType: "uint256", name: "amount", type: "uint256" },
89
+ { indexed: true, internalType: "address", name: "redeemAddress", type: "address" },
90
+ { indexed: false, internalType: "uint48", name: "startTime", type: "uint48" },
91
+ { indexed: false, internalType: "uint48", name: "expiryTime", type: "uint48" },
92
+ { indexed: false, internalType: "address", name: "executor", type: "address" },
93
+ ],
94
+ name: "RedemptionRegistered",
95
+ type: "event",
96
+ },
97
+ {
98
+ anonymous: false,
99
+ inputs: [{ indexed: false, internalType: "bool", name: "suspended", type: "bool" }],
100
+ name: "Suspended",
101
+ type: "event",
102
+ },
103
+ {
104
+ anonymous: false,
105
+ inputs: [{ indexed: false, internalType: "address", name: "keyManager", type: "address" }],
106
+ name: "UpdatedKeyManager",
107
+ type: "event",
108
+ },
109
+ {
110
+ inputs: [],
111
+ name: "REDEMPTION_DELAY",
112
+ outputs: [{ internalType: "uint48", name: "", type: "uint48" }],
113
+ stateMutability: "view",
114
+ type: "function",
115
+ },
116
+ {
117
+ inputs: [],
118
+ name: "disableCommunityGuard",
119
+ outputs: [],
120
+ stateMutability: "nonpayable",
121
+ type: "function",
122
+ },
123
+ {
124
+ inputs: [],
125
+ name: "enableCommunityGuard",
126
+ outputs: [],
127
+ stateMutability: "nonpayable",
128
+ type: "function",
129
+ },
130
+ {
131
+ inputs: [{ internalType: "bytes32", name: "nodeID", type: "bytes32" }],
132
+ name: "executeRedemption",
133
+ outputs: [
134
+ { internalType: "address", name: "", type: "address" },
135
+ { internalType: "uint256", name: "", type: "uint256" },
136
+ ],
137
+ stateMutability: "nonpayable",
138
+ type: "function",
139
+ },
140
+ {
141
+ inputs: [
142
+ { internalType: "bytes32", name: "nodeID", type: "bytes32" },
143
+ { internalType: "uint256", name: "amount", type: "uint256" },
144
+ ],
145
+ name: "fundStateChainAccount",
146
+ outputs: [],
147
+ stateMutability: "nonpayable",
148
+ type: "function",
149
+ },
150
+ {
151
+ inputs: [],
152
+ name: "getCommunityGuardDisabled",
153
+ outputs: [{ internalType: "bool", name: "", type: "bool" }],
154
+ stateMutability: "view",
155
+ type: "function",
156
+ },
157
+ {
158
+ inputs: [],
159
+ name: "getCommunityKey",
160
+ outputs: [{ internalType: "address", name: "", type: "address" }],
161
+ stateMutability: "view",
162
+ type: "function",
163
+ },
164
+ {
165
+ inputs: [],
166
+ name: "getFLIP",
167
+ outputs: [{ internalType: "contract IFLIP", name: "", type: "address" }],
168
+ stateMutability: "view",
169
+ type: "function",
170
+ },
171
+ {
172
+ inputs: [],
173
+ name: "getGovernor",
174
+ outputs: [{ internalType: "address", name: "", type: "address" }],
175
+ stateMutability: "view",
176
+ type: "function",
177
+ },
178
+ {
179
+ inputs: [],
180
+ name: "getKeyManager",
181
+ outputs: [{ internalType: "contract IKeyManager", name: "", type: "address" }],
182
+ stateMutability: "view",
183
+ type: "function",
184
+ },
185
+ {
186
+ inputs: [],
187
+ name: "getLastSupplyUpdateBlockNumber",
188
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
189
+ stateMutability: "view",
190
+ type: "function",
191
+ },
192
+ {
193
+ inputs: [],
194
+ name: "getMinimumFunding",
195
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
196
+ stateMutability: "view",
197
+ type: "function",
198
+ },
199
+ {
200
+ inputs: [{ internalType: "bytes32", name: "nodeID", type: "bytes32" }],
201
+ name: "getPendingRedemption",
202
+ outputs: [
203
+ {
204
+ components: [
205
+ { internalType: "uint256", name: "amount", type: "uint256" },
206
+ { internalType: "address", name: "redeemAddress", type: "address" },
207
+ { internalType: "uint48", name: "startTime", type: "uint48" },
208
+ { internalType: "uint48", name: "expiryTime", type: "uint48" },
209
+ { internalType: "address", name: "executor", type: "address" },
210
+ ],
211
+ internalType: "struct IStateChainGateway.Redemption",
212
+ name: "",
213
+ type: "tuple",
214
+ },
215
+ ],
216
+ stateMutability: "view",
217
+ type: "function",
218
+ },
219
+ {
220
+ inputs: [],
221
+ name: "getSuspendedState",
222
+ outputs: [{ internalType: "bool", name: "", type: "bool" }],
223
+ stateMutability: "view",
224
+ type: "function",
225
+ },
226
+ {
227
+ inputs: [],
228
+ name: "govUpdateFlipIssuer",
229
+ outputs: [],
230
+ stateMutability: "nonpayable",
231
+ type: "function",
232
+ },
233
+ { inputs: [], name: "govWithdraw", outputs: [], stateMutability: "nonpayable", type: "function" },
234
+ {
235
+ inputs: [
236
+ {
237
+ components: [
238
+ { internalType: "uint256", name: "sig", type: "uint256" },
239
+ { internalType: "uint256", name: "nonce", type: "uint256" },
240
+ { internalType: "address", name: "kTimesGAddress", type: "address" },
241
+ ],
242
+ internalType: "struct IShared.SigData",
243
+ name: "sigData",
244
+ type: "tuple",
245
+ },
246
+ { internalType: "bytes32", name: "nodeID", type: "bytes32" },
247
+ { internalType: "uint256", name: "amount", type: "uint256" },
248
+ { internalType: "address", name: "redeemAddress", type: "address" },
249
+ { internalType: "uint48", name: "expiryTime", type: "uint48" },
250
+ { internalType: "address", name: "executor", type: "address" },
251
+ ],
252
+ name: "registerRedemption",
253
+ outputs: [],
254
+ stateMutability: "nonpayable",
255
+ type: "function",
256
+ },
257
+ { inputs: [], name: "resume", outputs: [], stateMutability: "nonpayable", type: "function" },
258
+ {
259
+ inputs: [{ internalType: "contract IFLIP", name: "flip", type: "address" }],
260
+ name: "setFlip",
261
+ outputs: [],
262
+ stateMutability: "nonpayable",
263
+ type: "function",
264
+ },
265
+ {
266
+ inputs: [{ internalType: "uint256", name: "newMinFunding", type: "uint256" }],
267
+ name: "setMinFunding",
268
+ outputs: [],
269
+ stateMutability: "nonpayable",
270
+ type: "function",
271
+ },
272
+ { inputs: [], name: "suspend", outputs: [], stateMutability: "nonpayable", type: "function" },
273
+ {
274
+ inputs: [
275
+ {
276
+ components: [
277
+ { internalType: "uint256", name: "sig", type: "uint256" },
278
+ { internalType: "uint256", name: "nonce", type: "uint256" },
279
+ { internalType: "address", name: "kTimesGAddress", type: "address" },
280
+ ],
281
+ internalType: "struct IShared.SigData",
282
+ name: "sigData",
283
+ type: "tuple",
284
+ },
285
+ { internalType: "address", name: "newIssuer", type: "address" },
286
+ { internalType: "bool", name: "omitChecks", type: "bool" },
287
+ ],
288
+ name: "updateFlipIssuer",
289
+ outputs: [],
290
+ stateMutability: "nonpayable",
291
+ type: "function",
292
+ },
293
+ {
294
+ inputs: [
295
+ {
296
+ components: [
297
+ { internalType: "uint256", name: "sig", type: "uint256" },
298
+ { internalType: "uint256", name: "nonce", type: "uint256" },
299
+ { internalType: "address", name: "kTimesGAddress", type: "address" },
300
+ ],
301
+ internalType: "struct IShared.SigData",
302
+ name: "sigData",
303
+ type: "tuple",
304
+ },
305
+ { internalType: "uint256", name: "newTotalSupply", type: "uint256" },
306
+ { internalType: "uint256", name: "stateChainBlockNumber", type: "uint256" },
307
+ ],
308
+ name: "updateFlipSupply",
309
+ outputs: [],
310
+ stateMutability: "nonpayable",
311
+ type: "function",
312
+ },
313
+ {
314
+ inputs: [
315
+ {
316
+ components: [
317
+ { internalType: "uint256", name: "sig", type: "uint256" },
318
+ { internalType: "uint256", name: "nonce", type: "uint256" },
319
+ { internalType: "address", name: "kTimesGAddress", type: "address" },
320
+ ],
321
+ internalType: "struct IShared.SigData",
322
+ name: "sigData",
323
+ type: "tuple",
324
+ },
325
+ { internalType: "contract IKeyManager", name: "keyManager", type: "address" },
326
+ { internalType: "bool", name: "omitChecks", type: "bool" },
327
+ ],
328
+ name: "updateKeyManager",
329
+ outputs: [],
330
+ stateMutability: "nonpayable",
331
+ type: "function",
332
+ },
333
+ ];
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/index.js ADDED
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ /*
3
+ chainflip Integration
4
+ - Highlander
5
+
6
+ Notes:
7
+ lol polkadot cant ts bro, https://substrate.stackexchange.com/questions/4542/typescript-errors-when-using-polkadot-api
8
+
9
+ */
10
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12
+ return new (P || (P = Promise))(function (resolve, reject) {
13
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
14
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
15
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
16
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
17
+ });
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ const TAG = " | chainflip | ";
21
+ const { uuid } = require('uuidv4');
22
+ const log = require('@pioneer-platform/loggerdog')();
23
+ let { caipToNetworkId, shortListSymbolToCaip, ChainToNetworkId } = require("@pioneer-platform/pioneer-caip");
24
+ const { createMemo, parseMemo } = require('@pioneer-platform/pioneer-coins');
25
+ const axios = require('axios');
26
+ let networkSupport = [
27
+ ChainToNetworkId["BTC"],
28
+ ChainToNetworkId["ETH"],
29
+ ];
30
+ module.exports = {
31
+ init: function (settings) {
32
+ return true;
33
+ },
34
+ networkSupport: function () {
35
+ return networkSupport;
36
+ },
37
+ getQuote: function (quote) {
38
+ return get_quote(quote);
39
+ },
40
+ };
41
+ const get_quote = function (quote) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ let tag = TAG + " | get_quote | ";
44
+ try {
45
+ let output = {};
46
+ output.steps = 1;
47
+ output.memoless = true;
48
+ output.complete = true;
49
+ output.meta = {
50
+ quoteMode: "CHANGELLY"
51
+ };
52
+ output.complete = true;
53
+ if (!quote.sellAsset)
54
+ throw new Error("missing sellAsset");
55
+ if (!quote.buyAsset)
56
+ throw new Error("missing buyAsset");
57
+ if (!quote.sellAmount)
58
+ throw new Error("missing sellAmount");
59
+ if (!quote.recipientAddress)
60
+ throw new Error("missing recipientAddress");
61
+ if (!quote.slippage)
62
+ throw new Error("missing slippage");
63
+ // let providerUrl = "wss://rpc.polkadot.io"
64
+ // const provider = new WsProvider(providerUrl);
65
+ // const api = await ApiPromise.create({ provider });
66
+ //https://chainflip-swap.chainflip.io/quote?amount=100000000&srcChain=Bitcoin&srcAsset=BTC&destChain=Ethereum&destAsset=ETH
67
+ //get quote
68
+ const responseQuote = yield axios.get('https://chainflip-swap.chainflip.io/quote', {
69
+ params: {
70
+ amount: 100000000,
71
+ srcChain: 'Bitcoin',
72
+ srcAsset: 'BTC',
73
+ destChain: 'Ethereum',
74
+ destAsset: 'ETH'
75
+ }
76
+ });
77
+ // console.log(responseQuote.data); // Handle the response data as needed
78
+ //https://chainflip-swap.chainflip.io/trpc/openSwapDepositChannel?batch=1
79
+ const url = 'https://chainflip-swap.chainflip.io/trpc/openSwapDepositChannel?batch=1';
80
+ const data = {
81
+ "0": {
82
+ "json": {
83
+ "srcChain": "Ethereum",
84
+ "destChain": "Bitcoin",
85
+ "srcAsset": "ETH",
86
+ "destAsset": "BTC",
87
+ "amount": "20427368230548824399",
88
+ "quote": responseQuote.data,
89
+ "destAddress": "bc1qu3ghkz8788ysk7gqcvke5l0mr7skhgvpuk6dk4"
90
+ }
91
+ }
92
+ };
93
+ const headers = {
94
+ 'Accept': '*/*',
95
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
96
+ 'Accept-Language': 'en-US,en;q=0.9',
97
+ 'Content-Type': 'application/json',
98
+ 'Origin': 'https://swap.chainflip.io',
99
+ 'Referer': 'https://swap.chainflip.io/',
100
+ 'Sec-Ch-Ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
101
+ 'Sec-Ch-Ua-Mobile': '?0',
102
+ 'Sec-Ch-Ua-Platform': '"macOS"',
103
+ 'Sec-Fetch-Dest': 'empty',
104
+ 'Sec-Fetch-Mode': 'cors',
105
+ 'Sec-Fetch-Site': 'same-site',
106
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
107
+ };
108
+ const response = yield axios.post(url, data, { headers });
109
+ // console.log(response); // Log the response data
110
+ // console.log(response.data); // Log the response data
111
+ // console.log(JSON.stringify(response.data)); // Log the response data
112
+ let result = response.data[0].result.data.json;
113
+ log.info(tag, "result: ", result);
114
+ output.id = result.id;
115
+ output.source = 'chainflip';
116
+ output.estimatedExpiryTime = result.estimatedExpiryTime;
117
+ output.amountOut = responseQuote.data.egressAmount;
118
+ console.log("caipToNetworkId(ChainToNetworkId[\"BTC\"]): ", caipToNetworkId(ChainToNetworkId["BTC"]));
119
+ console.log("caipToNetworkId(quote.sellAsset): ", caipToNetworkId(quote.sellAsset));
120
+ if (caipToNetworkId(quote.sellAsset) == caipToNetworkId(ChainToNetworkId["BTC"])) {
121
+ // Convert from satoshis to BTC
122
+ output.amountOut /= 1e8;
123
+ }
124
+ else if (caipToNetworkId(quote.sellAsset) == caipToNetworkId(ChainToNetworkId["ETH"])) {
125
+ // Convert from wei to ETH
126
+ output.amountOut /= 1e18;
127
+ }
128
+ else {
129
+ throw Error("Chain not supported!");
130
+ }
131
+ let tx = {
132
+ type: "transfer",
133
+ chain: caipToNetworkId(quote.sellAsset),
134
+ txParams: {
135
+ address: result.depositAddress,
136
+ amount: quote.sellAmount
137
+ }
138
+ };
139
+ output.txs = [tx];
140
+ output.raw = data;
141
+ return output;
142
+ }
143
+ catch (e) {
144
+ console.error(tag, "e: ", e);
145
+ throw e;
146
+ }
147
+ });
148
+ };
@@ -0,0 +1,42 @@
1
+ import { AssetValue, type BaseWallet } from "@swapkit/helpers";
2
+ export declare function confirmSwap({ buyAsset, sellAsset, recipient, brokerEndpoint, }: {
3
+ buyAsset: AssetValue;
4
+ sellAsset: AssetValue;
5
+ recipient: string;
6
+ brokerEndpoint: string;
7
+ }): Promise<{
8
+ channelId: string;
9
+ depositAddress: string;
10
+ chain: string;
11
+ }>;
12
+ export declare const ChainflipPlugin: {
13
+ readonly chainflip: {
14
+ readonly plugin: ({ wallets, config: { brokerEndpoint }, }: {
15
+ wallets: BaseWallet<{
16
+ [key: string]: NotWorth;
17
+ }>;
18
+ config: {
19
+ brokerEndpoint: string;
20
+ };
21
+ }) => {
22
+ swap: ({ recipient, ...rest }: SwapParams<"chainflip">) => Promise<string>;
23
+ };
24
+ };
25
+ };
26
+ /**
27
+ * @deprecated Use import { ChainflipPlugin } from "@swapkit/chainflip" instead
28
+ */
29
+ export declare const ChainflipProvider: {
30
+ readonly chainflip: {
31
+ readonly plugin: ({ wallets, config: { brokerEndpoint }, }: {
32
+ wallets: BaseWallet<{
33
+ [key: string]: NotWorth;
34
+ }>;
35
+ config: {
36
+ brokerEndpoint: string;
37
+ };
38
+ }) => {
39
+ swap: ({ recipient, ...rest }: SwapParams<"chainflip">) => Promise<string>;
40
+ };
41
+ };
42
+ };
package/lib/plugin.js ADDED
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.ChainflipProvider = exports.ChainflipPlugin = exports.confirmSwap = void 0;
24
+ const helpers_1 = require("@swapkit/helpers");
25
+ function confirmSwap({ buyAsset, sellAsset, recipient, brokerEndpoint, }) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ try {
28
+ const response = yield fetch(brokerEndpoint, {
29
+ method: "POST",
30
+ headers: { "Content-Type": "application/json" },
31
+ body: JSON.stringify({
32
+ buyAsset: buyAsset.toString(),
33
+ sellAsset: sellAsset.toString(),
34
+ destinationAddress: recipient,
35
+ }),
36
+ }).then((res) => res.json());
37
+ return response;
38
+ }
39
+ catch (error) {
40
+ throw new helpers_1.SwapKitError("chainflip_channel_error", error);
41
+ }
42
+ });
43
+ }
44
+ exports.confirmSwap = confirmSwap;
45
+ const plugin = ({ wallets, config: { brokerEndpoint }, }) => {
46
+ function swap(_a) {
47
+ var _b, _c;
48
+ var { recipient } = _a, rest = __rest(_a, ["recipient"]);
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ if (!("route" in rest && ((_b = rest.route) === null || _b === void 0 ? void 0 : _b.buyAsset) && brokerEndpoint)) {
51
+ throw new helpers_1.SwapKitError("core_swap_invalid_params");
52
+ }
53
+ const { buyAsset: buyString, sellAsset: sellString, sellAmount } = rest.route;
54
+ if (!(sellString && buyString)) {
55
+ throw new helpers_1.SwapKitError("core_swap_asset_not_recognized");
56
+ }
57
+ const sellAsset = yield helpers_1.AssetValue.fromString(sellString);
58
+ if (!(wallets === null || wallets === void 0 ? void 0 : wallets[sellAsset.chain])) {
59
+ throw new helpers_1.SwapKitError("core_wallet_connection_not_found");
60
+ }
61
+ const buyAsset = yield helpers_1.AssetValue.fromString(buyString);
62
+ const assetValue = sellAsset.set(sellAmount);
63
+ const { depositAddress } = yield confirmSwap({
64
+ brokerEndpoint,
65
+ buyAsset,
66
+ recipient,
67
+ sellAsset,
68
+ });
69
+ const tx = yield wallets[sellAsset.chain].transfer({
70
+ assetValue,
71
+ from: (_c = wallets[sellAsset.chain]) === null || _c === void 0 ? void 0 : _c.address,
72
+ recipient: depositAddress,
73
+ });
74
+ return tx;
75
+ });
76
+ }
77
+ return { swap };
78
+ };
79
+ exports.ChainflipPlugin = { chainflip: { plugin } };
80
+ /**
81
+ * @deprecated Use import { ChainflipPlugin } from "@swapkit/chainflip" instead
82
+ */
83
+ exports.ChainflipProvider = exports.ChainflipPlugin;
package/lib/types.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { AssetValue } from "@swapkit/helpers";
2
+ export type WithdrawFeeResponse = {
3
+ egressId: string;
4
+ egressAsset: string;
5
+ egressAmount: string;
6
+ egressFee: string;
7
+ destinationAddress: string;
8
+ };
9
+ export type SwapDepositResponse = {
10
+ depositChannelId: string;
11
+ depositAddress: string;
12
+ srcChainExpiryBlock: number;
13
+ sellAsset: AssetValue;
14
+ buyAsset: AssetValue;
15
+ recipient: string;
16
+ brokerCommissionBPS: number;
17
+ };
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@pioneer-platform/chainflip-client",
3
+ "version": "0.0.2",
4
+ "main": "./lib/index.js",
5
+ "types": "./lib/index.d.ts",
6
+ "dependencies": {
7
+ "@pioneer-platform/loggerdog": "^8.3.1",
8
+ "@pioneer-platform/maya-network": "^8.3.7",
9
+ "@pioneer-platform/pioneer-caip": "^9.2.23",
10
+ "@pioneer-platform/pioneer-coins": "^9.2.13",
11
+ "@polkadot/api": "^10.13.1",
12
+ "axios": "^1.3.4",
13
+ "dotenv": "^8.2.0",
14
+ "ethers": "^6.12.0",
15
+ "uuidv4": "^6.2.13",
16
+ "web3": "1.10.3"
17
+ },
18
+ "scripts": {
19
+ "npm": "npm i",
20
+ "test": "npm run build && node __tests__/test-module.js",
21
+ "build": "tsc -p .",
22
+ "prepublish": "npm run build",
23
+ "refresh": "rm -rf ./node_modules ./package-lock.json && npm install"
24
+ },
25
+ "devDependencies": {
26
+ "@types/jest": "^25.2.3",
27
+ "@types/node": "^13.13.21",
28
+ "@types/source-map-support": "^0.5.3",
29
+ "jest": "^26.4.2",
30
+ "onchange": "^7.0.2",
31
+ "serve": "^11.3.2",
32
+ "ts-jest": "^29.0.5",
33
+ "typescript": "^5.0.2"
34
+ },
35
+ "gitHead": "a76012f6693a12181c4744e53e977a9eaeef0ed3",
36
+ "peerDependencies": {}
37
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2015",
4
+ "skipLibCheck": true,
5
+ "module": "commonjs",
6
+ "lib": ["es6", "es2015", "dom"],
7
+ "declaration": true,
8
+ "outDir": "lib",
9
+ "rootDir": "src",
10
+ "strict": true,
11
+ "types": ["node"],
12
+ "esModuleInterop": true
13
+ }
14
+ }