@chainflip/sdk 2.3.2 → 2.3.4-dev.1

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/swap.cjs CHANGED
@@ -3,19 +3,18 @@
3
3
  var assertion = require('@chainflip/utils/assertion');
4
4
  var chainflip = require('@chainflip/utils/chainflip');
5
5
  var lending = require('@chainflip/utils/lending');
6
- var core = require('@ts-rest/core');
7
- var z3 = require('zod');
8
- var solana = require('@chainflip/solana');
6
+ var rpc = require('@chainflip/rpc');
7
+ var bytes = require('@chainflip/utils/bytes');
9
8
  var ss58 = require('@chainflip/utils/ss58');
9
+ var string = require('@chainflip/utils/string');
10
+ var tickMath = require('@chainflip/utils/tickMath');
11
+ var BigNumber2 = require('bignumber.js');
12
+ var zod = require('zod');
13
+ var solana = require('@chainflip/solana');
10
14
  var tron = require('@chainflip/utils/tron');
11
15
  var bitcoin = require('@chainflip/bitcoin');
12
- var string = require('@chainflip/utils/string');
13
16
  var ethers = require('ethers');
14
17
  var number = require('@chainflip/utils/number');
15
- var rpc = require('@chainflip/rpc');
16
- var bytes = require('@chainflip/utils/bytes');
17
- var tickMath = require('@chainflip/utils/tickMath');
18
- var BigNumber2 = require('bignumber.js');
19
18
  var consts = require('@chainflip/utils/consts');
20
19
  var axios = require('axios');
21
20
 
@@ -39,24 +38,23 @@ function _interopNamespace(e) {
39
38
  return Object.freeze(n);
40
39
  }
41
40
 
42
- var z3__default = /*#__PURE__*/_interopDefault(z3);
43
41
  var ss58__namespace = /*#__PURE__*/_interopNamespace(ss58);
42
+ var BigNumber2__default = /*#__PURE__*/_interopDefault(BigNumber2);
44
43
  var bitcoin__namespace = /*#__PURE__*/_interopNamespace(bitcoin);
45
44
  var ethers__namespace = /*#__PURE__*/_interopNamespace(ethers);
46
- var BigNumber2__default = /*#__PURE__*/_interopDefault(BigNumber2);
47
45
  var axios__default = /*#__PURE__*/_interopDefault(axios);
48
46
 
49
47
  // src/swap/sdk.ts
50
- var booleanString = z3.z.string().regex(/^(true|false)$/i).transform((v) => v.toLowerCase() === "true");
51
- var numericString = z3.z.string().regex(/^[0-9]+$/);
52
- var numericOrEmptyString = z3.z.string().regex(/^[0-9]*$/);
53
- var hexString = z3.z.string().refine((v) => /^0x[0-9a-f]*$/i.test(v));
48
+ var booleanString = zod.z.string().regex(/^(true|false)$/i).transform((v) => v.toLowerCase() === "true");
49
+ var numericString = zod.z.string().regex(/^[0-9]+$/);
50
+ var numericOrEmptyString = zod.z.string().regex(/^[0-9]*$/);
51
+ var hexString = zod.z.string().refine((v) => /^0x[0-9a-f]*$/i.test(v));
54
52
  var hexStringWithMaxByteSize = (maxByteSize) => hexString.refine((val) => val.length / 2 <= maxByteSize + 1, {
55
53
  message: `String must be less than or equal to ${maxByteSize} bytes`
56
54
  });
57
- var basisPoints = z3.z.number().int({ message: "must be in basis points" });
55
+ var basisPoints = zod.z.number().int({ message: "must be in basis points" });
58
56
  var DOT_PREFIX = 0;
