@chainflip/sdk 1.9.5 → 1.10.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.js CHANGED
@@ -1,20 +1,20 @@
1
- import { getEnvironment, getEvmChainId, getAllBoostPoolsDepth, assert, isNotNullish, ADDRESSES } from './chunk-6IYYRTHK.js';
2
- import { chainflipChains, assetSymbols, isValidAssetAndChain, getInternalAssets, assetConstants, getInternalAsset, internalAssetToRpcAsset, chainflipNetworks, chainflipAssets, readAssetValue } from '@chainflip/utils/chainflip';
1
+ import { assert, getEnvironment, getEvmChainId, getAllBoostPoolsDepth, isNotNullish, ADDRESSES } from './chunk-Q64VYHIA.js';
2
+ import { unreachable } from '@chainflip/utils/assertion';
3
+ import { chainflipChains, assetSymbols, isValidAssetAndChain, getInternalAssets, chainflipNetworks, chainflipAssets, assetConstants, getInternalAsset, internalAssetToRpcAsset, readAssetValue } from '@chainflip/utils/chainflip';
3
4
  export { getInternalAsset as getChainflipId } from '@chainflip/utils/chainflip';
4
- import { createTRPCProxyClient, httpLink } from '@trpc/client';
5
- import superjson from 'superjson';
5
+ import { initContract, initClient } from '@ts-rest/core';
6
+ import z6, { z } from 'zod';
6
7
  import { HttpClient } from '@chainflip/rpc';
7
- import { unreachable } from '@chainflip/utils/assertion';
8
8
  import { bytesToHex } from '@chainflip/utils/bytes';
9
9
  import * as ss58 from '@chainflip/utils/ss58';
10
10
  import { isHex, toUpperCase } from '@chainflip/utils/string';
11
11
  import { priceX128ToPrice } from '@chainflip/utils/tickMath';
12
- import BigNumber2 from 'bignumber.js';
13
- import { z } from 'zod';
12
+ import BigNumber3 from 'bignumber.js';
14
13
  import { isValidSolanaAddress } from '@chainflip/solana';
15
14
  import { hexEncodeNumber } from '@chainflip/utils/number';
16
15
  import * as bitcoin from '@chainflip/bitcoin';
17
16
  import * as ethers from 'ethers';
17
+ import { CHAINFLIP_BLOCK_TIME_SECONDS } from '@chainflip/utils/consts';
18
18
  import axios from 'axios';
19
19
 
20
20
  // ../shared/src/strings.ts
@@ -112,14 +112,14 @@ z.object({
112
112
  });
113
113
  hadError = true;
114
114
  }