59
- var chainflipAddress = z3.z.string().refine(
57
+ var chainflipAddress = zod.z.string().refine(
60
58
  (address) => {
61
59
  if (!address.startsWith("cF")) return false;
62
60
  try {
@@ -66,76 +64,32 @@ var chainflipAddress = z3.z.string().refine(
66
64
  return false;
67
65
  }
68
66
  },
69
- (address) => ({ message: `${address} is not a valid Chainflip address` })
67
+ { error: (issue) => `${issue.input} is not a valid Chainflip address` }
70
68
  );
71
- z3.z.string().refine(solana.isValidSolanaAddress, (address) => ({
72
- message: `${address} is not a valid Solana address`
73
- }));
74
- var tronAddress = z3.z.string().refine(tron.isValidTronAddress, (address) => ({
75
- message: `${address} is not a valid Tron address`
76
- }));
77
- var u128 = z3.z.union([z3.z.number(), numericString, hexString]).transform((arg) => BigInt(arg));
78
- var unsignedInteger = z3.z.union([u128, z3.z.number().transform((n) => BigInt(n))]);
79
- var chain = z3.z.enum(chainflip.chainflipChains);
80
- var asset = z3.z.enum(chainflip.assetSymbols);
81
- var uncheckedAssetAndChain = z3.z.object({
82
- asset: z3.z.string(),
83
- chain: z3.z.string()
69
+ zod.z.string().refine(solana.isValidSolanaAddress, {
70
+ error: (issue) => `${issue.input} is not a valid Solana address`
71
+ });
72
+ zod.z.string().refine(tron.isValidTronAddress, {
73
+ error: (issue) => `${issue.input} is not a valid Tron address`
74
+ });
75
+ var u16 = zod.z.number().int().nonnegative().max(65535);
76
+ var u32 = zod.z.number().int().nonnegative().max(4294967295);
77
+ var u128 = zod.z.union([
78
+ zod.z.number().int().nonnegative().safe(),
79
+ numericString,
80
+ hexString.refine((v) => v.length > 2, { message: "hex string must not be empty" })
81
+ ]).transform((arg) => BigInt(arg)).refine((n) => n < 2n ** 128n, { message: "must be less than 2^128" });
82
+ var unsignedInteger = u128;
83
+ var chain = zod.z.enum(chainflip.chainflipChains);
84
+ var asset = zod.z.enum(chainflip.assetSymbols);
85
+ var uncheckedAssetAndChain = zod.z.object({
86
+ asset: zod.z.string(),
87
+ chain: zod.z.string()
84
88
  });
85
89
  var assetAndChain = uncheckedAssetAndChain.refine(
86
- (value) => chainflip.isValidAssetAndChain(value)
90
+ (value) => chain.safeParse(value.chain).success && asset.safeParse(value.asset).success && chainflip.isValidAssetAndChain(value)
87
91
  );
88
92
 
89
- // ../shared/src/api/encodeVaultSwapData.ts
90
- var EncodedVaultSwapData = z3.z.discriminatedUnion("chain", [
91
- z3.z.object({
92
- chain: z3.z.literal("Bitcoin"),
93
- nulldataPayload: hexString,
94
- depositAddress: z3.z.string()
95
- }),
96
- z3.z.object({
97
- chain: z3.z.enum(["Ethereum", "Arbitrum", "Bsc"]),
98
- value: z3.z.string(),
99
- to: hexString,
100
- calldata: hexString,
101
- sourceTokenAddress: hexString.optional()
102
- }),
103
- z3.z.object({
104
- chain: z3.z.literal("Tron"),
105
- calldata: hexString,
106
- value: z3.z.string(),
107
- to: tronAddress,
108
- note: hexString,
109
- sourceTokenAddress: tronAddress.optional()
110
- }),
111
- z3.z.object({
112
- chain: z3.z.literal("Solana"),
113
- programId: z3.z.string(),
114
- data: hexString,
115
- accounts: z3.z.array(
116
- z3.z.object({
117
- pubkey: z3.z.string(),
118
- isSigner: z3.z.boolean(),
119
- isWritable: z3.z.boolean()
120
- })
121
- )
122
- })
123
- ]);
124
- var NetworkInfo = z3__default.default.object({
125
- assets: z3__default.default.array(
126
- z3__default.default.object({
127
- asset: z3__default.default.enum(chainflip.chainflipAssets),
128
- vaultSwapDepositsEnabled: z3__default.default.boolean(),
129
- depositChannelDepositsEnabled: z3__default.default.boolean(),
130
- depositChannelCreationEnabled: z3__default.default.boolean(),
131
- egressEnabled: z3__default.default.boolean(),
132
- boostDepositsEnabled: z3__default.default.boolean(),
133
- livePriceProtectionEnabled: z3__default.default.boolean()
134
- })
135
- ),
136
- cfBrokerCommissionBps: z3__default.default.number()
137
- });
138
-
139
93
  // ../shared/src/guards.ts
140
94
  var isNotNullish = (value) => value !== null && value !== void 0;
141
95
  function assert(condition, message, Constructor = Error) {
@@ -210,114 +164,133 @@ var validators = {
210
164
  Bsc: validateEvmAddress
211
165
  }
212
166
  };
213
- var validateAddress = (chain2, address, network) => validators[network][chain2](address);
167
+ var validateAddress = (chain2, address, network) => Object.hasOwn(validators, network) && Object.hasOwn(validators[network], chain2) && validators[network][chain2](address);
214
168
 
215
169
  // ../shared/src/api/openAccountCreationDepositChannel.ts
216
- var getAccountCreationDepositChannelSchema = (network) => z3.z.object({
217
- signatureData: z3.z.object({
218
- Ethereum: z3.z.object({
170
+ var getAccountCreationDepositChannelSchema = (network) => zod.z.object({
171
+ signatureData: zod.z.object({
172
+ Ethereum: zod.z.object({
219
173
  signature: hexString,
220
174
  signer: hexString,
221
- sigType: z3.z.literal("Eip712")
175
+ sigType: zod.z.literal("Eip712")
222
176
  }).transform(({ sigType, ...rest }) => ({
223
177
  sig_type: sigType,
224
178
  ...rest
225
179
  }))
226
180
  }),
227
- transactionMetadata: z3.z.object({
228
- nonce: z3.z.number().gte(0),
229
- expiryBlock: z3.z.number().positive()
181
+ transactionMetadata: zod.z.object({
182
+ nonce: u32,
183
+ expiryBlock: u32.positive()
230
184
  }).transform(({ nonce, expiryBlock }) => ({
231
185
  nonce,
232
186
  expiry_block: expiryBlock
233
187
  })),
234
188
  asset: assetAndChain,
235
- refundAddress: z3.z.string(),
236
- boostFeeBps: z3.z.number().optional().default(0)
189
+ refundAddress: zod.z.string(),
190
+ boostFeeBps: u16.optional().default(0)
237
191
  }).superRefine(({ asset: asset2, refundAddress }, ctx) => {
238
192
  if (!validateAddress(asset2.chain, refundAddress, network)) {
239
193
  ctx.addIssue({
240
194
  message: `Address "${refundAddress}" is not a valid "${asset2.chain}" address for "${network}"`,
241
- code: z3.z.ZodIssueCode.custom
195
+ code: zod.z.ZodIssueCode.custom
242
196
  });
243
197
  }
244
198
  });
245
- z3.z.object({
199
+
200
+ // ../shared/src/strings.ts
201
+ var toCamelCase = (str) => str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
202
+
203
+ // ../shared/src/objects.ts
204
+ var transformKeysToCamelCase = (obj) => {
205
+ if (Array.isArray(obj)) {
206
+ return obj.map(transformKeysToCamelCase);
207
+ }
208
+ if (obj !== null && typeof obj === "object") {
209
+ return Object.fromEntries(
210
+ Object.entries(obj).map(([key, value]) => [
211
+ toCamelCase(key),
212
+ transformKeysToCamelCase(value)
213
+ ])
214
+ );
215
+ }
216
+ return obj;
217
+ };
218
+ zod.z.object({
246
219
  srcChain: chain,
247
220
  srcAsset: asset,
248
221
  destChain: chain,
249
222
  destAsset: asset,
250
223
  amount: numericString.transform((v) => BigInt(v)).refine((v) => v > 0n, { message: "swap input amount must be greater than 0" }).refine((v) => v < 2n ** 128n, { message: "swap input amount must be less than 2^128" }),
251
- brokerCommissionBps: numericOrEmptyString.transform((v) => Number(v)).optional(),
252
- ccmGasBudget: z3.z.union([
224
+ brokerCommissionBps: numericOrEmptyString.transform((v) => Number(v)).pipe(u16).optional(),
225
+ ccmGasBudget: zod.z.union([
253
226
  numericString.transform((v) => BigInt(v)).refine((v) => v < 2n ** 128n, { message: "ccm gas budget must be less than 2^128" }),
254
- z3.z.literal("undefined").transform(() => void 0)
227
+ zod.z.literal("undefined").transform(() => void 0)
255
228
  // sdk version 1.8.2 sends undefined string if not set
256
229
  ]).optional(),
257
- ccmMessageLengthBytes: z3.z.union([
258
- numericString.transform((v) => Number(v)),
259
- z3.z.literal("undefined").transform(() => void 0)
230
+ ccmMessageLengthBytes: zod.z.union([
231
+ numericString.transform((v) => Number(v)).pipe(u32),
232
+ zod.z.literal("undefined").transform(() => void 0)
260
233
  // sdk version 1.8.2 sends undefined string if not set
261
234
  ]).optional(),
262
- dcaV2Enabled: booleanString.default("false"),
235
+ dcaV2Enabled: booleanString.prefault("false"),
263
236
  isVaultSwap: booleanString.optional(),
264
237
  isOnChain: booleanString.optional(),
265
238
  brokerAccount: chainflipAddress.optional(),
266
239
  brokerIdSs58: chainflipAddress.optional(),
267
- expectedResponseTimeMs: numericString.transform((v) => Number(v)).optional()
240
+ expectedResponseTimeMs: numericString.transform((v) => Number(v)).pipe(u32).optional()
268
241
  }).transform((args, ctx) => {
269
242
  const { srcAsset, destAsset } = chainflip.getInternalAssets(args, false);
270
243
  let hadError = false;
271
244
  if (srcAsset === null) {
272
245
  ctx.addIssue({
273
246
  message: `invalid asset and chain combination: ${JSON.stringify({ asset: args.srcAsset, chain: args.srcChain })}`,
274
- code: z3.z.ZodIssueCode.custom
247
+ code: zod.z.ZodIssueCode.custom
275
248
  });
276
249
  hadError = true;
277
250
  }
278
251
  if (destAsset === null) {
279
252
  ctx.addIssue({
280
253
  message: `invalid asset and chain combination: ${JSON.stringify({ asset: args.destAsset, chain: args.destChain })}`,
281
- code: z3.z.ZodIssueCode.custom
254
+ code: zod.z.ZodIssueCode.custom
282
255
  });
283
256
  hadError = true;
284
257
  }
285
258
  if (args.ccmGasBudget !== void 0 && args.ccmMessageLengthBytes === void 0) {
286
259
  ctx.addIssue({
287
260
  message: `ccmMessageLengthBytes must be set if ccmGasBudget is set`,
288
- code: z3.z.ZodIssueCode.custom
261
+ code: zod.z.ZodIssueCode.custom
289
262
  });
290
263
  hadError = true;
291
264
  }
292
265
  if (args.ccmGasBudget === void 0 && args.ccmMessageLengthBytes !== void 0) {
293
266
  ctx.addIssue({
294
267
  message: `ccmGasBudget must be set if ccmMessageLengthBytes is set`,
295
- code: z3.z.ZodIssueCode.custom
268
+ code: zod.z.ZodIssueCode.custom
296
269
  });
297
270
  hadError = true;
298
271
  }
299
272
  if (args.isOnChain && args.isVaultSwap) {
300
273
  ctx.addIssue({
301
274
  message: "isOnChain and isVaultSwap cannot be set at the same time",
302
- code: z3.z.ZodIssueCode.custom
275
+ code: zod.z.ZodIssueCode.custom
303
276
  });
304
277
  hadError = true;
305
278
  }
306
279
  if (args.isVaultSwap && args.srcChain === "Assethub") {
307
280
  ctx.addIssue({
308
281
  message: "Vault swaps are not supported on Assethub",
309
- code: z3.z.ZodIssueCode.custom
282
+ code: zod.z.ZodIssueCode.custom
310
283
  });
311
284
  hadError = true;
312
285
  }
313
286
  if (args.isOnChain && args.brokerCommissionBps !== void 0 && args.brokerCommissionBps > 0) {
314
287
  ctx.addIssue({
315
288
  message: "isOnChain cannot be set with a non-zero broker commission",
316
- code: z3.z.ZodIssueCode.custom
289
+ code: zod.z.ZodIssueCode.custom
317
290
  });
318
291
  hadError = true;
319
292
  }
320
- if (hadError) return z3.z.NEVER;
293
+ if (hadError) return zod.z.NEVER;
321
294
  const ccmParams = args.ccmGasBudget !== void 0 && args.ccmMessageLengthBytes !== void 0 ? { gasBudget: args.ccmGasBudget, messageLengthBytes: args.ccmMessageLengthBytes } : void 0;
322
295
  return {
323
296
  srcAsset,
@@ -332,8 +305,8 @@ z3.z.object({
332
305
  expectedResponseTimeMs: args.expectedResponseTimeMs
333
306
  };
334
307
  });
335
- var ccmParamsSchema = z3.z.object({
336
- gasBudget: z3.z.union([numericString, hexString]).transform((n) => BigInt(n)).refine((n) => n < 2n ** 128n, { message: "ccm gas budget must be less than 2^128" }).transform((n) => number.hexEncodeNumber(n)),
308
+ var ccmParamsSchema = zod.z.object({
309
+ gasBudget: zod.z.union([numericString, hexString]).transform((n) => BigInt(n)).refine((n) => n < 2n ** 128n, { message: "ccm gas budget must be less than 2^128" }).transform((n) => number.hexEncodeNumber(n)),
337
310
  // https://github.com/chainflip-io/chainflip-backend/blob/415aa9e20ec4046c68892cd34798e5d831c5b83f/state-chain/chains/src/lib.rs#L709
338
311
  message: hexStringWithMaxByteSize(15e3),
339
312
  // https://github.com/chainflip-io/chainflip-backend/blob/415aa9e20ec4046c68892cd34798e5d831c5b83f/state-chain/chains/src/lib.rs#L710
@@ -343,94 +316,22 @@ var ccmParamsSchema = z3.z.object({
343
316
  message,
344
317
  ccmAdditionalData: ccmAdditionalData ?? "0x"
345
318
  }));
346
- var affiliateBroker = z3.z.object({
319
+ var affiliateBroker = zod.z.object({
347
320
  account: chainflipAddress,
348
- commissionBps: z3.z.number()
321
+ commissionBps: u16
349
322
  }).transform(({ account, commissionBps: bps }) => ({ account, bps }));
350
- var dcaParams = z3.z.object({
351
- numberOfChunks: z3.z.number(),
352
- chunkIntervalBlocks: z3.z.number()
323
+ var dcaParams = zod.z.object({
324
+ numberOfChunks: u32.min(1, { message: "number of chunks must be greater than 0" }),
325
+ chunkIntervalBlocks: u32
353
326
  });
354
- var fillOrKillParams = z3.z.object({
355
- retryDurationBlocks: z3.z.number(),
356
- refundAddress: z3.z.string(),
327
+ zod.z.object({
328
+ retryDurationBlocks: u32,
329
+ refundAddress: zod.z.string(),
357
330
  minPriceX128: numericString,
358
331
  maxOraclePriceSlippage: basisPoints.nullish().transform((v) => v ?? null),
359
332
  refundCcmMetadata: ccmParamsSchema.nullish().optional().default(null)
360
333
  });
361
334
 
362
- // ../shared/src/api/openSwapDepositChannel.ts
363
- var assets = z3.z.object({
364
- srcAsset: assetAndChain,
365
- destAsset: assetAndChain
366
- });
367
- var amountString = numericString.max(30, { message: "must have at most 30 digits" });
368
- var getOpenSwapDepositChannelSchema = (network) => z3.z.intersection(
369
- assets,
370
- z3.z.object({
371
- destAddress: z3.z.string(),
372
- amount: amountString,
373
- ccmParams: ccmParamsSchema.optional(),
374
- maxBoostFeeBps: z3.z.number().optional(),
375
- srcAddress: z3.z.string().optional(),
376
- fillOrKillParams,
377
- dcaParams: dcaParams.optional(),
378
- quote: z3.z.object({
379
- intermediateAmount: amountString.optional(),
380
- egressAmount: amountString,
381
- estimatedPrice: z3.z.string().regex(/^[0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?$/i, { message: "must be a decimal number" }).refine((v) => Number(v) < 1e35, { message: "must be less than 10^35" }),
382
- recommendedSlippageTolerancePercent: z3.z.number().optional(),
383
- recommendedLivePriceSlippageTolerancePercent: z3.z.number().optional()
384
- }).optional(),
385
- takeCommission: z3.z.boolean().optional()
386
- })
387
- ).superRefine(({ ...val }, ctx) => {
388
- if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
389
- ctx.addIssue({
390
- message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
391
- code: z3.z.ZodIssueCode.custom
392
- });
393
- }
394
- if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refundAddress, network)) {
395
- ctx.addIssue({
396
- message: `Address "${val.fillOrKillParams.refundAddress}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
397
- code: z3.z.ZodIssueCode.custom
398
- });
399
- }
400
- }).transform(({ amount, ...rest }) => ({
401
- ...rest,
402
- expectedDepositAmount: amount
403
- }));
404
- var DepositChannelInfo = z3.z.object({
405
- id: z3.z.string(),
406
- depositAddress: z3.z.string(),
407
- brokerCommissionBps: z3.z.number(),
408
- maxBoostFeeBps: z3.z.number(),
409
- issuedBlock: z3.z.number(),
410
- srcChainExpiryBlock: z3.z.string(),
411
- estimatedExpiryTime: z3.z.number().optional(),
412
- channelOpeningFee: z3.z.string()
413
- });
414
-
415
- // ../shared/src/strings.ts
416
- var toCamelCase = (str) => str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
417
-
418
- // ../shared/src/objects.ts
419
- var transformKeysToCamelCase = (obj) => {
420
- if (Array.isArray(obj)) {
421
- return obj.map(transformKeysToCamelCase);
422
- }
423
- if (obj !== null && typeof obj === "object") {
424
- return Object.fromEntries(
425
- Object.entries(obj).map(([key, value]) => [
426
- toCamelCase(key),
427
- transformKeysToCamelCase(value)
428
- ])
429
- );
430
- }
431
- return obj;
432
- };
433
-
434
335
  // ../shared/src/broker.ts
435
336
  var transformedDcaParamsSchema = dcaParams.transform(
436
337
  ({ numberOfChunks, chunkIntervalBlocks }) => ({
@@ -445,9 +346,9 @@ var transformedCcmParamsSchema = ccmParamsSchema.transform(
445
346
  ccm_additional_data: ccmAdditionalData
446
347
  })
447
348
  );
448
- var transformedFokSchema = z3.z.object({
449
- retryDurationBlocks: z3.z.number(),
450
- refundAddress: z3.z.string(),
349
+ var transformedFokSchema = zod.z.object({
350
+ retryDurationBlocks: u32,
351
+ refundAddress: zod.z.string(),
451
352
  minPriceX128: numericString,
452
353
  maxOraclePriceSlippage: basisPoints.nullish().transform((v) => v ?? null),
453
354
  refundCcmMetadata: transformedCcmParamsSchema.nullable().optional().default(null)
@@ -466,67 +367,68 @@ var transformedFokSchema = z3.z.object({
466
367
  refund_ccm_metadata: refundCcmMetadata
467
368
  })
468
369
  );
469
- var getDepositAddressRequestSchema = (network) => z3.z.object({
370
+ var getDepositAddressRequestSchema = (network) => zod.z.object({
470
371
  srcAsset: assetAndChain,
471
372
  destAsset: assetAndChain,
472
- destAddress: z3.z.string(),
473
- commissionBps: z3.z.number().optional().default(0),
373
+ destAddress: zod.z.string(),
374
+ commissionBps: u16.optional().default(0),
474
375
  ccmParams: transformedCcmParamsSchema.optional(),
475
- maxBoostFeeBps: z3.z.number().optional(),
476
- affiliates: z3.z.array(affiliateBroker).optional(),
376
+ maxBoostFeeBps: u16.optional(),
377
+ affiliates: zod.z.array(affiliateBroker).optional(),
477
378
  fillOrKillParams: transformedFokSchema,
478
379
  dcaParams: transformedDcaParamsSchema.optional()
479
380
  }).superRefine((val, ctx) => {
480
381
  if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
481
382
  ctx.addIssue({
482
383
  message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
483
- code: z3.z.ZodIssueCode.custom
384
+ code: zod.z.ZodIssueCode.custom
484
385
  });
485
386
  }
486
387
  if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refund_address, network)) {
487
388
  ctx.addIssue({
488
389
  message: `Address "${val.fillOrKillParams.refund_address}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
489
- code: z3.z.ZodIssueCode.custom
390
+ code: zod.z.ZodIssueCode.custom
490
391
  });
491
392
  }
492
393
  });
493
- var getVaultSwapParameterEncodingRequestSchema = (network) => z3.z.object({
394
+ var getVaultSwapParameterEncodingRequestSchema = (network) => zod.z.object({
494
395
  srcAsset: assetAndChain,
495
- srcAddress: z3.z.string().optional(),
396
+ srcAddress: zod.z.string().optional(),
496
397
  destAsset: assetAndChain,
497
- destAddress: z3.z.string(),
398
+ destAddress: zod.z.string(),
498
399
  amount: unsignedInteger,
499
- commissionBps: z3.z.number().optional().default(0),
400
+ commissionBps: u16.optional().default(0),
500
401
  ccmParams: transformedCcmParamsSchema.optional(),
501
- maxBoostFeeBps: z3.z.number().optional(),
502
- affiliates: z3.z.array(affiliateBroker).optional(),
402
+ maxBoostFeeBps: u16.optional(),
403
+ affiliates: zod.z.array(affiliateBroker).optional(),
503
404
  fillOrKillParams: transformedFokSchema,
504
405
  dcaParams: transformedDcaParamsSchema.optional(),
505
- extraParams: z3.z.object({ seed: hexString.optional() }).optional(),
406
+ extraParams: zod.z.object({ seed: hexString.optional() }).optional(),
407
+ // TODO: remove after brokerAccount is deprecated
506
408
  brokerAccount: chainflipAddress.optional()
507
409
  }).superRefine((val, ctx) => {
508
410
  if (val.srcAddress && !validateAddress(val.srcAsset.chain, val.srcAddress, network)) {
509
411
  ctx.addIssue({
510
412
  message: `Address "${val.srcAddress}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
511
- code: z3.z.ZodIssueCode.custom
413
+ code: zod.z.ZodIssueCode.custom
512
414
  });
513
415
  }
514
416
  if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
515
417
  ctx.addIssue({
516
418
  message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
517
- code: z3.z.ZodIssueCode.custom
419
+ code: zod.z.ZodIssueCode.custom
518
420
  });
519
421
  }
520
422
  if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refund_address, network)) {
521
423
  ctx.addIssue({
522
424
  message: `Address "${val.fillOrKillParams.refund_address}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
523
- code: z3.z.ZodIssueCode.custom
425
+ code: zod.z.ZodIssueCode.custom
524
426
  });
525
427
  }
526
428
  if (val.extraParams?.seed && val.extraParams.seed.length !== 66) {
527
- ctx.addIssue({ message: "Seed must be 32 bytes", code: z3.z.ZodIssueCode.custom });
429
+ ctx.addIssue({ message: "Seed must be 32 bytes", code: zod.z.ZodIssueCode.custom });
528
430
  }
529
- }).transform((data) => {
431
+ }).transform((data, ctx) => {
530
432
  let extraParams;
531
433
  if (data.srcAsset.chain === "Bitcoin") {
532
434
  const minOutputAmount = BigNumber2__default.default(data.amount.toString()).multipliedBy(tickMath.priceX128ToPrice(data.fillOrKillParams.min_price)).toFixed(0);
@@ -543,7 +445,13 @@ var getVaultSwapParameterEncodingRequestSchema = (network) => z3.z.object({
543
445
  refund_parameters: data.fillOrKillParams
544
446
  };
545
447
  } else if (data.srcAsset.chain === "Solana") {
546
- assert(data.srcAddress, "srcAddress is required for Solana");
448
+ if (!data.srcAddress) {
449
+ ctx.addIssue({
450
+ message: "srcAddress is required for Solana",
451
+ code: zod.z.ZodIssueCode.custom
452
+ });
453
+ return zod.z.NEVER;
454
+ }
547
455
  extraParams = {
548
456
  chain: "Solana",
549
457
  from: data.srcAddress,
@@ -552,7 +460,11 @@ var getVaultSwapParameterEncodingRequestSchema = (network) => z3.z.object({
552
460
  refund_parameters: data.fillOrKillParams
553
461
  };
554
462
  } else {
555
- throw new Error(`parameter encoding is not supported for ${data.srcAsset.chain}`);
463
+ ctx.addIssue({
464
+ message: `parameter encoding is not supported for ${data.srcAsset.chain}`,
465
+ code: zod.z.ZodIssueCode.custom
466
+ });
467
+ return zod.z.NEVER;
556
468
  }
557
469
  return { ...data, extraParams };
558
470
  });
@@ -606,36 +518,37 @@ async function requestSwapParameterEncoding(request, opts, chainflipNetwork) {
606
518
  );
607
519
  return transformKeysToCamelCase(response);
608
520
  }
609
- var getParameterEncodingRequestSchema = (network) => z3.z.object({
521
+ var getParameterEncodingRequestSchema = (network) => zod.z.object({
610
522
  srcAsset: assetAndChain,
611
- srcAddress: z3.z.string().optional(),
523
+ srcAddress: zod.z.string().optional(),
612
524
  destAsset: assetAndChain,
613
- destAddress: z3.z.string(),
525
+ destAddress: zod.z.string(),
614
526
  amount: unsignedInteger,
615
- commissionBps: z3.z.number().optional().default(0),
527
+ commissionBps: u16.optional().default(0),
616
528
  ccmParams: transformedCcmParamsSchema.optional(),
617
- maxBoostFeeBps: z3.z.number().optional(),
618
- affiliates: z3.z.array(affiliateBroker).optional(),
529
+ maxBoostFeeBps: u16.optional(),
530
+ affiliates: zod.z.array(affiliateBroker).optional(),
619
531
  fillOrKillParams: transformedFokSchema,
620
532
  dcaParams: transformedDcaParamsSchema.optional(),
533
+ // TODO: remove after brokerAccount is deprecated
621
534
  brokerAccount: chainflipAddress.optional()
622
535
  }).superRefine(({ ...val }, ctx) => {
623
536
  if (val.srcAddress && !validateAddress(val.srcAsset.chain, val.srcAddress, network)) {
624
537
  ctx.addIssue({
625
538
  message: `Address "${val.srcAddress}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
626
- code: z3.z.ZodIssueCode.custom
539
+ code: zod.z.ZodIssueCode.custom
627
540
  });
628
541
  }
629
542
  if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
630
543
  ctx.addIssue({
631
544
  message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
632
- code: z3.z.ZodIssueCode.custom
545
+ code: zod.z.ZodIssueCode.custom
633
546
  });
634
547
  }
635
548
  if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refund_address, network)) {
636
549
  ctx.addIssue({
637
550
  message: `Address "${val.fillOrKillParams.refund_address}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
638
- code: z3.z.ZodIssueCode.custom
551
+ code: zod.z.ZodIssueCode.custom
639
552
  });
640
553
  }
641
554
  }).transform(({ ...rest }) => rest);
@@ -656,56 +569,22 @@ async function requestCfParametersEncoding(request, opts, network) {
656
569
  );
657
570
  return response;
658
571
  }
659
-
660
- // ../shared/src/api/contract.ts
661
- var c = core.initContract();
662
- var createApiContract = (network) => c.router(
663
- {
664
- networkInfo: {
665
- method: "GET",
666
- path: "/networkInfo",
667
- responses: {
668
- 200: NetworkInfo
669
- },
670
- summary: "Get information about the Chainflip network"
671
- },
672
- encodeCfParameters: {
673
- method: "POST",
674
- path: "/encodeCfParameters",
675
- body: getParameterEncodingRequestSchema(network),
676
- responses: {
677
- 200: hexString
678
- }
679
- },
680
- encodeVaultSwapData: {
681
- method: "POST",
682
- path: "/encodeVaultSwapData",
683
- body: getVaultSwapParameterEncodingRequestSchema(network),
684
- responses: {
685
- 200: EncodedVaultSwapData
686
- }
687
- },
688
- openSwapDepositChannel: {
689
- method: "POST",
690
- path: "/openSwapDepositChannel",
691
- body: getOpenSwapDepositChannelSchema(network),
692
- responses: {
693
- 201: DepositChannelInfo
694
- }
695
- },
696
- openAccountCreationDepositChannel: {
697
- method: "POST",
698
- path: "/openAccountCreationDepositChannel",
699
- body: getAccountCreationDepositChannelSchema(network),
700
- responses: {
701
- 201: DepositChannelInfo
702
- }
703
- }
704
- },
705
- {
706
- pathPrefix: "/api"
707
- }
708
- );
572
+ async function requestAccountCreationDepositAddress(request, opts, network) {
573
+ const client = new rpc.HttpClient(opts.url);
574
+ const params = getAccountCreationDepositChannelSchema(network).parse(request);
575
+ const response = await client.sendRequest(
576
+ "broker_request_account_creation_deposit_address",
577
+ params.signatureData,
578
+ params.transactionMetadata,
579
+ params.asset,
580
+ params.boostFeeBps,
581
+ params.refundAddress
582
+ );
583
+ return {
584
+ ...transformKeysToCamelCase(response),
585
+ address: formatBrokerDepositAddress(params.asset.chain, response.address)
586
+ };
587
+ }
709
588
 
710
589
  // ../shared/src/consts.ts
711
590
  var ETHEREUM_EVM_CHAIN_ID = {
@@ -833,12 +712,12 @@ var MultiCache = class {
833
712
  }
834
713
  values = {};
835
714
  read(type) {
836
- const { fetch, ttl } = this.fetchers[type];
715
+ const { fetch: fetch2, ttl } = this.fetchers[type];
837
716
  let cached = this.values[type];
838
717
  if (!cached || cached.timestamp + ttl < Date.now()) {
839
718
  cached = {
840
719
  timestamp: Date.now(),
841
- value: fetch().catch((err) => {
720
+ value: fetch2().catch((err) => {
842
721
  this.values[type] = void 0;
843
722
  throw err;
844
723
  })
@@ -901,6 +780,17 @@ function parseFoKParams(params, quote) {
901
780
  return "refundAddress" in params ? { ...parsed, refundAddress: params.refundAddress } : parsed;
902
781
  }
903
782
  var isTestnet = (network) => network !== "mainnet";
783
+ function calculateExpiryTime(args) {
784
+ const { chainInfo, expiryBlock } = args;
785
+ if (chainInfo == null || expiryBlock == null) {
786
+ return null;
787
+ }
788
+ const remainingBlocks = Number(BigInt(expiryBlock) - BigInt(chainInfo.height));
789
+ const { blockTimeSeconds } = chainflip.anyChainConstants[chainInfo.chain];
790
+ return new Date(
791
+ new Date(chainInfo.blockTrackedAt).getTime() + remainingBlocks * blockTimeSeconds * 1e3
792
+ );
793
+ }
904
794
  var camelCase = (str) => str.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
905
795
  var camelCaseKeys = (obj) => {
906
796
  if (typeof obj !== "object" || obj === null) return obj;
@@ -1009,7 +899,7 @@ var getChainData = (chain2, network, env) => ({
1009
899
 
1010
900
  // package.json
1011
901
  var package_default = {
1012
- version: "2.3.2"};
902
+ version: "2.3.4-dev.1"};
1013
903
 
1014
904
  // src/swap/consts.ts
1015
905
  var CF_SDK_VERSION_HEADERS = { "X-Chainflip-Sdk-Version": package_default.version };
@@ -1057,8 +947,64 @@ var getStatusV2 = async (baseUrl, { id }, { signal }) => {
1057
947
  });
1058
948
  return data;
1059
949
  };
950
+ var lowercaseKeys = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
951
+ var backendRequest = async (baseUrl, method, path, body) => {
952
+ const headers = lowercaseKeys(CF_SDK_VERSION_HEADERS);
953
+ let serializedBody;
954
+ if (method !== "GET" && body != null) {
955
+ headers["content-type"] = "application/json";
956
+ serializedBody = JSON.stringify(body);
957
+ }
958
+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}${path}`, {
959
+ method,
960
+ headers,
961
+ body: serializedBody
962
+ });
963
+ const contentType = res.headers.get("content-type") ?? "";
964
+ if (contentType.includes("application/") && contentType.includes("json")) {
965
+ return { status: res.status, body: await res.json(), headers: res.headers };
966
+ }
967
+ if (contentType.includes("text/")) {
968
+ return { status: res.status, body: await res.text(), headers: res.headers };
969
+ }
970
+ return { status: res.status, body: await res.blob(), headers: res.headers };
971
+ };
972
+ var apiError = (action, res) => {
973
+ const { body } = res;
974
+ const message = body && typeof body === "object" && "message" in body && typeof body.message === "string" ? `: ${body.message}` : "";
975
+ return new Error(`Failed to ${action} (${res.status})${message}`, { cause: res });
976
+ };
977
+ var getNetworkInfo = async (baseUrl) => {
978
+ const res = await backendRequest(baseUrl, "GET", "/api/networkInfo");
979
+ assert(res.status === 200, "Failed to fetch network info");
980
+ return res.body;
981
+ };
982
+ var openSwapDepositChannel = async (baseUrl, body) => {
983
+ const res = await backendRequest(baseUrl, "POST", "/api/openSwapDepositChannel", body);
984
+ if (res.status !== 201) throw apiError("open swap deposit channel", res);
985
+ return res.body;
986
+ };
987
+ var encodeVaultSwapData = async (baseUrl, body) => {
988
+ const res = await backendRequest(baseUrl, "POST", "/api/encodeVaultSwapData", body);
989
+ if (res.status !== 200) throw apiError("encode vault swap data", res);
990
+ return res.body;
991
+ };
992
+ var encodeCfParameters = async (baseUrl, body) => {
993
+ const res = await backendRequest(baseUrl, "POST", "/api/encodeCfParameters", body);
994
+ if (res.status !== 200) throw apiError("encode cf parameters", res);
995
+ return res.body;
996
+ };
997
+ var openAccountCreationDepositChannel = async (baseUrl, body) => {
998
+ const res = await backendRequest(baseUrl, "POST", "/api/openAccountCreationDepositChannel", body);
999
+ if (res.status !== 201) throw apiError("open account creation deposit channel", res);
1000
+ return res.body;
1001
+ };
1060
1002
 
1061
1003
  // src/swap/sdk.ts
1004
+ var BrokerName = {
1005
+ ChainflipSwap: "swap.chainflip.io"
1006
+ };
1007
+ var brokerNames = Object.values(BrokerName);
1062
1008
  var assertQuoteValid = (quote) => {
1063
1009
  switch (quote.type) {
1064
1010
  case "REGULAR":
@@ -1073,7 +1019,6 @@ var assertQuoteValid = (quote) => {
1073
1019
  var SwapSDK = class {
1074
1020
  options;
1075
1021
  rpcConfig;
1076
- apiClient;
1077
1022
  cache;
1078
1023
  dcaV2Enabled = false;
1079
1024
  constructor(options = {}) {
@@ -1084,12 +1029,6 @@ var SwapSDK = class {
1084
1029
  backendUrl: options.backendUrl ?? BACKEND_SERVICE_URLS[network]
1085
1030
  };
1086
1031
  this.rpcConfig = options.rpcUrl ? { rpcUrl: options.rpcUrl } : { network };
1087
- this.apiClient = core.initClient(createApiContract(this.options.network), {
1088
- // remove trailing slashes. this bug has been fixed in `@ts-rest/core`
1089
- // but it hasn't been released yet
1090
- baseUrl: this.options.backendUrl.replace(/\/+$/, ""),
1091
- baseHeaders: CF_SDK_VERSION_HEADERS
1092
- });
1093
1032
  this.dcaV2Enabled = options.enabledFeatures?.dcaV2 ?? false;
1094
1033
  this.cache = new MultiCache({
1095
1034
  environment: {
@@ -1097,11 +1036,7 @@ var SwapSDK = class {
1097
1036
  ttl: 6e4
1098
1037
  },
1099
1038
  networkInfo: {
1100
- fetch: async () => {
1101
- const res = await this.apiClient.networkInfo();
1102
- assert(res.status === 200, "Failed to fetch network info");
1103
- return res.body;
1104
- },
1039
+ fetch: () => getNetworkInfo(this.options.backendUrl),
1105
1040
  ttl: 6e4
1106
1041
  }
1107
1042
  });
@@ -1122,8 +1057,8 @@ var SwapSDK = class {
1122
1057
  return this.cache.read("environment");
1123
1058
  }
1124
1059
  async getSupportedAssets(type) {
1125
- const assets2 = await this.cache.read("networkInfo");
1126
- return assets2.assets.filter((a) => chainflip.isChainflipAsset(a.asset)).filter((a) => {
1060
+ const assets = await this.cache.read("networkInfo");
1061
+ return assets.assets.filter((a) => chainflip.isChainflipAsset(a.asset)).filter((a) => {
1127
1062
  switch (type) {
1128
1063
  case "all":
1129
1064
  return true;
@@ -1154,20 +1089,60 @@ var SwapSDK = class {
1154
1089
  ]);
1155
1090
  return supportedAssets.map((asset2) => getAssetData(asset2, this.options.network, env)).filter((asset2) => !chain2 || asset2.chain === chain2);
1156
1091
  }
1157
- // eslint-disable-next-line class-methods-use-this
1158
- shouldTakeCommission() {
1159
- return false;
1092
+ resolveBroker(fees = {}) {
1093
+ const { broker } = this.options;
1094
+ assert(
1095
+ !(broker && "name" in broker && "url" in broker),
1096
+ "A broker can be set by url or name, not both"
1097
+ );
1098
+ if (broker && "name" in broker) {
1099
+ assert(brokerNames.includes(broker.name), `Broker name "${broker.name}" is not supported`);
1100
+ assert(
1101
+ fees.brokerCommissionBps === void 0 && !fees.affiliates?.length,
1102
+ `Broker commission and affiliates are not supported with the ${broker.name} broker`
1103
+ );
1104
+ }
1105
+ return broker;
1106
+ }
1107
+ requireBroker(fees = {}) {
1108
+ const broker = this.resolveBroker(fees);
1109
+ assert(broker, "A broker url or name is required to open channels or encode swaps");
1110
+ return broker;
1160
1111
  }
1161
- async getCommissionBps(brokerCommissionBps) {
1162
- if (this.shouldTakeCommission()) {
1163
- return (await this.cache.read("networkInfo")).cfBrokerCommissionBps;
1112
+ // TODO: remove after brokerAccount is deprecated
1113
+ resolveEncodingBroker(brokerAccount, fees) {
1114
+ if (!brokerAccount) return this.requireBroker(fees);
1115
+ assert(
1116
+ !this.options.broker,
1117
+ "Setting brokerAccount is not supported when the SDK is initialized with a broker"
1118
+ );
1119
+ return void 0;
1120
+ }
1121
+ async estimateExpiryTime(chain2, expiryBlock) {
1122
+ try {
1123
+ const { chainTracking } = await this.cache.read("networkInfo");
1124
+ const chainInfo = chainTracking?.find((info) => info.chain === chain2);
1125
+ return calculateExpiryTime({ chainInfo, expiryBlock })?.getTime();
1126
+ } catch {
1127
+ return void 0;
1128
+ }
1129
+ }
1130
+ async getCommissionBps({
1131
+ brokerCommissionBps,
1132
+ affiliateBrokers,
1133
+ isOnChain
1134
+ }) {
1135
+ const broker = this.resolveBroker({ brokerCommissionBps, affiliates: affiliateBrokers });
1136
+ if (!isOnChain && broker && "name" in broker && broker.name === BrokerName.ChainflipSwap) {
1137
+ return this.getQuotedBrokerCommissionBps();
1164
1138
  }
1165
1139
  return brokerCommissionBps ?? 0;
1166
1140
  }
1141
+ async getQuotedBrokerCommissionBps() {
1142
+ return (await this.cache.read("networkInfo")).cfBrokerCommissionBps;
1143
+ }
1167
1144
  async getQuoteV2(quoteRequest, options = {}) {
1168
- const submitterBrokerCommissionBps = await this.getCommissionBps(
1169
- quoteRequest.brokerCommissionBps
1170
- );
1145
+ const submitterBrokerCommissionBps = await this.getCommissionBps(quoteRequest);
1171
1146
  return getQuoteV2(
1172
1147
  this.options.backendUrl,
1173
1148
  {
@@ -1254,8 +1229,9 @@ var SwapSDK = class {
1254
1229
  fillOrKillParams: inputFoKParams,
1255
1230
  affiliateBrokers: affiliates,
1256
1231
  ccmParams,
1257
- brokerCommissionBps: brokerCommissionBpsParam
1232
+ brokerCommissionBps
1258
1233
  }) {
1234
+ const broker = this.requireBroker({ brokerCommissionBps, affiliates });
1259
1235
  await this.validateSwapAmount(quote.srcAsset, BigInt(quote.depositAmount));
1260
1236
  assertQuoteValid(quote);
1261
1237
  assert(!quote.isVaultSwap, "Cannot open a deposit channel for a vault swap quote");
@@ -1265,7 +1241,6 @@ var SwapSDK = class {
1265
1241
  } else {
1266
1242
  assert(!quote.ccmParams, "Cannot open regular channel for quote with CCM params");
1267
1243
  }
1268
- const brokerCommissionBps = await this.getCommissionBps(brokerCommissionBpsParam);
1269
1244
  const depositAddressRequest = {
1270
1245
  srcAsset: quote.srcAsset,
1271
1246
  destAsset: quote.destAsset,
@@ -1277,43 +1252,30 @@ var SwapSDK = class {
1277
1252
  ccmParams,
1278
1253
  amount: quote.depositAmount
1279
1254
  };
1280
- let response;
1281
- if (this.options.broker) {
1255
+ let channel;
1256
+ if ("url" in broker) {
1282
1257
  const result = await requestSwapDepositAddress(
1283
- {
1284
- ...depositAddressRequest,
1285
- commissionBps: brokerCommissionBps,
1286
- affiliates
1287
- },
1288
- { url: this.options.broker.url },
1258
+ { ...depositAddressRequest, commissionBps: brokerCommissionBps ?? 0, affiliates },
1259
+ broker,
1289
1260
  this.options.network
1290
1261
  );
1291
- response = {
1262
+ channel = {
1292
1263
  id: `${result.issuedBlock}-${quote.srcAsset.chain}-${result.channelId}`,
1293
1264
  depositAddress: result.address,
1294
- brokerCommissionBps,
1265
+ brokerCommissionBps: brokerCommissionBps ?? 0,
1266
+ maxBoostFeeBps: Number(depositAddressRequest.maxBoostFeeBps) || 0,
1295
1267
  srcChainExpiryBlock: result.sourceChainExpiryBlock,
1296
- maxBoostFeeBps: depositAddressRequest.maxBoostFeeBps,
1268
+ estimatedExpiryTime: await this.estimateExpiryTime(
1269
+ quote.srcAsset.chain,
1270
+ result.sourceChainExpiryBlock
1271
+ ),
1297
1272
  channelOpeningFee: result.channelOpeningFee
1298
1273
  };
1299
1274
  } else {
1300
- assert(
1301
- !brokerCommissionBps || this.shouldTakeCommission(),
1302
- "Broker commission is supported only when initializing the SDK with a brokerUrl"
1303
- );
1304
- assert(
1305
- !affiliates?.length,
1306
- "Affiliate brokers are supported only when initializing the SDK with a brokerUrl"
1307
- );
1308
- const res = await this.apiClient.openSwapDepositChannel({
1309
- body: {
1310
- ...depositAddressRequest,
1311
- quote,
1312
- takeCommission: this.shouldTakeCommission()
1313
- }
1275
+ channel = await openSwapDepositChannel(this.options.backendUrl, {
1276
+ ...depositAddressRequest,
1277
+ quote
1314
1278
  });
1315
- assert(res.status === 201, "Failed to open swap deposit channel");
1316
- response = res.body;
1317
1279
  }
1318
1280
  return {
1319
1281
  ...depositAddressRequest,
@@ -1321,14 +1283,14 @@ var SwapSDK = class {
1321
1283
  destAsset: quote.destAsset.asset,
1322
1284
  srcChain: quote.srcAsset.chain,
1323
1285
  destChain: quote.destAsset.chain,
1324
- depositChannelId: response.id,
1325
- depositAddress: response.depositAddress,
1326
- brokerCommissionBps: response.brokerCommissionBps,
1286
+ depositChannelId: channel.id,
1287
+ depositAddress: channel.depositAddress,
1288
+ brokerCommissionBps: channel.brokerCommissionBps,
1327
1289
  affiliateBrokers: affiliates ?? [],
1328
- maxBoostFeeBps: Number(response.maxBoostFeeBps) || 0,
1329
- depositChannelExpiryBlock: BigInt(response.srcChainExpiryBlock),
1330
- estimatedDepositChannelExpiryTime: response.estimatedExpiryTime,
1331
- channelOpeningFee: BigInt(response.channelOpeningFee),
1290
+ maxBoostFeeBps: channel.maxBoostFeeBps,
1291
+ depositChannelExpiryBlock: BigInt(channel.srcChainExpiryBlock),
1292
+ estimatedDepositChannelExpiryTime: channel.estimatedExpiryTime,
1293
+ channelOpeningFee: BigInt(channel.channelOpeningFee),
1332
1294
  fillOrKillParams: inputFoKParams
1333
1295
  };
1334
1296
  }
@@ -1340,9 +1302,10 @@ var SwapSDK = class {
1340
1302
  affiliateBrokers: affiliates,
1341
1303
  ccmParams,
1342
1304
  brokerAccount,
1343
- brokerCommissionBps: brokerCommissionBpsParam,
1305
+ brokerCommissionBps,
1344
1306
  extraParams
1345
1307
  }) {
1308
+ const broker = this.resolveEncodingBroker(brokerAccount, { brokerCommissionBps, affiliates });
1346
1309
  await this.validateSwapAmount(quote.srcAsset, BigInt(quote.depositAmount));
1347
1310
  assertQuoteValid(quote);
1348
1311
  assert(quote.isVaultSwap, "Cannot encode vault swap data for non-vault swap quotes");
@@ -1351,7 +1314,6 @@ var SwapSDK = class {
1351
1314
  } else {
1352
1315
  assert(!quote.ccmParams, "Cannot encode regular swap for quote with CCM params");
1353
1316
  }
1354
- const brokerCommissionBps = await this.getCommissionBps(brokerCommissionBpsParam);
1355
1317
  const vaultSwapRequest = {
1356
1318
  srcAsset: quote.srcAsset,
1357
1319
  destAsset: quote.destAsset,
@@ -1363,41 +1325,24 @@ var SwapSDK = class {
1363
1325
  fillOrKillParams: parseFoKParams(inputFoKParams, quote),
1364
1326
  dcaParams: quote.type === "DCA" ? quote.dcaParams : void 0,
1365
1327
  extraParams,
1366
- brokerAccount,
1367
1328
  commissionBps: brokerCommissionBps,
1368
1329
  affiliates
1369
1330
  };
1370
- if (this.options.broker) {
1371
- assert(
1372
- !vaultSwapRequest.brokerAccount,
1373
- "Cannot overwrite broker account when initializing the SDK with a brokerUrl"
1374
- );
1375
- return requestSwapParameterEncoding(
1376
- vaultSwapRequest,
1377
- { url: this.options.broker.url },
1378
- this.options.network
1379
- );
1331
+ if (broker && "url" in broker) {
1332
+ return requestSwapParameterEncoding(vaultSwapRequest, broker, this.options.network);
1380
1333
  }
1381
- assert(
1382
- !vaultSwapRequest.commissionBps || vaultSwapRequest.brokerAccount || this.shouldTakeCommission(),
1383
- "Broker commission is supported only when setting a broker account"
1384
- );
1385
- assert(
1386
- !vaultSwapRequest.affiliates?.length || vaultSwapRequest.brokerAccount,
1387
- "Affiliate brokers are supported only when setting a broker account"
1334
+ const body = await encodeVaultSwapData(
1335
+ this.options.backendUrl,
1336
+ brokerAccount ? { ...vaultSwapRequest, brokerAccount, commissionBps: brokerCommissionBps ?? 0 } : { ...vaultSwapRequest, commissionBps: await this.getQuotedBrokerCommissionBps() }
1388
1337
  );
1389
- const res = await this.apiClient.encodeVaultSwapData({ body: vaultSwapRequest });
1390
- if (res.status !== 200) {
1391
- throw new Error("Failed to encode vault swap data", { cause: res });
1392
- }
1393
- switch (res.body.chain) {
1338
+ switch (body.chain) {
1394
1339
  case "Arbitrum":
1395
1340
  case "Ethereum":
1396
1341
  case "Tron":
1397
1342
  case "Bsc":
1398
- return { ...res.body, value: BigInt(res.body.value) };
1343
+ return { ...body, value: BigInt(body.value) };
1399
1344
  default:
1400
- return res.body;
1345
+ return body;
1401
1346
  }
1402
1347
  }
1403
1348
  async encodeCfParameters({
@@ -1410,6 +1355,7 @@ var SwapSDK = class {
1410
1355
  brokerAccount,
1411
1356
  brokerCommissionBps
1412
1357
  }) {
1358
+ const broker = this.resolveEncodingBroker(brokerAccount, { brokerCommissionBps, affiliates });
1413
1359
  await this.validateSwapAmount(quote.srcAsset, BigInt(quote.depositAmount));
1414
1360
  assertQuoteValid(quote);
1415
1361
  if (ccmParams) {
@@ -1427,54 +1373,52 @@ var SwapSDK = class {
1427
1373
  maxBoostFeeBps: "maxBoostFeeBps" in quote ? quote.maxBoostFeeBps : void 0,
1428
1374
  fillOrKillParams: parseFoKParams(fillOrKillParams2, quote),
1429
1375
  dcaParams: quote.type === "DCA" ? quote.dcaParams : void 0,
1430
- commissionBps: await this.getCommissionBps(brokerCommissionBps),
1376
+ commissionBps: brokerCommissionBps,
1431
1377
  affiliates
1432
1378
  };
1433
- if (this.options.broker) {
1434
- assert(
1435
- !brokerAccount,
1436
- "Cannot overwrite broker account when initializing the SDK with a brokerUrl"
1437
- );
1438
- return requestCfParametersEncoding(
1439
- requestParams,
1440
- { url: this.options.broker.url },
1441
- this.options.network
1442
- );
1379
+ if (broker && "url" in broker) {
1380
+ return requestCfParametersEncoding(requestParams, broker, this.options.network);
1443
1381
  }
1444
- assert(
1445
- !requestParams.commissionBps || brokerAccount || this.shouldTakeCommission(),
1446
- "Broker commission is supported only when setting a broker account"
1447
- );
1448
- assert(
1449
- !requestParams.affiliates?.length || brokerAccount,
1450
- "Affiliate brokers are supported only when setting a broker account"
1382
+ return encodeCfParameters(
1383
+ this.options.backendUrl,
1384
+ brokerAccount ? { ...requestParams, brokerAccount, commissionBps: brokerCommissionBps ?? 0 } : { ...requestParams, commissionBps: await this.getQuotedBrokerCommissionBps() }
1451
1385
  );
1452
- const res = await this.apiClient.encodeCfParameters({
1453
- body: { ...requestParams, brokerAccount }
1454
- });
1455
- if (res.status !== 200) {
1456
- throw new Error("Failed to encode cf parameters", { cause: res });
1457
- }
1458
- return res.body;
1459
1386
  }
1460
1387
  async checkBoostEnabled() {
1461
- const { assets: assets2 } = await this.cache.read("networkInfo");
1462
- return assets2.find((a) => a.asset === "Btc")?.boostDepositsEnabled ?? true;
1388
+ const { assets } = await this.cache.read("networkInfo");
1389
+ return assets.find((a) => a.asset === "Btc")?.boostDepositsEnabled ?? true;
1463
1390
  }
1464
1391
  async requestAccountCreationDepositAddress(asset2, refundAddress, signatureData, transactionMetadata, boostFeeBps = 0) {
1465
- const res = await this.apiClient.openAccountCreationDepositChannel({
1466
- body: {
1467
- asset: chainflip.internalAssetToRpcAsset[asset2],
1468
- refundAddress,
1469
- signatureData,
1470
- transactionMetadata,
1471
- boostFeeBps
1472
- }
1473
- });
1474
- if (res.status !== 201) {
1475
- throw new Error("Failed to request account creation deposit channel", { cause: res });
1392
+ const broker = this.requireBroker();
1393
+ const rpcAsset = chainflip.internalAssetToRpcAsset[asset2];
1394
+ const request = {
1395
+ asset: rpcAsset,
1396
+ refundAddress,
1397
+ signatureData,
1398
+ transactionMetadata,
1399
+ boostFeeBps
1400
+ };
1401
+ if ("url" in broker) {
1402
+ const result = await requestAccountCreationDepositAddress(
1403
+ request,
1404
+ broker,
1405
+ this.options.network
1406
+ );
1407
+ return {
1408
+ id: `${result.issuedBlock}-${rpcAsset.chain}-${result.channelId}`,
1409
+ depositAddress: result.address,
1410
+ brokerCommissionBps: 0,
1411
+ maxBoostFeeBps: boostFeeBps,
1412
+ issuedBlock: result.issuedBlock,
1413
+ srcChainExpiryBlock: result.depositChainExpiryBlock.toString(),
1414
+ estimatedExpiryTime: await this.estimateExpiryTime(
1415
+ rpcAsset.chain,
1416
+ result.depositChainExpiryBlock
1417
+ ),
1418
+ channelOpeningFee: result.channelOpeningFee.toString()
1419
+ };
1476
1420
  }
1477
- return res.body;
1421
+ return openAccountCreationDepositChannel(this.options.backendUrl, request);
1478
1422
  }
1479
1423
  };
1480
1424
  var arrayToMap = (array) => Object.fromEntries(array.map((item) => [item, item]));
@@ -1488,6 +1432,7 @@ Object.defineProperty(exports, "getChainflipId", {
1488
1432
  get: function () { return chainflip.getInternalAsset; }
1489
1433
  });
1490
1434
  exports.Assets = Assets;
1435
+ exports.BrokerName = BrokerName;
1491
1436
  exports.ChainflipIds = InternalAssets;
1492
1437
  exports.ChainflipNetworks = ChainflipNetworks;
1493
1438
  exports.Chains = Chains;