115
- if (args.isOnChain !== void 0 && args.isVaultSwap !== void 0) {
115
+ if (args.isOnChain && args.isVaultSwap) {
116
116
  ctx.addIssue({
117
117
  message: "isOnChain and isVaultSwap cannot be set at the same time",
118
118
  code: z.ZodIssueCode.custom
119
119
  });
120
120
  hadError = true;
121
121
  }
122
- if (args.isOnChain !== void 0 && args.brokerCommissionBps !== void 0 && args.brokerCommissionBps > 0) {
122
+ if (args.isOnChain && args.brokerCommissionBps !== void 0 && args.brokerCommissionBps > 0) {
123
123
  ctx.addIssue({
124
124
  message: "isOnChain cannot be set with a non-zero broker commission",
125
125
  code: z.ZodIssueCode.custom
@@ -145,12 +145,12 @@ var ccmParamsSchema = z.object({
145
145
  message: hexStringWithMaxByteSize(15e3),
146
146
  // https://github.com/chainflip-io/chainflip-backend/blob/415aa9e20ec4046c68892cd34798e5d831c5b83f/state-chain/chains/src/lib.rs#L710
147
147
  ccmAdditionalData: hexStringWithMaxByteSize(3e3).optional(),
148
- /** @deprecated DEPRECATED(1.8) pass additionalData instead */
148
+ /** @deprecated DEPRECATED(1.10) pass additionalData instead */
149
149
  cfParameters: hexStringWithMaxByteSize(3e3).optional()
150
150
  }).transform(({ gasBudget, message, ccmAdditionalData, cfParameters }) => ({
151
151
  gasBudget,
152
152
  message,
153
- ccmAdditionalData: ccmAdditionalData ?? cfParameters
153
+ ccmAdditionalData: ccmAdditionalData ?? cfParameters ?? "0x"
154
154
  }));
155
155
  var affiliateBroker = z.object({
156
156
  account: chainflipAddress,
@@ -160,7 +160,7 @@ var dcaParams = z.object({
160
160
  numberOfChunks: z.number(),
161
161
  chunkIntervalBlocks: z.number()
162
162
  });
163
- z.object({
163
+ var fillOrKillParams = z.object({
164
164
  retryDurationBlocks: z.number(),
165
165
  refundAddress: z.string(),
166
166
  minPriceX128: numericString
@@ -244,7 +244,7 @@ var transformedCcmParamsSchema = ccmParamsSchema.transform(
244
244
  message,
245
245
  gas_budget: gasBudget,
246
246
  ccm_additional_data: ccmAdditionalData,
247
- /** @deprecated DEPRECATED(1.8) we still need to pass cf_parameters until 1.8 is deployed to all networks */
247
+ /** @deprecated DEPRECATED(1.10) we still need to pass cf_parameters until 1.8 is deployed to all networks */
248
248
  cf_parameters: ccmAdditionalData
249
249
  })
250
250
  );
@@ -273,7 +273,7 @@ var getDepositAddressRequestSchema = (network) => z.object({
273
273
  });
274
274
  }
275
275
  });
276
- var getParameterEncodingRequestSchema = (network) => z.object({
276
+ var getVaultSwapParameterEncodingRequestSchema = (network) => z.object({
277
277
  srcAsset: assetAndChain,
278
278
  srcAddress: z.string().optional(),
279
279
  destAsset: assetAndChain,
@@ -311,7 +311,7 @@ var getParameterEncodingRequestSchema = (network) => z.object({
311
311
  }).transform((data) => {
312
312
  let extraParams;
313
313
  if (data.srcAsset.chain === "Bitcoin") {
314
- const minOutputAmount = BigNumber2(data.amount.toString()).multipliedBy(priceX128ToPrice(data.fillOrKillParams.min_price)).toFixed(0);
314
+ const minOutputAmount = BigNumber3(data.amount.toString()).multipliedBy(priceX128ToPrice(data.fillOrKillParams.min_price)).toFixed(0);
315
315
  extraParams = {
316
316
  chain: "Bitcoin",
317
317
  min_output_amount: `0x${BigInt(minOutputAmount).toString(16)}`,
@@ -377,7 +377,7 @@ async function requestSwapDepositAddress(request, opts, chainflipNetwork) {
377
377
  }
378
378
  async function requestSwapParameterEncoding(request, opts, chainflipNetwork) {
379
379
  const client = new HttpClient(opts.url);
380
- const params = getParameterEncodingRequestSchema(chainflipNetwork).parse(request);
380
+ const params = getVaultSwapParameterEncodingRequestSchema(chainflipNetwork).parse(request);
381
381
  const response = await client.sendRequest(
382
382
  "broker_request_swap_parameter_encoding",
383
383
  params.srcAsset,
@@ -392,6 +392,283 @@ async function requestSwapParameterEncoding(request, opts, chainflipNetwork) {
392
392
  );
393
393
  return transformKeysToCamelCase(response);
394
394
  }
395
+ var cfParameterEncodingRequestSchema = z.object({
396
+ srcAsset: assetAndChain,
397
+ srcAddress: z.string().optional(),
398
+ destAsset: assetAndChain,
399
+ destAddress: z.string(),
400
+ amount: unsignedInteger,
401
+ commissionBps: z.number().optional().default(0),
402
+ ccmParams: transformedCcmParamsSchema.optional(),
403
+ maxBoostFeeBps: z.number().optional(),
404
+ affiliates: z.array(affiliateBroker).optional(),
405
+ fillOrKillParams: transformedFokSchema,
406
+ dcaParams: transformedDcaParamsSchema.optional(),
407
+ network: z.enum(chainflipNetworks)
408
+ }).superRefine(({ network, ...val }, ctx) => {
409
+ if (val.srcAddress && !validateAddress(val.srcAsset.chain, val.srcAddress, network)) {
410
+ ctx.addIssue({
411
+ message: `Address "${val.srcAddress}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
412
+ code: z.ZodIssueCode.custom
413
+ });
414
+ }
415
+ if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
416
+ ctx.addIssue({
417
+ message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
418
+ code: z.ZodIssueCode.custom
419
+ });
420
+ }
421
+ if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refund_address, network)) {
422
+ ctx.addIssue({
423
+ message: `Address "${val.fillOrKillParams.refund_address}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
424
+ code: z.ZodIssueCode.custom
425
+ });
426
+ }
427
+ }).transform(({ network, ...rest }) => rest);
428
+ async function requestCfParametersEncoding(request, opts) {
429
+ const client = new HttpClient(opts.url);
430
+ const params = cfParameterEncodingRequestSchema.parse(request);
431
+ const response = await client.sendRequest(
432
+ "broker_encode_cf_parameters",
433
+ params.srcAsset,
434
+ params.destAsset,
435
+ params.destAddress,
436
+ params.commissionBps,
437
+ params.fillOrKillParams,
438
+ params.ccmParams,
439
+ params.maxBoostFeeBps,
440
+ params.affiliates,
441
+ params.dcaParams
442
+ );
443
+ return response;
444
+ }
445
+
446
+ // ../shared/src/api/encodeCfParameters.ts
447
+ var CfParameterEncodingRequestWithBroker = cfParameterEncodingRequestSchema.and(
448
+ z.object({
449
+ brokerAccount: chainflipAddress.optional()
450
+ })
451
+ );
452
+ var TransformedCcmParams = ccmParamsSchema.transform(
453
+ ({ message, gasBudget, ccmAdditionalData }) => ({
454
+ message,
455
+ gas_budget: gasBudget,
456
+ ccm_additional_data: ccmAdditionalData,
457
+ /** @deprecated DEPRECATED(1.10) we still need to pass cf_parameters until 1.8 is deployed to all networks */
458
+ cf_parameters: ccmAdditionalData
459
+ })
460
+ );
461
+ var FillOrKillParams = fillOrKillParams.transform(
462
+ ({ retryDurationBlocks, refundAddress, minPriceX128 }) => ({
463
+ retry_duration: retryDurationBlocks,
464
+ refund_address: refundAddress,
465
+ min_price: `0x${BigInt(minPriceX128).toString(16)}`
466
+ })
467
+ );
468
+ var TransformedDcaParams = dcaParams.transform(
469
+ ({ numberOfChunks, chunkIntervalBlocks }) => ({
470
+ number_of_chunks: numberOfChunks,
471
+ chunk_interval: chunkIntervalBlocks
472
+ })
473
+ );
474
+ var EncodeVaultSwapBody = z.object({
475
+ srcAsset: assetAndChain,
476
+ srcAddress: z.string().optional(),
477
+ destAsset: assetAndChain,
478
+ destAddress: z.string(),
479
+ amount: unsignedInteger,
480
+ commissionBps: z.number().optional().default(0),
481
+ ccmParams: TransformedCcmParams.optional(),
482
+ maxBoostFeeBps: z.number().optional(),
483
+ affiliates: z.array(affiliateBroker).optional(),
484
+ fillOrKillParams: FillOrKillParams,
485
+ dcaParams: TransformedDcaParams.optional(),
486
+ extraParams: z.object({ seed: hexString.optional() }).optional(),
487
+ network: z.enum(chainflipNetworks)
488
+ }).superRefine(({ network, ...val }, ctx) => {
489
+ if (val.srcAddress && !validateAddress(val.srcAsset.chain, val.srcAddress, network)) {
490
+ ctx.addIssue({
491
+ message: `Address "${val.srcAddress}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
492
+ code: z.ZodIssueCode.custom
493
+ });
494
+ }
495
+ if (!validateAddress(val.destAsset.chain, val.destAddress, network)) {
496
+ ctx.addIssue({
497
+ message: `Address "${val.destAddress}" is not a valid "${val.destAsset.chain}" address for "${network}"`,
498
+ code: z.ZodIssueCode.custom
499
+ });
500
+ }
501
+ if (!validateAddress(val.srcAsset.chain, val.fillOrKillParams.refund_address, network)) {
502
+ ctx.addIssue({
503
+ message: `Address "${val.fillOrKillParams.refund_address}" is not a valid "${val.srcAsset.chain}" address for "${network}"`,
504
+ code: z.ZodIssueCode.custom
505
+ });
506
+ }
507
+ if (val.extraParams?.seed && val.extraParams.seed.length !== 66) {
508
+ ctx.addIssue({ message: "Seed must be 32 bytes", code: z.ZodIssueCode.custom });
509
+ }
510
+ }).transform(({ network, ...data }) => {
511
+ let extraParams;
512
+ if (data.srcAsset.chain === "Bitcoin") {
513
+ const minOutputAmount = BigNumber(data.amount.toString()).multipliedBy(priceX128ToPrice(data.fillOrKillParams.min_price)).toFixed(0);
514
+ extraParams = {
515
+ chain: "Bitcoin",
516
+ min_output_amount: `0x${BigInt(minOutputAmount).toString(16)}`,
517
+ retry_duration: data.fillOrKillParams.retry_duration
518
+ };
519
+ } else if (data.srcAsset.chain === "Ethereum" || data.srcAsset.chain === "Arbitrum") {
520
+ extraParams = {
521
+ chain: data.srcAsset.chain,
522
+ input_amount: `0x${data.amount.toString(16)}`,
523
+ refund_parameters: data.fillOrKillParams
524
+ };
525
+ } else if (data.srcAsset.chain === "Solana") {
526
+ assert(data.srcAddress, "srcAddress is required for Solana");
527
+ extraParams = {
528
+ chain: "Solana",
529
+ from: data.srcAddress,
530
+ seed: data.extraParams?.seed ?? bytesToHex(crypto.getRandomValues(new Uint8Array(32))),
531
+ input_amount: `0x${data.amount.toString(16)}`,
532
+ refund_parameters: data.fillOrKillParams
533
+ };
534
+ } else {
535
+ throw new Error(`parameter encoding is not supported for ${data.srcAsset.chain}`);
536
+ }
537
+ return { ...data, extraParams };
538
+ });
539
+ var EncodedVaultSwapData = z.discriminatedUnion("chain", [
540
+ z.object({
541
+ chain: z.literal("Bitcoin"),
542
+ nulldataPayload: hexString,
543
+ depositAddress: z.string()
544
+ }),
545
+ z.object({
546
+ chain: z.enum(["Ethereum", "Arbitrum"]),
547
+ value: z.string(),
548
+ to: hexString,
549
+ calldata: hexString,
550
+ sourceTokenAddress: hexString.optional()
551
+ }),
552
+ z.object({
553
+ chain: z.literal("Solana"),
554
+ programId: z.string(),
555
+ data: hexString,
556
+ accounts: z.array(
557
+ z.object({
558
+ pubkey: z.string(),
559
+ isSigner: z.boolean(),
560
+ isWritable: z.boolean()
561
+ })
562
+ )
563
+ })
564
+ ]);
565
+ var NetworkInfo = z6.object({
566
+ assets: z6.array(
567
+ z6.object({
568
+ asset: z6.enum(chainflipAssets),
569
+ vaultSwapDepositsEnabled: z6.boolean(),
570
+ depositChannelDepositsEnabled: z6.boolean(),
571
+ depositChannelCreationEnabled: z6.boolean(),
572
+ egressEnabled: z6.boolean(),
573
+ boostDepositsEnabled: z6.boolean()
574
+ })
575
+ ),
576
+ cfBrokerCommissionBps: z6.number()
577
+ });
578
+ var ChainflipAsset = z.enum(chainflipAssets);
579
+ var NetworkStatus = z.object({
580
+ assets: z.object({
581
+ deposit: z.array(ChainflipAsset),
582
+ destination: z.array(ChainflipAsset),
583
+ all: z.array(ChainflipAsset)
584
+ }),
585
+ boostDepositsEnabled: z.boolean(),
586
+ cfBrokerCommissionBps: z.number()
587
+ });
588
+ var OpenSwapDepositChannelBody = z.object({
589
+ srcAsset: asset,
590
+ destAsset: asset,
591
+ srcChain: chain,
592
+ destChain: chain,
593
+ destAddress: z.string(),
594
+ amount: numericString,
595
+ ccmParams: ccmParamsSchema.optional(),
596
+ maxBoostFeeBps: z.number().optional(),
597
+ srcAddress: z.string().optional(),
598
+ fillOrKillParams,
599
+ dcaParams: dcaParams.optional(),
600
+ quote: z.object({
601
+ intermediateAmount: z.string().optional(),
602
+ egressAmount: z.string(),
603
+ estimatedPrice: z.string(),
604
+ recommendedSlippageTolerancePercent: z.number().optional()
605
+ }).optional(),
606
+ takeCommission: z.boolean().optional()
607
+ }).transform(({ amount, ...rest }) => ({
608
+ ...rest,
609
+ expectedDepositAmount: amount
610
+ }));
611
+ var DepositChannelInfo = z.object({
612
+ id: z.string(),
613
+ depositAddress: z.string(),
614
+ brokerCommissionBps: z.number(),
615
+ maxBoostFeeBps: z.number(),
616
+ issuedBlock: z.number(),
617
+ srcChainExpiryBlock: z.string(),
618
+ estimatedExpiryTime: z.number().optional(),
619
+ channelOpeningFee: z.string()
620
+ });
621
+
622
+ // ../shared/src/api/contract.ts
623
+ var c = initContract();
624
+ var apiContract = c.router(
625
+ {
626
+ /** @deprecated DEPRECATED(1.9): using `networkInfo` now */
627
+ networkStatus: {
628
+ method: "GET",
629
+ path: "/networkStatus",
630
+ responses: {
631
+ 200: NetworkStatus
632
+ },
633
+ summary: "Get information about the Chainflip network"
634
+ },
635
+ networkInfo: {
636
+ method: "GET",
637
+ path: "/networkInfo",
638
+ responses: {
639
+ 200: NetworkInfo
640
+ },
641
+ summary: "Get information about the Chainflip network"
642
+ },
643
+ encodeCfParameters: {
644
+ method: "POST",
645
+ path: "/encodeCfParameters",
646
+ body: CfParameterEncodingRequestWithBroker,
647
+ responses: {
648
+ 200: hexString
649
+ }
650
+ },
651
+ encodeVaultSwapData: {
652
+ method: "POST",
653
+ path: "/encodeVaultSwapData",
654
+ body: EncodeVaultSwapBody,
655
+ responses: {
656
+ 200: EncodedVaultSwapData
657
+ }
658
+ },
659
+ openSwapDepositChannel: {
660
+ method: "POST",
661
+ path: "/openSwapDepositChannel",
662
+ body: OpenSwapDepositChannelBody,
663
+ responses: {
664
+ 201: DepositChannelInfo
665
+ }
666
+ }
667
+ },
668
+ {
669
+ pathPrefix: "/api"
670
+ }
671
+ );
395
672
 
396
673
  // ../shared/src/dataStructures.ts
397
674
  var MultiCache = class {
@@ -415,7 +692,8 @@ var MultiCache = class {
415
692
  return cached.value;
416
693
  }
417
694
  };
418
- var getPriceX128FromPrice = (price, srcAsset, destAsset) => BigNumber2(price).multipliedBy(new BigNumber2(2).pow(128)).shiftedBy(assetConstants[destAsset].decimals - assetConstants[srcAsset].decimals).toFixed(0);
695
+ var getPriceX128FromPrice = (price, srcAsset, destAsset) => BigNumber3(price).multipliedBy(new BigNumber3(2).pow(128)).shiftedBy(assetConstants[destAsset].decimals - assetConstants[srcAsset].decimals).toFixed(0);
696
+ var blocksPerMinute = 60 / CHAINFLIP_BLOCK_TIME_SECONDS;
419
697
  function parseFoKParams(params, quote) {
420
698
  const srcAsset = getInternalAsset(quote.srcAsset);
421
699
  const destAsset = getInternalAsset(quote.destAsset);
@@ -427,24 +705,25 @@ function parseFoKParams(params, quote) {
427
705
  );
428
706
  minPrice = params.minPrice;
429
707
  } else if ("slippageTolerancePercent" in params) {
430
- const tolerance = new BigNumber2(params.slippageTolerancePercent);
708
+ const tolerance = new BigNumber3(params.slippageTolerancePercent);
431
709
  assert(!tolerance.isNaN(), "Invalid slippage tolerance");
432
710
  assert(
433
711
  tolerance.gte(0) && tolerance.lte(100),
434
712
  "Slippage tolerance must be between 0 and 100 inclusive",
435
713
  RangeError
436
714
  );
437
- const estimatedPrice = new BigNumber2(quote.estimatedPrice);
715
+ const estimatedPrice = new BigNumber3(quote.estimatedPrice);
438
716
  assert(!estimatedPrice.isNaN(), "Invalid estimated price");
439
- minPrice = estimatedPrice.times(new BigNumber2(100).minus(tolerance).dividedBy(100)).toFixed(assetConstants[destAsset].decimals);
717
+ minPrice = estimatedPrice.times(new BigNumber3(100).minus(tolerance).dividedBy(100)).toFixed(assetConstants[destAsset].decimals);
440
718
  } else {
441
719
  throw new Error("Either minPrice or slippageTolerancePercent must be provided");
442
720
  }
443
- return {
444
- refundAddress: params.refundAddress,
445
- retryDurationBlocks: params.retryDurationBlocks,
721
+ const retryDurationBlocks = "retryDurationBlocks" in params ? params.retryDurationBlocks : Math.max(Math.ceil(params.retryDurationMinutes * blocksPerMinute), 0);
722
+ const parsed = {
723
+ retryDurationBlocks,
446
724
  minPriceX128: getPriceX128FromPrice(minPrice, srcAsset, destAsset)
447
725
  };
726
+ return "refundAddress" in params ? { ...parsed, refundAddress: params.refundAddress } : parsed;
448
727
  }
449
728
  var isTestnet = (network) => network !== "mainnet";
450
729
  var MAX_SWAP_AMOUNT = 2n ** 128n - 1n;
@@ -524,7 +803,7 @@ var getChainData = (chain2, network, env) => ({
524
803
 
525
804
  // package.json
526
805
  var package_default = {
527
- version: "1.9.5"};
806
+ version: "1.10.1"};
528
807
 
529
808
  // src/swap/consts.ts
530
809
  var CF_SDK_VERSION_HEADERS = { "X-Chainflip-Sdk-Version": package_default.version };
@@ -586,7 +865,7 @@ var assertQuoteValid = (quote) => {
586
865
  var SwapSDK = class {
587
866
  options;
588
867
  rpcConfig;
589
- trpc;
868
+ apiClient;
590
869
  cache;
591
870
  dcaEnabled = false;
592
871
  constructor(options = {}) {
@@ -597,14 +876,11 @@ var SwapSDK = class {
597
876
  backendUrl: options.backendUrl ?? BACKEND_SERVICE_URLS[network]
598
877
  };
599
878
  this.rpcConfig = options.rpcUrl ? { rpcUrl: options.rpcUrl } : { network };
600
- this.trpc = createTRPCProxyClient({
601
- transformer: superjson,
602
- links: [
603
- httpLink({
604
- url: new URL("/trpc", this.options.backendUrl),
605
- headers: CF_SDK_VERSION_HEADERS
606
- })
607
- ]
879
+ this.apiClient = initClient(apiContract, {
880
+ // remove trailing slashes. this bug has been fixed in `@ts-rest/core`
881
+ // but it hasn't been released yet
882
+ baseUrl: this.options.backendUrl.replace(/\/+$/, ""),
883
+ baseHeaders: CF_SDK_VERSION_HEADERS
608
884
  });
609
885
  this.dcaEnabled = options.enabledFeatures?.dca ?? false;
610
886
  this.cache = new MultiCache({
@@ -612,8 +888,12 @@ var SwapSDK = class {
612
888
  fetch: () => getEnvironment(this.rpcConfig),
613
889
  ttl: 6e4
614
890
  },
615
- networkStatus: {
616
- fetch: () => this.trpc.networkStatus.query(),
891
+ networkInfo: {
892
+ fetch: async () => {
893
+ const res = await this.apiClient.networkInfo();
894
+ assert(res.status === 200, "Failed to fetch network info");
895
+ return res.body;
896
+ },
617
897
  ttl: 6e4
618
898
  }
619
899
  });
@@ -634,8 +914,23 @@ var SwapSDK = class {
634
914
  return this.cache.read("environment");
635
915
  }
636
916
  async getSupportedAssets(type) {
637
- const assets = await this.cache.read("networkStatus");
638
- return assets.assets[type];
917
+ const assets = await this.cache.read("networkInfo");
918
+ return assets.assets.filter((a) => {
919
+ switch (type) {
920
+ case "all":
921
+ return true;
922
+ case "deposit":
923
+ return a.depositChannelCreationEnabled && a.depositChannelDepositsEnabled && a.vaultSwapDepositsEnabled;
924
+ case "destination":
925
+ return a.egressEnabled;
926
+ case "depositChannel":
927
+ return a.depositChannelCreationEnabled && a.depositChannelDepositsEnabled;
928
+ case "vaultSwap":
929
+ return a.vaultSwapDepositsEnabled;
930
+ default:
931
+ return unreachable(type, "unexpected type");
932
+ }
933
+ }).map((a) => a.asset);
639
934
  }
640
935
  async getBoostPoolsDepth() {
641
936
  return getAllBoostPoolsDepth(this.rpcConfig);
@@ -654,7 +949,7 @@ var SwapSDK = class {
654
949
  }
655
950
  async getCommissionBps(brokerCommissionBps) {
656
951
  if (this.shouldTakeCommission()) {
657
- return (await this.cache.read("networkStatus")).cfBrokerCommissionBps;
952
+ return (await this.cache.read("networkInfo")).cfBrokerCommissionBps;
658
953
  }
659
954
  return brokerCommissionBps ?? this.options.broker?.commissionBps ?? 0;
660
955
  }
@@ -782,11 +1077,15 @@ var SwapSDK = class {
782
1077
  !affiliates?.length,
783
1078
  "Affiliate brokers are supported only when initializing the SDK with a brokerUrl"
784
1079
  );
785
- response = await this.trpc.openSwapDepositChannel.mutate({
786
- ...depositAddressRequest,
787
- quote,
788
- takeCommission: this.shouldTakeCommission()
1080
+ const res = await this.apiClient.openSwapDepositChannel({
1081
+ body: {
1082
+ ...depositAddressRequest,
1083
+ quote,
1084
+ takeCommission: this.shouldTakeCommission()
1085
+ }
789
1086
  });
1087
+ assert(res.status === 201, "Failed to open swap deposit channel");
1088
+ response = res.body;
790
1089
  }
791
1090
  return {
792
1091
  ...depositAddressRequest,
@@ -795,9 +1094,9 @@ var SwapSDK = class {
795
1094
  brokerCommissionBps: response.brokerCommissionBps,
796
1095
  affiliateBrokers: affiliates ?? [],
797
1096
  maxBoostFeeBps: Number(response.maxBoostFeeBps) || 0,
798
- depositChannelExpiryBlock: response.srcChainExpiryBlock,
1097
+ depositChannelExpiryBlock: BigInt(response.srcChainExpiryBlock),
799
1098
  estimatedDepositChannelExpiryTime: response.estimatedExpiryTime,
800
- channelOpeningFee: response.channelOpeningFee,
1099
+ channelOpeningFee: BigInt(response.channelOpeningFee),
801
1100
  fillOrKillParams: inputFoKParams
802
1101
  };
803
1102
  }
@@ -855,7 +1154,73 @@ var SwapSDK = class {
855
1154
  !vaultSwapRequest.affiliates?.length || vaultSwapRequest.brokerAccount,
856
1155
  "Affiliate brokers are supported only when setting a broker account"
857
1156
  );
858
- return this.trpc.encodeVaultSwapData.mutate(vaultSwapRequest);
1157
+ const res = await this.apiClient.encodeVaultSwapData({
1158
+ body: { ...vaultSwapRequest, network: this.options.network }
1159
+ });
1160
+ if (res.status !== 200) {
1161
+ throw new Error("Failed to encode vault swap data", { cause: res });
1162
+ }
1163
+ switch (res.body.chain) {
1164
+ case "Arbitrum":
1165
+ case "Ethereum":
1166
+ return { ...res.body, value: BigInt(res.body.value) };
1167
+ default:
1168
+ return res.body;
1169
+ }
1170
+ }
1171
+ async encodeCfParameters({
1172
+ quote,
1173
+ srcAddress,
1174
+ destAddress,
1175
+ fillOrKillParams: fillOrKillParams2,
1176
+ affiliateBrokers: affiliates,
1177
+ ccmParams,
1178
+ brokerAccount,
1179
+ brokerCommissionBps
1180
+ }) {
1181
+ await this.validateSwapAmount(quote.srcAsset, BigInt(quote.depositAmount));
1182
+ assertQuoteValid(quote);
1183
+ if (ccmParams) {
1184
+ assert(quote.ccmParams, "Cannot encode CCM swap for quote without CCM params");
1185
+ } else {
1186
+ assert(!quote.ccmParams, "Cannot encode regular swap for quote with CCM params");
1187
+ }
1188
+ const requestParams = {
1189
+ srcAsset: quote.srcAsset,
1190
+ destAsset: quote.destAsset,
1191
+ srcAddress,
1192
+ destAddress,
1193
+ amount: quote.depositAmount,
1194
+ ccmParams,
1195
+ maxBoostFeeBps: "maxBoostFeeBps" in quote ? quote.maxBoostFeeBps : void 0,
1196
+ fillOrKillParams: parseFoKParams(fillOrKillParams2, quote),
1197
+ dcaParams: quote.type === "DCA" ? quote.dcaParams : void 0,
1198
+ commissionBps: await this.getCommissionBps(brokerCommissionBps),
1199
+ affiliates,
1200
+ network: this.options.network
1201
+ };
1202
+ if (this.options.broker) {
1203
+ assert(
1204
+ !brokerAccount,
1205
+ "Cannot overwrite broker account when initializing the SDK with a brokerUrl"
1206
+ );
1207
+ return requestCfParametersEncoding(requestParams, { url: this.options.broker.url });
1208
+ }
1209
+ assert(
1210
+ !requestParams.commissionBps || brokerAccount || this.shouldTakeCommission(),
1211
+ "Broker commission is supported only when setting a broker account"
1212
+ );
1213
+ assert(
1214
+ !requestParams.affiliates?.length || brokerAccount,
1215
+ "Affiliate brokers are supported only when setting a broker account"
1216
+ );
1217
+ const res = await this.apiClient.encodeCfParameters({
1218
+ body: { ...requestParams, brokerAccount }
1219
+ });
1220
+ if (res.status !== 200) {
1221
+ throw new Error("Failed to encode cf parameters", { cause: res });
1222
+ }
1223
+ return res.body;
859
1224
  }
860
1225
  // eslint-disable-next-line class-methods-use-this
861
1226
  getOnChainSwapExtrinsicArgs({
@@ -877,8 +1242,8 @@ var SwapSDK = class {
877
1242
  ];
878
1243
  }
879
1244
  async checkBoostEnabled() {
880
- const { boostDepositsEnabled } = await this.cache.read("networkStatus");
881
- return boostDepositsEnabled;
1245
+ const { assets } = await this.cache.read("networkInfo");
1246
+ return assets.find((a) => a.asset === "Btc")?.boostDepositsEnabled ?? true;
882
1247
  }
883
1248
  };
884
1249
  var arrayToMap = (array) => Object.fromEntries(array.map((item) => [item, item]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chainflip/sdk",
3
- "version": "1.9.5",
3
+ "version": "1.10.1",
4
4
  "description": "",
5
5
  "exports": {
6
6
  "./swap": {
@@ -52,16 +52,15 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "@chainflip/bitcoin": "^1.2.5",
56
- "@chainflip/rpc": "~1.9.7",
55
+ "@chainflip/bitcoin": "^1.2.6",
56
+ "@chainflip/rpc": "~1.11.0-beta.3",
57
57
  "@chainflip/solana": "^2.1.9",
58
- "@chainflip/utils": "^0.8.7",
59
- "@trpc/client": "^10.45.2",
60
- "axios": "^1.9.0",
58
+ "@chainflip/utils": "^0.8.11",
59
+ "@ts-rest/core": "^3.52.1",
60
+ "axios": "^1.10.0",
61
61
  "bignumber.js": "^9.3.0",
62
- "ethers": "^6.14.1",
63
- "superjson": "^1.13.3",
64
- "zod": "^3.25.7"
62
+ "ethers": "^6.14.4",
63
+ "zod": "^3.25.76"
65
64
  },
66
65
  "devDependencies": {
67
66
  "@trpc/server": "^10.45.2",
File without changes