@tradeport/sui-trading-sdk 0.4.64 → 0.4.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -142,6 +142,16 @@ var TRADEPORT_NFT_STRATEGY_PACKAGE_ID = "0xb7386fc8c6e64ea2b0079e293592b57e98498
142
142
  var TRADEPORT_NFT_STRATEGY_MANAGER_ID = "0xfb58ee62b3a62a8150f871da950dfdf923cd0d97b153caf99b5219cd4ddda5bd";
143
143
  var TRADEPORT_POOL_REGISTRY_ID = "0xcd0a614c4cbbf173f59dee2602c43a1717f283215ed7a0bb1d55d786af16fbcd";
144
144
  var TRADEPORT_POOL_VERSIONED_ID = "0x0309b66202e9aaf470081fffee7ffc0fbd50e3b7400d4f56fd06502e4dbbd676";
145
+ var DexConstants = {
146
+ commission: "0x24f5f2258ef80c0a3243088199faeb95ad50516ca1517dbd93be398d759057bb",
147
+ commissionManager: "0xd19a03d4ec3d12b0ce407b54eb676cc0f8e1403621deda77d9677bfcb9d738c1",
148
+ poolsToExclude: [
149
+ "0x3addbbc82866c0bbd93e51b6e2d75c0a4faaf270cc0e281d8f4de5df48bebfa4",
150
+ "0x19d614f421046cae90f5a3a976816063478f648087a12adc74e90ebd54dfaf19",
151
+ "0x514c74e28a9720366abc4a65a5688f47c72e784dbf035844d3f59059bfaed056",
152
+ "0x0854de4e9d64716b757b2f6f22258467f59cc1b4bc0cc64c70086549faaddedf"
153
+ ]
154
+ };
145
155
  var USDC_COIN_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
146
156
  var COLLECTION_IDS_WITH_ZERO_COMMISSION = [
147
157
  ""
@@ -3572,6 +3582,16 @@ var getCollectionChainState = async (collectionId) => {
3572
3582
  });
3573
3583
  return res?.collections?.[0]?.chain_state;
3574
3584
  };
3585
+ var getCollectionChainStateByFtType = async (ftType) => {
3586
+ const res = await gqlChainRequest({
3587
+ chain: "sui",
3588
+ query: fetchCollectionChainStateByFtType,
3589
+ variables: {
3590
+ ftType
3591
+ }
3592
+ });
3593
+ return res?.collections_by_ft_type?.[0]?.chain_state;
3594
+ };
3575
3595
 
3576
3596
  // src/methods/applyFtStrategy/applyFtStrategy.ts
3577
3597
  async function applyFtStrategy({
@@ -3606,105 +3626,12 @@ async function applyFtStrategy({
3606
3626
  return tx;
3607
3627
  }
3608
3628
 
3609
- // src/methods/applyNftStrategy/applyNftStrategy.ts
3610
- import { Transaction as Transaction5 } from "@mysten/sui/transactions";
3611
-
3612
- // src/graphql/queries/fetchCollectionFloorListingForMarket.ts
3613
- import { gql as gql13 } from "graphql-request";
3614
- var fetchCollectionFloorListingsForMarket = gql13`
3615
- query fetchCollectionFloorListingsForMarket(
3616
- $collectionId: uuid!
3617
- $marketAddress: String!
3618
- $totalPrice: numeric
3619
- ) {
3620
- listings(
3621
- where: {
3622
- collection_id: { _eq: $collectionId }
3623
- listed: { _eq: true }
3624
- market_name: { _eq: "tradeport" }
3625
- seller: { _neq: $marketAddress }
3626
- nonce: { _like: "1::0x%" }
3627
- price: { _lte: $totalPrice }
3628
- }
3629
- order_by: [{ price: asc_nulls_last }, { block_height: asc }, { tx_index: asc }]
3630
- ) {
3631
- id
3632
- price
3633
- nft {
3634
- token_id
3635
- delegated_owner
3636
- }
3637
- }
3638
- }
3639
- `;
3640
-
3641
- // src/methods/applyNftStrategy/applyNftStrategy.ts
3642
- async function applyTradeportNftStrategy({
3643
- collectionId,
3644
- strategyFtType,
3645
- tx: existingTx
3646
- }) {
3647
- const tx = existingTx ?? new Transaction5();
3648
- const chainState = await getCollectionChainState(collectionId);
3649
- const nftStrategies = chainState?.nft_strategies ?? {};
3650
- const nftStrategyKeys = Object.keys(nftStrategies);
3651
- if (nftStrategyKeys.length === 0) {
3652
- throw new Error("No NFT strategies found for collection");
3653
- }
3654
- strategyFtType = strategyFtType ?? nftStrategyKeys[0];
3655
- if (!nftStrategyKeys.includes(strategyFtType)) {
3656
- throw new Error(`Specified FT type ${strategyFtType} is not supported for this collection`);
3657
- }
3658
- const transferPolicy = getNativeKioskTransferPolicies(chainState?.transfer_policies ?? [])?.at(0);
3659
- if (!transferPolicy) {
3660
- throw new Error("No transfer policy found for collection");
3661
- }
3662
- const nftType = chainState?.nft_type;
3663
- let suiBalance = BigInt(
3664
- nftStrategies[strategyFtType].sui_balance ?? 0n
3665
- );
3666
- const result = await gqlChainRequest({
3667
- chain: "sui",
3668
- query: fetchCollectionFloorListingsForMarket,
3669
- variables: {
3670
- collectionId,
3671
- marketAddress: TRADEPORT_NFT_STRATEGY_MANAGER_ID,
3672
- totalPrice: suiBalance.toString()
3673
- }
3674
- });
3675
- if ((result?.listings?.length ?? 0) === 0) {
3676
- throw new Error(
3677
- `No floor listing found for collection with price bellow or equal to ${suiBalance} MIST`
3678
- );
3679
- }
3680
- for (const floorListing of result.listings) {
3681
- suiBalance -= BigInt(floorListing.price);
3682
- if (suiBalance < 0n) {
3683
- break;
3684
- }
3685
- tx.moveCall({
3686
- target: `${TRADEPORT_NFT_STRATEGY_PACKAGE_ID}::tradeport_nft_strategy::apply_tradeport_nft_strategy_confirm_request`,
3687
- typeArguments: [nftType, strategyFtType],
3688
- arguments: [
3689
- tx.object(TRADEPORT_NFT_STRATEGY_MANAGER_ID),
3690
- tx.object(nftStrategies[strategyFtType].kiosk_id),
3691
- tx.object(TRADEPORT_LISTINGS_STORE),
3692
- tx.object(TRADEPORT_ORDERBOOK_STORE),
3693
- tx.object(floorListing.nft.delegated_owner),
3694
- tx.object(floorListing.nft.token_id),
3695
- tx.object(transferPolicy.id)
3696
- ]
3697
- });
3698
- }
3699
- return tx;
3700
- }
3701
-
3702
3629
  // src/methods/buyListings/buyListings.ts
3703
3630
  import { Transaction as Transaction7 } from "@mysten/sui/transactions";
3704
3631
 
3705
3632
  // src/graphql/queries/fetchListingsById.ts
3706
- import { gql as gql14 } from "graphql-request";
3707
- var fetchListingsById = gql14`
3633
+ import { gql as gql13 } from "graphql-request";
3634
+ var fetchListingsById = gql13`
3708
3635
  query fetchListingsById($listingIds: [uuid!]) {
3709
3636
  listings(where: { id: { _in: $listingIds } }) {
3710
3637
  id
@@ -3743,6 +3670,29 @@ var addThirdPartyTxFee = async (tx, price) => {
3743
3670
  );
3744
3671
  };
3745
3672
 
3673
+ // src/helpers/deserializeOrCreateTxBlock.ts
3674
+ import { Transaction as Transaction5 } from "@mysten/sui/transactions";
3675
+ var deserializeOrCreateTxBlock = ({
3676
+ existingTx
3677
+ }) => {
3678
+ if (typeof existingTx === "string") {
3679
+ return Transaction5.from(existingTx);
3680
+ }
3681
+ return existingTx ?? new Transaction5();
3682
+ };
3683
+
3684
+ // src/helpers/extractSwapResultCoin.ts
3685
+ var extractSwapResultCoinFromTxBlock = (txBlock) => {
3686
+ if (!txBlock) return void 0;
3687
+ const tx = typeof txBlock === "string" ? JSON.parse(txBlock) : txBlock?.getData();
3688
+ const commands = tx.commands ?? [];
3689
+ const index = commands.findIndex(
3690
+ (cmd) => cmd?.MoveCall?.module === "universal_router" && cmd?.MoveCall?.function === "settle"
3691
+ );
3692
+ if (index === -1) return void 0;
3693
+ return { $kind: "Result", Result: index };
3694
+ };
3695
+
3746
3696
  // src/helpers/kiosk/preProcessSharedBulkBuyingData.ts
3747
3697
  import { bcs as bcs2 } from "@mysten/sui/bcs";
3748
3698
  import { Transaction as Transaction6 } from "@mysten/sui/transactions";
@@ -3848,8 +3798,8 @@ var preProcessSharedBulkBuyingData = async ({
3848
3798
  import { bcs as bcs3 } from "@mysten/sui/bcs";
3849
3799
 
3850
3800
  // src/graphql/queries/fetchCommissionByListingId.ts
3851
- import { gql as gql15 } from "graphql-request";
3852
- var fetchCommissionByNftContractId = gql15`
3801
+ import { gql as gql14 } from "graphql-request";
3802
+ var fetchCommissionByNftContractId = gql14`
3853
3803
  query fetchCommissionByNftContractId($nftContractId: uuid!) {
3854
3804
  commissions(where: { contract_id: { _eq: $nftContractId } }) {
3855
3805
  is_custodial
@@ -4599,7 +4549,8 @@ var buyListings = async ({
4599
4549
  throw new Error("No listings found");
4600
4550
  }
4601
4551
  const listingsForTracking = [];
4602
- const tx = existingTx ?? new Transaction7();
4552
+ const tx = deserializeOrCreateTxBlock({ existingTx });
4553
+ const swapResultCoin = extractSwapResultCoinFromTxBlock(tx);
4603
4554
  const tocenTokenIds = [];
4604
4555
  let tocenNftType = "";
4605
4556
  let tocenTotalPrice = 0;
@@ -4644,7 +4595,7 @@ var buyListings = async ({
4644
4595
  sellerKiosk: listing.nft?.chain_state?.kiosk_id,
4645
4596
  collectionId: listing?.nft?.collection_id,
4646
4597
  nftContractId: listing?.nft?.contract_id,
4647
- coinToSplit,
4598
+ coinToSplit: swapResultCoin ? swapResultCoin : coinToSplit,
4648
4599
  marketFeeDecimalPercent,
4649
4600
  beforeResolveKioskTransferRequest,
4650
4601
  sharedKioskState,
@@ -4693,6 +4644,9 @@ var buyListings = async ({
4693
4644
  });
4694
4645
  }
4695
4646
  sharedKioskState?.kioskTx?.finalize();
4647
+ if (swapResultCoin) {
4648
+ tx.transferObjects([swapResultCoin], walletAddress);
4649
+ }
4696
4650
  if (tocenTokenIds?.length > 0) {
4697
4651
  addTocenBuyTxHandler({
4698
4652
  tx,
@@ -4701,7 +4655,7 @@ var buyListings = async ({
4701
4655
  price: tocenTotalPrice
4702
4656
  });
4703
4657
  }
4704
- return tx;
4658
+ return Transaction7.from(tx);
4705
4659
  };
4706
4660
 
4707
4661
  // src/methods/cancelMultiBid/cancelMultiBid.ts
@@ -4825,8 +4779,8 @@ async function cancelMultiBid({ multiBidId }) {
4825
4779
  import { Transaction as Transaction9 } from "@mysten/sui/transactions";
4826
4780
 
4827
4781
  // src/graphql/queries/fetchAccountKiosks.ts
4828
- import { gql as gql16 } from "graphql-request";
4829
- var fetchAccountKiosks = gql16`
4782
+ import { gql as gql15 } from "graphql-request";
4783
+ var fetchAccountKiosks = gql15`
4830
4784
  query fetchAccountKiosks($accountAddress: String!) {
4831
4785
  kiosks: kiosks_by_owner_address(owner_address: $accountAddress) {
4832
4786
  id
@@ -5295,22 +5249,17 @@ var claimNfts = async ({ nftIds, walletAddress, tx: existingTx }, context, useOl
5295
5249
  return Transaction10.from(tx);
5296
5250
  };
5297
5251
 
5298
- // src/methods/createMultiBid/createMultiBid.ts
5299
- import { Transaction as Transaction12 } from "@mysten/sui/transactions";
5300
-
5301
5252
  // src/methods/updateMultiBid/updateMultiBid.ts
5302
- import { Transaction as Transaction11 } from "@mysten/sui/transactions";
5303
5253
  async function updateMultiBid({
5304
- walletAddress,
5305
5254
  multiBidId,
5306
5255
  name,
5307
5256
  amount,
5308
5257
  amountToWithdraw,
5309
5258
  tx: existingTx,
5310
- multiBidChainId,
5311
- coinToSplit
5312
- }, context) {
5313
- const tx = existingTx ?? new Transaction11();
5259
+ multiBidChainId
5260
+ }) {
5261
+ const tx = deserializeOrCreateTxBlock({ existingTx });
5262
+ const swapResultCoin = extractSwapResultCoinFromTxBlock(tx);
5314
5263
  if (!multiBidChainId) {
5315
5264
  const { chain_id: chainId, cancelled_at } = (await gqlChainRequest({
5316
5265
  chain: "sui",
@@ -5325,7 +5274,7 @@ async function updateMultiBid({
5325
5274
  }
5326
5275
  multiBidChainId = chainId;
5327
5276
  }
5328
- const [coin] = tx.splitCoins(coinToSplit ? coinToSplit : tx.gas, [amount ?? 0n]);
5277
+ const [coin] = tx.splitCoins(swapResultCoin ? swapResultCoin : tx.gas, [amount ?? 0n]);
5329
5278
  tx.moveCall({
5330
5279
  target: `${TRADEPORT_MULTI_BID_PACKAGE}::tradeport_biddings::update_multi_bid`,
5331
5280
  arguments: [
@@ -5346,7 +5295,7 @@ async function createMultiBid({
5346
5295
  amount,
5347
5296
  tx: existingTx
5348
5297
  }) {
5349
- const tx = existingTx ?? new Transaction12();
5298
+ const tx = deserializeOrCreateTxBlock({ existingTx });
5350
5299
  const multiBidChainId = tx.moveCall({
5351
5300
  target: `${TRADEPORT_MULTI_BID_PACKAGE}::tradeport_biddings::create_multi_bid`,
5352
5301
  arguments: [tx.object(TRADEPORT_MULTI_BID_STORE), tx.pure.option("string", name)]
@@ -5364,11 +5313,7 @@ async function createMultiBid({
5364
5313
  }
5365
5314
 
5366
5315
  // src/methods/listNfts/listNfts.ts
5367
- import { Transaction as Transaction13 } from "@mysten/sui/transactions";
5368
-
5369
- // src/helpers/isExpiredListing.ts
5370
- import { normalizeSuiAddress } from "@mysten/sui/utils";
5371
- var isExpiredListing = (listing, walletAddress) => listing.nonce && listing.seller && normalizeSuiAddress(listing.seller) === normalizeSuiAddress(walletAddress);
5316
+ import { Transaction as Transaction12 } from "@mysten/sui/transactions";
5372
5317
 
5373
5318
  // src/helpers/validateMinFloorPrice.ts
5374
5319
  function validateMinFloorPrice({ transferPolicies, listPrice }) {
@@ -5697,16 +5642,328 @@ async function relistNft({
5697
5642
  }
5698
5643
  }
5699
5644
 
5645
+ // src/methods/swapCoins/swapCoins.ts
5646
+ import {
5647
+ AggregatorQuoter,
5648
+ CoinProvider,
5649
+ Protocol,
5650
+ TradeBuilder
5651
+ } from "@flowx-finance/sdk";
5652
+ import { coinWithBalance, Transaction as Transaction11 } from "@mysten/sui/transactions";
5653
+ import { normalizeStructTag as normalizeStructTag2, normalizeSuiAddress, SUI_TYPE_ARG } from "@mysten/sui/utils";
5654
+ import ms from "ms";
5655
+
5656
+ // src/utils/pureValues.ts
5657
+ var toDecimalValue = (value, decimals) => {
5658
+ if (!value || decimals === void 0) return new bigNumberConfig_default(0);
5659
+ return new bigNumberConfig_default(value).div(10 ** decimals);
5660
+ };
5661
+ var toPureValue = (value, decimals) => {
5662
+ if (!value || decimals === void 0) return new bigNumberConfig_default(0);
5663
+ return new bigNumberConfig_default(new bigNumberConfig_default(value).multipliedBy(10 ** decimals).toFixed(0));
5664
+ };
5665
+
5666
+ // src/methods/swapCoins/swapCoins.ts
5667
+ async function swapCoins({
5668
+ walletAddress,
5669
+ coinInType,
5670
+ coinInAmount,
5671
+ coinOutType,
5672
+ slippage = 1e3,
5673
+ // 0.1%
5674
+ ttl = "5m",
5675
+ excludeSources = [Protocol.STEAMM, Protocol.BOLT],
5676
+ routes,
5677
+ commission,
5678
+ tx: existingTx
5679
+ }, { suiClient, defiRouterUrl }) {
5680
+ const inAmount = BigInt(coinInAmount);
5681
+ const tx = existingTx ?? new Transaction11();
5682
+ coinInType = normalizeStructTag2(coinInType);
5683
+ coinOutType = normalizeStructTag2(coinOutType);
5684
+ walletAddress = normalizeSuiAddress(walletAddress);
5685
+ tx.setSenderIfNotSet(normalizeSuiAddress(walletAddress));
5686
+ if (inAmount === 0n) {
5687
+ const zeroCoin = tx.moveCall({
5688
+ target: "0x2::coin::zero",
5689
+ typeArguments: [coinOutType]
5690
+ });
5691
+ return {
5692
+ tx,
5693
+ coinOut: zeroCoin
5694
+ };
5695
+ }
5696
+ if (coinInType === coinOutType) {
5697
+ const getCoin = coinWithBalance({
5698
+ type: coinInType,
5699
+ balance: inAmount
5700
+ });
5701
+ return {
5702
+ tx,
5703
+ coinOut: getCoin(tx)
5704
+ };
5705
+ }
5706
+ const types = await getAffectedNftAndFtTypes(coinInType, coinOutType);
5707
+ const { feeAndReward, amountToSwap } = calculateSwapAmounts(types.length, inAmount);
5708
+ if (!routes) {
5709
+ routes = (await buildSwapRoutes(
5710
+ {
5711
+ walletAddress,
5712
+ coinInType,
5713
+ coinOutType,
5714
+ amountToSwap,
5715
+ excludeSources,
5716
+ commission
5717
+ },
5718
+ { defiRouterUrl }
5719
+ )).routes;
5720
+ }
5721
+ const tradeBuilder = new TradeBuilder("mainnet", routes);
5722
+ if (commission) {
5723
+ tradeBuilder.commission(commission);
5724
+ }
5725
+ const trade = tradeBuilder.sender(walletAddress).slippage(slippage).deadline(Date.now() + ms(ttl)).build();
5726
+ const coinOut = await trade.swap({ client: suiClient, tx });
5727
+ let suiFeeAndRewardCoin;
5728
+ if (coinInType === normalizeStructTag2(SUI_TYPE_ARG)) {
5729
+ suiFeeAndRewardCoin = tx.splitCoins(tx.gas, [
5730
+ tx.pure.u64(feeAndReward)
5731
+ ])[0];
5732
+ } else {
5733
+ const suiFeeAndRewardRoutes = await buildSwapRoutes(
5734
+ {
5735
+ walletAddress,
5736
+ coinInType,
5737
+ coinOutType: SUI_TYPE_ARG,
5738
+ amountToSwap: feeAndReward,
5739
+ excludeSources
5740
+ },
5741
+ { defiRouterUrl }
5742
+ );
5743
+ const suiFeeTradeBuilder = new TradeBuilder("mainnet", suiFeeAndRewardRoutes.routes);
5744
+ const suiFeeTrade = suiFeeTradeBuilder.sender(walletAddress).slippage(slippage).deadline(Date.now() + ms(ttl)).build();
5745
+ suiFeeAndRewardCoin = await suiFeeTrade.swap({ client: suiClient, tx });
5746
+ }
5747
+ if (types.length > 0) {
5748
+ if (types.length > 2) {
5749
+ throw new Error("Unexpected affected types count greater than 2");
5750
+ }
5751
+ let usedSuiCoin = suiFeeAndRewardCoin;
5752
+ if (types.length === 2) {
5753
+ const suiFeeAndRewardCoinBalance = tx.moveCall({
5754
+ target: "0x2::coin::value",
5755
+ typeArguments: [SUI_TYPE_ARG],
5756
+ arguments: [suiFeeAndRewardCoin]
5757
+ });
5758
+ const halfSuiCoinAmount = tx.moveCall({
5759
+ target: "0x2::math::divide_and_round_up",
5760
+ arguments: [suiFeeAndRewardCoinBalance, tx.pure.u64(2)]
5761
+ });
5762
+ const [coin] = tx.splitCoins(usedSuiCoin, [halfSuiCoinAmount]);
5763
+ usedSuiCoin = coin;
5764
+ }
5765
+ for (const data of types) {
5766
+ const { nftType, ftType, type } = data;
5767
+ switch (type) {
5768
+ case "liquidNft": {
5769
+ tx.moveCall({
5770
+ target: `${DexConstants.commission}::commission::pay`,
5771
+ arguments: [
5772
+ tx.object(DexConstants.commissionManager),
5773
+ tx.pure.string("swap"),
5774
+ usedSuiCoin,
5775
+ tx.pure.option("string", nftType)
5776
+ ],
5777
+ typeArguments: [SUI_TYPE_ARG]
5778
+ });
5779
+ break;
5780
+ }
5781
+ case "nftStrategy": {
5782
+ const suiFeeAndRewardCoinBalance = tx.moveCall({
5783
+ target: "0x2::coin::value",
5784
+ typeArguments: [SUI_TYPE_ARG],
5785
+ arguments: [usedSuiCoin]
5786
+ });
5787
+ const feeAmount = tx.moveCall({
5788
+ target: "0x2::math::divide_and_round_up",
5789
+ arguments: [suiFeeAndRewardCoinBalance, tx.pure.u64(4)]
5790
+ });
5791
+ const [feeCoin] = tx.splitCoins(usedSuiCoin, [feeAmount]);
5792
+ tx.moveCall({
5793
+ target: `${DexConstants.commission}::commission::pay`,
5794
+ arguments: [
5795
+ tx.object(DexConstants.commissionManager),
5796
+ tx.pure.string("swap"),
5797
+ feeCoin,
5798
+ tx.pure.option("string", void 0)
5799
+ ],
5800
+ typeArguments: [SUI_TYPE_ARG]
5801
+ });
5802
+ tx.moveCall({
5803
+ target: `${TRADEPORT_NFT_STRATEGY_PACKAGE_ID}::tradeport_nft_strategy::reward_strategy`,
5804
+ arguments: [
5805
+ tx.object(TRADEPORT_NFT_STRATEGY_MANAGER_ID),
5806
+ usedSuiCoin
5807
+ // 3/4 retained coin for reward
5808
+ ],
5809
+ typeArguments: [nftType, ftType]
5810
+ });
5811
+ break;
5812
+ }
5813
+ default: {
5814
+ throw new Error(`Unexpected type ${type}`);
5815
+ }
5816
+ }
5817
+ usedSuiCoin = suiFeeAndRewardCoin;
5818
+ }
5819
+ } else {
5820
+ tx.moveCall({
5821
+ target: `${DexConstants.commission}::commission::pay`,
5822
+ arguments: [
5823
+ tx.object(DexConstants.commissionManager),
5824
+ tx.pure.string("swap"),
5825
+ suiFeeAndRewardCoin,
5826
+ tx.pure.option("string", void 0)
5827
+ ],
5828
+ typeArguments: [SUI_TYPE_ARG]
5829
+ });
5830
+ }
5831
+ return {
5832
+ tx,
5833
+ coinOut
5834
+ };
5835
+ }
5836
+ async function calculateAmountToSwap({
5837
+ coinInType,
5838
+ coinOutType,
5839
+ coinInAmount
5840
+ }) {
5841
+ const types = await getAffectedNftAndFtTypes(coinInType, coinOutType);
5842
+ const { amountToSwap } = calculateSwapAmounts(types.length, BigInt(coinInAmount));
5843
+ return amountToSwap;
5844
+ }
5845
+ async function calculateSwapInputAmountWithSlippage({
5846
+ coinInType,
5847
+ coinOutType,
5848
+ coinOutAmount,
5849
+ slippage = 0
5850
+ }) {
5851
+ if (coinInType === coinOutType) {
5852
+ return new bigNumberConfig_default(coinOutAmount);
5853
+ }
5854
+ const provider = new CoinProvider("mainnet");
5855
+ const coinQueryResult = await provider.getCoins({
5856
+ limit: 2,
5857
+ coinTypes: [coinInType, coinOutType]
5858
+ });
5859
+ const coinIn = coinQueryResult?.find(
5860
+ (coin) => normalizeStructTag2(coin.coinType) === normalizeStructTag2(coinInType)
5861
+ );
5862
+ const coinOut = coinQueryResult?.find(
5863
+ (coin) => normalizeStructTag2(coin.coinType) === normalizeStructTag2(coinOutType)
5864
+ );
5865
+ const exchangeRate = new bigNumberConfig_default(coinOut.derivedPriceInUSD ?? 0)?.gt(0) ? new bigNumberConfig_default(coinIn?.derivedPriceInUSD ?? 1)?.div(coinOut?.derivedPriceInUSD ?? 1) : new bigNumberConfig_default(0);
5866
+ const amountSell = toDecimalValue(coinOutAmount.toString(), coinOut?.decimals).div(exchangeRate);
5867
+ const slippageMultiplier = 1 + parseInt(slippage.toString() || "0", 10) / 1e6;
5868
+ const amountWithSlippage = amountSell.times(slippageMultiplier);
5869
+ const coinInAmount = toPureValue(amountWithSlippage, coinIn?.decimals);
5870
+ return coinInAmount;
5871
+ }
5872
+ async function buildSwapRoutes(options, { defiRouterUrl }) {
5873
+ const aggregatorQuoter = new AggregatorQuoter("mainnet");
5874
+ const routes = await aggregatorQuoter.getRoutes({
5875
+ tokenIn: options.coinInType,
5876
+ tokenOut: options.coinOutType,
5877
+ amountIn: options.amountToSwap.toString(),
5878
+ commission: options.commission,
5879
+ excludeSources: options.excludeSources
5880
+ });
5881
+ if (defiRouterUrl && options.walletAddress) {
5882
+ await makeDefiRouterRequest(`${defiRouterUrl}/start`, {
5883
+ walletId: options.walletAddress,
5884
+ coinTypeIn: options.coinInType,
5885
+ coinTypeOut: options.coinOutType,
5886
+ amountIn: options.amountToSwap.toString()
5887
+ });
5888
+ }
5889
+ return routes;
5890
+ }
5891
+ function calculateSwapAmounts(affectedTypesCount, inAmount) {
5892
+ const feeAndReward = affectedTypesCount > 0 ? BigInt(affectedTypesCount) * inAmount / 25n : inAmount / 100n;
5893
+ const amountToSwap = inAmount - feeAndReward;
5894
+ if (amountToSwap <= 0n) {
5895
+ throw new Error("Amount to swap is too small");
5896
+ }
5897
+ return { feeAndReward, amountToSwap };
5898
+ }
5899
+ async function getAffectedNftAndFtTypes(coinInType, coinOutType) {
5900
+ const normalizedSuiType = normalizeStructTag2(SUI_TYPE_ARG);
5901
+ const coinTypes = [coinInType, coinOutType].filter((type) => type !== normalizedSuiType);
5902
+ const types = await Promise.all(
5903
+ coinTypes.map(async (type) => {
5904
+ const chainState = await getCollectionChainStateByFtType(type);
5905
+ return chainState ? {
5906
+ nftType: chainState.nft_type,
5907
+ ftType: type,
5908
+ type: chainState.ft_type ? "liquidNft" : "nftStrategy"
5909
+ } : void 0;
5910
+ })
5911
+ );
5912
+ return types.filter(Boolean);
5913
+ }
5914
+ async function makeDefiRouterRequest(url, body, defaultResponse = void 0) {
5915
+ try {
5916
+ const response = await fetch(url, {
5917
+ method: "POST",
5918
+ headers: { "Content-Type": "application/json" },
5919
+ body: JSON.stringify(body)
5920
+ });
5921
+ if (!response.ok) {
5922
+ console.warn(`DeFi router request failed with status ${response.status}`);
5923
+ return defaultResponse;
5924
+ }
5925
+ if (response.headers.get("Content-Type")?.includes("application/json")) {
5926
+ return await response.json();
5927
+ }
5928
+ return defaultResponse;
5929
+ } catch (error) {
5930
+ console.warn(`DeFi router request error: ${error.message}`);
5931
+ return defaultResponse;
5932
+ }
5933
+ }
5934
+
5700
5935
  // src/methods/sponsorNftListing/addSponsorNftListingTx.ts
5701
- import { coinWithBalance } from "@mysten/sui/transactions";
5702
5936
  var addSponsorListingTx = async ({
5703
5937
  tx,
5704
5938
  nftTokenId,
5705
5939
  nftType,
5706
- sponsorOptions
5940
+ suiClient,
5941
+ walletAddress,
5942
+ sponsorOptions,
5943
+ defiRouterUrl
5707
5944
  }) => {
5708
- const totalFee = new bigNumberConfig_default(sponsorOptions?.usdcFeeAmountPerPeriod)?.times(sponsorOptions?.numOfPeriods).toString();
5709
- const sponsorCoin = sponsorOptions.coinToSplit ? tx.splitCoins(sponsorOptions.coinToSplit, [tx.pure.u64(totalFee)])[0] : coinWithBalance({ type: USDC_COIN_TYPE, balance: BigInt(totalFee) });
5945
+ const coinInAmount = sponsorOptions?.coinInAmount ?? await calculateSwapInputAmountWithSlippage({
5946
+ coinInType: sponsorOptions?.coinInType,
5947
+ coinOutType: USDC_COIN_TYPE,
5948
+ coinOutAmount: new bigNumberConfig_default(sponsorOptions?.usdcFeeAmountPerPeriod)?.times(sponsorOptions?.numOfPeriods).toString(),
5949
+ slippage: sponsorOptions?.slippage
5950
+ });
5951
+ const { coinOut } = await swapCoins(
5952
+ {
5953
+ walletAddress,
5954
+ coinInType: sponsorOptions?.coinInType,
5955
+ coinInAmount: coinInAmount.toString(),
5956
+ coinOutType: USDC_COIN_TYPE,
5957
+ slippage: sponsorOptions?.slippage,
5958
+ tx
5959
+ },
5960
+ { suiClient, defiRouterUrl }
5961
+ );
5962
+ const [sponsorFeeCoin] = tx.splitCoins(coinOut, [
5963
+ tx.pure.u64(
5964
+ new bigNumberConfig_default(sponsorOptions?.usdcFeeAmountPerPeriod)?.times(sponsorOptions?.numOfPeriods).toString()
5965
+ )
5966
+ ]);
5710
5967
  tx.moveCall({
5711
5968
  target: `${TRADEPORT_LISTINGS_PACKAGE}::tradeport_listings::add_sponsored_listing`,
5712
5969
  arguments: [
@@ -5714,14 +5971,19 @@ var addSponsorListingTx = async ({
5714
5971
  tx.object.clock(),
5715
5972
  tx.pure.id(nftTokenId),
5716
5973
  tx.pure.u64(sponsorOptions?.numOfPeriods),
5717
- tx.object(sponsorCoin)
5974
+ tx.object(sponsorFeeCoin)
5718
5975
  ],
5719
5976
  typeArguments: [nftType]
5720
5977
  });
5978
+ tx.transferObjects([coinOut], walletAddress);
5721
5979
  };
5722
5980
 
5981
+ // src/helpers/isExpiredListing.ts
5982
+ import { normalizeSuiAddress as normalizeSuiAddress2 } from "@mysten/sui/utils";
5983
+ var isExpiredListing = (listing, walletAddress) => listing.nonce && listing.seller && normalizeSuiAddress2(listing.seller) === normalizeSuiAddress2(walletAddress);
5984
+
5723
5985
  // src/methods/listNfts/listNfts.ts
5724
- var listNfts = async ({ nfts, walletAddress, tx: existingTx }, context) => {
5986
+ var listNfts = async ({ nfts, walletAddress }, context) => {
5725
5987
  const res = await gqlChainRequest({
5726
5988
  chain: "sui",
5727
5989
  query: fetchNftsWithListingsById,
@@ -5731,7 +5993,7 @@ var listNfts = async ({ nfts, walletAddress, tx: existingTx }, context) => {
5731
5993
  throw new Error("No nfts found");
5732
5994
  }
5733
5995
  const nftsForTracking = [];
5734
- const tx = existingTx ?? new Transaction13();
5996
+ const tx = new Transaction12();
5735
5997
  const sharedKioskState = {
5736
5998
  kioskTx: void 0
5737
5999
  };
@@ -5781,9 +6043,12 @@ var listNfts = async ({ nfts, walletAddress, tx: existingTx }, context) => {
5781
6043
  if (inputNft?.sponsorOptions?.shouldSponsor) {
5782
6044
  await addSponsorListingTx({
5783
6045
  tx,
6046
+ suiClient: context.suiClient,
5784
6047
  nftTokenId: nft?.token_id,
5785
6048
  nftType,
5786
- sponsorOptions: inputNft?.sponsorOptions
6049
+ walletAddress,
6050
+ sponsorOptions: inputNft?.sponsorOptions,
6051
+ defiRouterUrl: context.defiRouterUrl
5787
6052
  });
5788
6053
  }
5789
6054
  nftsForTracking.push({
@@ -5796,15 +6061,15 @@ var listNfts = async ({ nfts, walletAddress, tx: existingTx }, context) => {
5796
6061
  });
5797
6062
  }
5798
6063
  sharedKioskState?.kioskTx?.finalize();
5799
- return tx;
6064
+ return tx instanceof Transaction12 ? tx : Transaction12.from(tx);
5800
6065
  };
5801
6066
 
5802
6067
  // src/methods/migrateNftsFromUnsharedToSharedKiosks/migrateNftsFromUnsharedToSharedKiosks.ts
5803
- import { Transaction as Transaction14 } from "@mysten/sui/transactions";
6068
+ import { Transaction as Transaction13 } from "@mysten/sui/transactions";
5804
6069
 
5805
6070
  // src/graphql/queries/fetchNftsByKioskId.ts
5806
- import { gql as gql17 } from "graphql-request";
5807
- var fetchNftsByKioskId = gql17`
6071
+ import { gql as gql16 } from "graphql-request";
6072
+ var fetchNftsByKioskId = gql16`
5808
6073
  query fetchNftsByKioskId($jsonFilter: jsonb) {
5809
6074
  nfts(where: { chain_state: { _contains: $jsonFilter } }) {
5810
6075
  id
@@ -5825,7 +6090,7 @@ var fetchNftsByKioskId = gql17`
5825
6090
  }
5826
6091
  }
5827
6092
  `;
5828
- var fetchBulkNftsByKioskId = gql17`
6093
+ var fetchBulkNftsByKioskId = gql16`
5829
6094
  query fetchNftsByKioskId($where: nfts_bool_exp) {
5830
6095
  nfts(where: $where) {
5831
6096
  id
@@ -5848,8 +6113,8 @@ var fetchBulkNftsByKioskId = gql17`
5848
6113
  `;
5849
6114
 
5850
6115
  // src/graphql/queries/fetchTransferPoliciesByType.ts
5851
- import { gql as gql18 } from "graphql-request";
5852
- var fetchTransferPoliciesByType = gql18`
6116
+ import { gql as gql17 } from "graphql-request";
6117
+ var fetchTransferPoliciesByType = gql17`
5853
6118
  query fetchTransferPoliciesByType($type: String!) {
5854
6119
  transfer_policies_by_type(type: $type) {
5855
6120
  id
@@ -6008,7 +6273,7 @@ async function getTransferPolicyForDirectTransfer(suiClient, collectionChainStat
6008
6273
 
6009
6274
  // src/methods/migrateNftsFromUnsharedToSharedKiosks/migrateNftsFromUnsharedToSharedKiosks.ts
6010
6275
  async function migrateNftsFromUnsharedToSharedKiosks({ walletAddress, max = 50 }, context) {
6011
- const tx = new Transaction14();
6276
+ const tx = new Transaction13();
6012
6277
  const res = await gqlChainRequest({
6013
6278
  chain: "sui",
6014
6279
  query: fetchKiosksByOwner,
@@ -6174,15 +6439,15 @@ async function migrateNftsFromUnsharedToSharedKiosks({ walletAddress, max = 50 }
6174
6439
  }
6175
6440
  }
6176
6441
  sharedKioskState?.kioskTx?.finalize();
6177
- return Transaction14.from(tx);
6442
+ return Transaction13.from(tx);
6178
6443
  }
6179
6444
 
6180
6445
  // src/methods/placeCollectionBids/placeCollectionBids.ts
6181
- import { Transaction as Transaction15 } from "@mysten/sui/transactions";
6446
+ import { Transaction as Transaction14 } from "@mysten/sui/transactions";
6182
6447
 
6183
6448
  // src/graphql/queries/fetchCollectionsById.ts
6184
- import { gql as gql19 } from "graphql-request";
6185
- var fetchCollectionsById = gql19`
6449
+ import { gql as gql18 } from "graphql-request";
6450
+ var fetchCollectionsById = gql18`
6186
6451
  query fetchCollectionsById($collectionIds: [uuid!]) {
6187
6452
  collections(where: { id: { _in: $collectionIds } }) {
6188
6453
  id
@@ -6192,7 +6457,7 @@ var fetchCollectionsById = gql19`
6192
6457
  }
6193
6458
  }
6194
6459
  `;
6195
- var fetchCollectionsByIdWithOneNft = gql19`
6460
+ var fetchCollectionsByIdWithOneNft = gql18`
6196
6461
  query fetchCollectionsByIdWithOneNft($collectionIds: [uuid!]) {
6197
6462
  collections(where: { id: { _in: $collectionIds } }) {
6198
6463
  id
@@ -6210,7 +6475,7 @@ var fetchCollectionsByIdWithOneNft = gql19`
6210
6475
  }
6211
6476
  }
6212
6477
  `;
6213
- var fetchCollectionsBySlug = gql19`
6478
+ var fetchCollectionsBySlug = gql18`
6214
6479
  query fetchCollectionsBySlug($slug: String!) {
6215
6480
  collections(where: { slug: { _eq: $slug } }) {
6216
6481
  id
@@ -6332,8 +6597,8 @@ function isDynamicCollection(collectionId) {
6332
6597
  }
6333
6598
 
6334
6599
  // src/graphql/queries/fetchCollectionFloorListings.ts
6335
- import { gql as gql20 } from "graphql-request";
6336
- var fetchCollectionFloorListings = gql20`
6600
+ import { gql as gql19 } from "graphql-request";
6601
+ var fetchCollectionFloorListings = gql19`
6337
6602
  query fetchCollectionFloorListings($collectionId: uuid!) {
6338
6603
  listings(
6339
6604
  where: { collection_id: { _eq: $collectionId }, listed: { _eq: true }, nft: {} }
@@ -6392,14 +6657,7 @@ async function addOriginByteCollectionBidTx({
6392
6657
  }
6393
6658
 
6394
6659
  // src/methods/placeCollectionBids/placeCollectionBids.ts
6395
- var placeCollectionBids = async ({
6396
- collections,
6397
- walletAddress,
6398
- multiBidId,
6399
- multiBidChainId,
6400
- tx: existingTx,
6401
- coinToSplit
6402
- }, context) => {
6660
+ var placeCollectionBids = async ({ collections, walletAddress, multiBidId, multiBidChainId, tx: existingTx }, context) => {
6403
6661
  const res = await gqlChainRequest({
6404
6662
  chain: "sui",
6405
6663
  query: fetchCollectionsByIdWithOneNft,
@@ -6409,7 +6667,8 @@ var placeCollectionBids = async ({
6409
6667
  throw new Error("No collection found");
6410
6668
  }
6411
6669
  const collectionsForTracking = [];
6412
- const tx = existingTx ?? new Transaction15();
6670
+ const tx = deserializeOrCreateTxBlock({ existingTx });
6671
+ const swapResultCoin = extractSwapResultCoinFromTxBlock(tx);
6413
6672
  for (const collection of res.collections) {
6414
6673
  const nftType = getNftType({
6415
6674
  collectionId: collection?.id,
@@ -6429,7 +6688,7 @@ var placeCollectionBids = async ({
6429
6688
  multiBidId,
6430
6689
  multiBidChainId,
6431
6690
  expireAt: collections?.find((c) => c.id === collection?.id)?.expireAt,
6432
- coinToSplit
6691
+ coinToSplit: swapResultCoin
6433
6692
  };
6434
6693
  const numOfBids = collections?.find((c) => c.id === collection?.id)?.numOfBids;
6435
6694
  if (isOriginByteCollection(txData?.transferPolicies) && !ORIGIN_BYTE_NFT_TYPES_MISSING_ORDERBOOK?.includes(normalizedNftType(txData?.nftType))) {
@@ -6456,13 +6715,17 @@ var placeCollectionBids = async ({
6456
6715
  bidder: walletAddress
6457
6716
  });
6458
6717
  }
6459
- return tx;
6718
+ if (swapResultCoin) {
6719
+ tx.transferObjects([swapResultCoin], walletAddress);
6720
+ }
6721
+ return Transaction14.from(tx);
6460
6722
  };
6461
6723
 
6462
6724
  // src/methods/placeNftBids/placeNftBids.ts
6463
- import { Transaction as Transaction16 } from "@mysten/sui/transactions";
6464
- var placeNftBids = async ({ bids, walletAddress, multiBidId, multiBidChainId, tx: existingTx, coinToSplit }, context) => {
6465
- const tx = existingTx ?? new Transaction16();
6725
+ import { Transaction as Transaction15 } from "@mysten/sui/transactions";
6726
+ var placeNftBids = async ({ bids, walletAddress, multiBidId, multiBidChainId, tx: existingTx }, context) => {
6727
+ const tx = deserializeOrCreateTxBlock({ existingTx });
6728
+ const swapResultCoin = extractSwapResultCoinFromTxBlock(tx);
6466
6729
  const res = await gqlChainRequest({
6467
6730
  chain: "sui",
6468
6731
  query: fetchNftsById,
@@ -6496,7 +6759,7 @@ var placeNftBids = async ({ bids, walletAddress, multiBidId, multiBidChainId, tx
6496
6759
  multiBidId,
6497
6760
  multiBidChainId,
6498
6761
  expireAt: bid?.expireAt,
6499
- coinToSplit
6762
+ coinToSplit: swapResultCoin
6500
6763
  };
6501
6764
  await addTradePortPlaceNftBidTxHandler(txData);
6502
6765
  nftsForTracking.push({
@@ -6506,11 +6769,14 @@ var placeNftBids = async ({ bids, walletAddress, multiBidId, multiBidChainId, tx
6506
6769
  bidder: walletAddress
6507
6770
  });
6508
6771
  }
6509
- return tx;
6772
+ if (swapResultCoin) {
6773
+ tx.transferObjects([swapResultCoin], walletAddress);
6774
+ }
6775
+ return Transaction15.from(tx);
6510
6776
  };
6511
6777
 
6512
6778
  // src/methods/removeCollectionBids/removeCollectionBids.ts
6513
- import { Transaction as Transaction17 } from "@mysten/sui/transactions";
6779
+ import { Transaction as Transaction16 } from "@mysten/sui/transactions";
6514
6780
 
6515
6781
  // src/methods/removeCollectionBids/addRemoveCollectionBidsTxs.ts
6516
6782
  import { normalizeSuiObjectId as normalizeSuiObjectId7 } from "@mysten/sui/utils";
@@ -6618,7 +6884,7 @@ var removeCollectionBids = async ({ bidIds, tx: existingTx }, context) => {
6618
6884
  throw new Error("No bids found");
6619
6885
  }
6620
6886
  const bidsForTracking = [];
6621
- const tx = existingTx ? Transaction17.from(existingTx) : new Transaction17();
6887
+ const tx = existingTx ? Transaction16.from(existingTx) : new Transaction16();
6622
6888
  for (const bid of res.bids) {
6623
6889
  if (DELOREAN_TOKEN_IDS_TO_DISABLE?.includes(bid?.nft?.token_id)) {
6624
6890
  throw new Error(DELOREAN_TOKEN_IDS_TO_DISABLE_MESSAGE);
@@ -6666,11 +6932,11 @@ var removeCollectionBids = async ({ bidIds, tx: existingTx }, context) => {
6666
6932
  bidder: bid?.bidder
6667
6933
  });
6668
6934
  }
6669
- return Transaction17.from(tx);
6935
+ return Transaction16.from(tx);
6670
6936
  };
6671
6937
 
6672
6938
  // src/methods/removeNftBids/removeNftBids.ts
6673
- import { Transaction as Transaction18 } from "@mysten/sui/transactions";
6939
+ import { Transaction as Transaction17 } from "@mysten/sui/transactions";
6674
6940
  var removeNftBids = async ({ bidIds, tx: existingTx }, context) => {
6675
6941
  const res = await gqlChainRequest({
6676
6942
  chain: "sui",
@@ -6681,7 +6947,7 @@ var removeNftBids = async ({ bidIds, tx: existingTx }, context) => {
6681
6947
  throw new Error("No bids found");
6682
6948
  }
6683
6949
  const bidsForTracking = [];
6684
- const tx = existingTx ? Transaction18.from(existingTx) : new Transaction18();
6950
+ const tx = existingTx ? Transaction17.from(existingTx) : new Transaction17();
6685
6951
  for (const bid of res.bids) {
6686
6952
  if (DELOREAN_TOKEN_IDS_TO_DISABLE?.includes(bid?.nft?.token_id)) {
6687
6953
  throw new Error(DELOREAN_TOKEN_IDS_TO_DISABLE_MESSAGE);
@@ -6726,61 +6992,11 @@ var removeNftBids = async ({ bidIds, tx: existingTx }, context) => {
6726
6992
  bidder: bid?.bidder
6727
6993
  });
6728
6994
  }
6729
- return Transaction18.from(tx);
6730
- };
6731
-
6732
- // src/methods/sponsorNftListing/sponsorNftListing.ts
6733
- import { Transaction as Transaction19 } from "@mysten/sui/transactions";
6734
-
6735
- // src/graphql/queries/fetchNftCollectionChainState.ts
6736
- import { gql as gql21 } from "graphql-request";
6737
- var fetchNftCollectionChainState = gql21`
6738
- query fetchNftCollectionChainState($nftTokenId: String!) {
6739
- nfts(where: { token_id: { _eq: $nftTokenId } }) {
6740
- collection {
6741
- id
6742
- chain_state
6743
- }
6744
- }
6745
- }
6746
- `;
6747
-
6748
- // src/methods/sponsorNftListing/sponsorNftListing.ts
6749
- var sponsorNftListing = async ({
6750
- tx: existingTx,
6751
- nftTokenId,
6752
- options
6753
- }) => {
6754
- const res = await gqlChainRequest({
6755
- chain: "sui",
6756
- query: fetchNftCollectionChainState,
6757
- variables: { nftTokenId }
6758
- });
6759
- if (res?.nfts?.length === 0) {
6760
- throw new Error(`No nft found with token id ${nftTokenId}`);
6761
- }
6762
- const nft = res?.nfts?.[0];
6763
- const nftType = getNftType({
6764
- collectionId: nft?.collection?.id,
6765
- collectionChainState: nft?.collection?.chain_state,
6766
- nft
6767
- });
6768
- const transferPolicies = nft?.collection?.chain_state?.transfer_policies;
6769
- if (isOriginByteCollection(transferPolicies)) {
6770
- throw new Error(`You cannot sponsor an Origin Byte NFT. Nft Token Id: ${nftTokenId}`);
6771
- }
6772
- const tx = existingTx ?? new Transaction19();
6773
- await addSponsorListingTx({
6774
- tx,
6775
- nftTokenId,
6776
- nftType,
6777
- sponsorOptions: options
6778
- });
6779
- return tx;
6995
+ return Transaction17.from(tx);
6780
6996
  };
6781
6997
 
6782
6998
  // src/methods/transferNfts/transferNfts.ts
6783
- import { Transaction as Transaction20 } from "@mysten/sui/transactions";
6999
+ import { Transaction as Transaction18 } from "@mysten/sui/transactions";
6784
7000
  var transferNfts = async ({ nftIds, recipientAddress, walletAddress }, context) => {
6785
7001
  if (addLeadingZerosAfter0x(recipientAddress) === addLeadingZerosAfter0x(walletAddress)) {
6786
7002
  throw new Error("Cannot transfer to self");
@@ -6798,7 +7014,7 @@ var transferNfts = async ({ nftIds, recipientAddress, walletAddress }, context)
6798
7014
  }
6799
7015
  const nftsForTracking = [];
6800
7016
  const nftsToTransferDirectly = [];
6801
- const tx = new Transaction20();
7017
+ const tx = new Transaction18();
6802
7018
  const sharedKioskState = {
6803
7019
  kioskTx: void 0
6804
7020
  };
@@ -6901,11 +7117,11 @@ var transferNfts = async ({ nftIds, recipientAddress, walletAddress }, context)
6901
7117
  context.suiClient
6902
7118
  );
6903
7119
  sharedKioskState?.kioskTx?.finalize();
6904
- return Transaction20.from(tx);
7120
+ return Transaction18.from(tx);
6905
7121
  };
6906
7122
 
6907
7123
  // src/methods/unlistListings/unlistListings.ts
6908
- import { Transaction as Transaction21 } from "@mysten/sui/transactions";
7124
+ import { Transaction as Transaction19 } from "@mysten/sui/transactions";
6909
7125
  var unlistListings = async ({ listingIds, walletAddress }, context) => {
6910
7126
  const res = await gqlChainRequest({
6911
7127
  chain: "sui",
@@ -6916,7 +7132,7 @@ var unlistListings = async ({ listingIds, walletAddress }, context) => {
6916
7132
  throw new Error("No listings found");
6917
7133
  }
6918
7134
  const listingsForTracking = [];
6919
- const tx = new Transaction21();
7135
+ const tx = new Transaction19();
6920
7136
  const sharedKioskState = {
6921
7137
  kioskTx: void 0
6922
7138
  };
@@ -6985,12 +7201,12 @@ var unlistListings = async ({ listingIds, walletAddress }, context) => {
6985
7201
  });
6986
7202
  }
6987
7203
  sharedKioskState?.kioskTx?.finalize();
6988
- return Transaction21.from(tx);
7204
+ return Transaction19.from(tx);
6989
7205
  };
6990
7206
 
6991
7207
  // src/methods/withdrawProfitsFromKiosks/withdrawProfitsFromKiosks.ts
6992
7208
  import { KioskTransaction as KioskTransaction2 } from "@mysten/kiosk";
6993
- import { Transaction as Transaction22 } from "@mysten/sui/transactions";
7209
+ import { Transaction as Transaction20 } from "@mysten/sui/transactions";
6994
7210
  async function withdrawProfitsFromKiosks({ walletAddress }, context) {
6995
7211
  const res = await gqlChainRequest({
6996
7212
  chain: "sui",
@@ -7010,7 +7226,7 @@ async function withdrawProfitsFromKiosks({ walletAddress }, context) {
7010
7226
  if (kiosksWithProfit.length === 0) {
7011
7227
  throw new Error(`No kiosks with profit to withdraw found for ${walletAddress}`);
7012
7228
  }
7013
- const tx = new Transaction22();
7229
+ const tx = new Transaction20();
7014
7230
  try {
7015
7231
  for (const kiosk of kiosksWithProfit) {
7016
7232
  let kioskTx;
@@ -7056,7 +7272,149 @@ async function withdrawProfitsFromKiosks({ walletAddress }, context) {
7056
7272
  } catch (err) {
7057
7273
  console.log("err", err);
7058
7274
  }
7059
- return Transaction22.from(tx);
7275
+ return Transaction20.from(tx);
7276
+ }
7277
+
7278
+ // src/methods/sponsorNftListing/sponsorNftListing.ts
7279
+ import { Transaction as Transaction21 } from "@mysten/sui/transactions";
7280
+
7281
+ // src/graphql/queries/fetchNftCollectionChainState.ts
7282
+ import { gql as gql20 } from "graphql-request";
7283
+ var fetchNftCollectionChainState = gql20`
7284
+ query fetchNftCollectionChainState($nftTokenId: String!) {
7285
+ nfts(where: { token_id: { _eq: $nftTokenId } }) {
7286
+ collection {
7287
+ id
7288
+ chain_state
7289
+ }
7290
+ }
7291
+ }
7292
+ `;
7293
+
7294
+ // src/methods/sponsorNftListing/sponsorNftListing.ts
7295
+ var sponsorNftListing = async ({ nftTokenId, walletAddress, options }, context) => {
7296
+ const res = await gqlChainRequest({
7297
+ chain: "sui",
7298
+ query: fetchNftCollectionChainState,
7299
+ variables: { nftTokenId }
7300
+ });
7301
+ if (res?.nfts?.length === 0) {
7302
+ throw new Error(`No nft found with token id ${nftTokenId}`);
7303
+ }
7304
+ const nft = res?.nfts?.[0];
7305
+ const nftType = getNftType({
7306
+ collectionId: nft?.collection?.id,
7307
+ collectionChainState: nft?.collection?.chain_state,
7308
+ nft
7309
+ });
7310
+ const transferPolicies = nft?.collection?.chain_state?.transfer_policies;
7311
+ if (isOriginByteCollection(transferPolicies)) {
7312
+ throw new Error(`You cannot sponsor an Origin Byte NFT. Nft Token Id: ${nftTokenId}`);
7313
+ }
7314
+ const tx = new Transaction21();
7315
+ await addSponsorListingTx({
7316
+ tx,
7317
+ suiClient: context.suiClient,
7318
+ nftTokenId,
7319
+ nftType,
7320
+ walletAddress,
7321
+ sponsorOptions: options,
7322
+ defiRouterUrl: context.defiRouterUrl
7323
+ });
7324
+ return tx instanceof Transaction21 ? tx : Transaction21.from(tx);
7325
+ };
7326
+
7327
+ // src/methods/applyNftStrategy/applyNftStrategy.ts
7328
+ import { Transaction as Transaction22 } from "@mysten/sui/transactions";
7329
+
7330
+ // src/graphql/queries/fetchCollectionFloorListingForMarket.ts
7331
+ import { gql as gql21 } from "graphql-request";
7332
+ var fetchCollectionFloorListingsForMarket = gql21`
7333
+ query fetchCollectionFloorListingsForMarket(
7334
+ $collectionId: uuid!
7335
+ $marketAddress: String!
7336
+ $totalPrice: numeric
7337
+ ) {
7338
+ listings(
7339
+ where: {
7340
+ collection_id: { _eq: $collectionId }
7341
+ listed: { _eq: true }
7342
+ market_name: { _eq: "tradeport" }
7343
+ seller: { _neq: $marketAddress }
7344
+ nonce: { _like: "1::0x%" }
7345
+ price: { _lte: $totalPrice }
7346
+ }
7347
+ order_by: [{ price: asc_nulls_last }, { block_height: asc }, { tx_index: asc }]
7348
+ ) {
7349
+ id
7350
+ price
7351
+ nft {
7352
+ token_id
7353
+ delegated_owner
7354
+ }
7355
+ }
7356
+ }
7357
+ `;
7358
+
7359
+ // src/methods/applyNftStrategy/applyNftStrategy.ts
7360
+ async function applyTradeportNftStrategy({
7361
+ collectionId,
7362
+ strategyFtType,
7363
+ tx: existingTx
7364
+ }) {
7365
+ const tx = existingTx ?? new Transaction22();
7366
+ const chainState = await getCollectionChainState(collectionId);
7367
+ const nftStrategies = chainState?.nft_strategies ?? {};
7368
+ const nftStrategyKeys = Object.keys(nftStrategies);
7369
+ if (nftStrategyKeys.length === 0) {
7370
+ throw new Error("No NFT strategies found for collection");
7371
+ }
7372
+ strategyFtType = strategyFtType ?? nftStrategyKeys[0];
7373
+ if (!nftStrategyKeys.includes(strategyFtType)) {
7374
+ throw new Error(`Specified FT type ${strategyFtType} is not supported for this collection`);
7375
+ }
7376
+ const transferPolicy = getNativeKioskTransferPolicies(chainState?.transfer_policies ?? [])?.at(0);
7377
+ if (!transferPolicy) {
7378
+ throw new Error("No transfer policy found for collection");
7379
+ }
7380
+ const nftType = chainState?.nft_type;
7381
+ let suiBalance = BigInt(
7382
+ nftStrategies[strategyFtType].sui_balance ?? 0n
7383
+ );
7384
+ const result = await gqlChainRequest({
7385
+ chain: "sui",
7386
+ query: fetchCollectionFloorListingsForMarket,
7387
+ variables: {
7388
+ collectionId,
7389
+ marketAddress: TRADEPORT_NFT_STRATEGY_MANAGER_ID,
7390
+ totalPrice: suiBalance.toString()
7391
+ }
7392
+ });
7393
+ if ((result?.listings?.length ?? 0) === 0) {
7394
+ throw new Error(
7395
+ `No floor listing found for collection with price bellow or equal to ${suiBalance} MIST`
7396
+ );
7397
+ }
7398
+ for (const floorListing of result.listings) {
7399
+ suiBalance -= BigInt(floorListing.price);
7400
+ if (suiBalance < 0n) {
7401
+ break;
7402
+ }
7403
+ tx.moveCall({
7404
+ target: `${TRADEPORT_NFT_STRATEGY_PACKAGE_ID}::tradeport_nft_strategy::apply_tradeport_nft_strategy_confirm_request`,
7405
+ typeArguments: [nftType, strategyFtType],
7406
+ arguments: [
7407
+ tx.object(TRADEPORT_NFT_STRATEGY_MANAGER_ID),
7408
+ tx.object(nftStrategies[strategyFtType].kiosk_id),
7409
+ tx.object(TRADEPORT_LISTINGS_STORE),
7410
+ tx.object(TRADEPORT_ORDERBOOK_STORE),
7411
+ tx.object(floorListing.nft.delegated_owner),
7412
+ tx.object(floorListing.nft.token_id),
7413
+ tx.object(transferPolicy.id)
7414
+ ]
7415
+ });
7416
+ }
7417
+ return tx;
7060
7418
  }
7061
7419
 
7062
7420
  // src/SuiTradingClient.ts
@@ -7066,14 +7424,14 @@ var SuiTradingClient = class {
7066
7424
  apiKey,
7067
7425
  apiVercelId,
7068
7426
  apiUrl,
7069
- tradeportRouterUrl,
7427
+ defiRouterUrl,
7070
7428
  suiNodeUrl,
7071
7429
  graphQLClient
7072
7430
  }) {
7073
7431
  this.allowedApiUsersForUnsharedKiosksMigration = ["tradeport.xyz", "mercato.xyz"];
7074
7432
  this.apiUser = apiUser;
7075
7433
  this.apiKey = apiKey;
7076
- this.tradeportRouterUrl = tradeportRouterUrl;
7434
+ this.defiRouterUrl = defiRouterUrl ?? "https://api.indexer.xyz/router";
7077
7435
  this.suiClient = createSuiClient_default(suiNodeUrl ?? getFullnodeUrl("mainnet"));
7078
7436
  this.kioskClient = createKioskClient_default(this.suiClient);
7079
7437
  if (graphQLClient) {
@@ -7087,31 +7445,31 @@ var SuiTradingClient = class {
7087
7445
  ...apiVercelId && { "x-vercel-id": apiVercelId }
7088
7446
  });
7089
7447
  }
7090
- async buyListings(args) {
7448
+ async buyListings({ listingIds, walletAddress, tx }) {
7091
7449
  const context = {
7092
7450
  apiUser: this.apiUser,
7093
7451
  apiKey: this.apiKey,
7094
- tradeportRouterUrl: this.tradeportRouterUrl,
7452
+ defiRouterUrl: this.defiRouterUrl,
7095
7453
  suiClient: this.suiClient,
7096
7454
  kioskClient: this.kioskClient
7097
7455
  };
7098
- return buyListings(args, context);
7456
+ return buyListings({ listingIds, walletAddress, tx }, context);
7099
7457
  }
7100
- async listNfts({ nfts, walletAddress, tx }) {
7458
+ async listNfts({ nfts, walletAddress }) {
7101
7459
  const context = {
7102
7460
  apiUser: this.apiUser,
7103
7461
  apiKey: this.apiKey,
7104
- tradeportRouterUrl: this.tradeportRouterUrl,
7462
+ defiRouterUrl: this.defiRouterUrl,
7105
7463
  suiClient: this.suiClient,
7106
7464
  kioskClient: this.kioskClient
7107
7465
  };
7108
- return listNfts({ nfts, walletAddress, tx }, context);
7466
+ return listNfts({ nfts, walletAddress }, context);
7109
7467
  }
7110
7468
  async unlistListings({ listingIds, walletAddress }) {
7111
7469
  const context = {
7112
7470
  apiUser: this.apiUser,
7113
7471
  apiKey: this.apiKey,
7114
- tradeportRouterUrl: this.tradeportRouterUrl,
7472
+ defiRouterUrl: this.defiRouterUrl,
7115
7473
  suiClient: this.suiClient,
7116
7474
  kioskClient: this.kioskClient
7117
7475
  };
@@ -7121,7 +7479,7 @@ var SuiTradingClient = class {
7121
7479
  const context = {
7122
7480
  apiUser: this.apiUser,
7123
7481
  apiKey: this.apiKey,
7124
- tradeportRouterUrl: this.tradeportRouterUrl,
7482
+ defiRouterUrl: this.defiRouterUrl,
7125
7483
  suiClient: this.suiClient,
7126
7484
  kioskClient: this.kioskClient
7127
7485
  };
@@ -7130,7 +7488,7 @@ var SuiTradingClient = class {
7130
7488
  async removeNftBids({ bidIds, tx }) {
7131
7489
  const context = {
7132
7490
  apiUser: this.apiUser,
7133
- tradeportRouterUrl: this.tradeportRouterUrl,
7491
+ defiRouterUrl: this.defiRouterUrl,
7134
7492
  apiKey: this.apiKey,
7135
7493
  suiClient: this.suiClient,
7136
7494
  kioskClient: this.kioskClient
@@ -7141,7 +7499,7 @@ var SuiTradingClient = class {
7141
7499
  const context = {
7142
7500
  apiUser: this.apiUser,
7143
7501
  apiKey: this.apiKey,
7144
- tradeportRouterUrl: this.tradeportRouterUrl,
7502
+ defiRouterUrl: this.defiRouterUrl,
7145
7503
  suiClient: this.suiClient,
7146
7504
  kioskClient: this.kioskClient
7147
7505
  };
@@ -7160,7 +7518,7 @@ var SuiTradingClient = class {
7160
7518
  const context = {
7161
7519
  apiUser: this.apiUser,
7162
7520
  apiKey: this.apiKey,
7163
- tradeportRouterUrl: this.tradeportRouterUrl,
7521
+ defiRouterUrl: this.defiRouterUrl,
7164
7522
  suiClient: this.suiClient,
7165
7523
  kioskClient: this.kioskClient
7166
7524
  };
@@ -7186,7 +7544,7 @@ var SuiTradingClient = class {
7186
7544
  const context = {
7187
7545
  apiUser: this.apiUser,
7188
7546
  apiKey: this.apiKey,
7189
- tradeportRouterUrl: this.tradeportRouterUrl,
7547
+ defiRouterUrl: this.defiRouterUrl,
7190
7548
  suiClient: this.suiClient,
7191
7549
  kioskClient: this.kioskClient
7192
7550
  };
@@ -7262,7 +7620,7 @@ var SuiTradingClient = class {
7262
7620
  const context = {
7263
7621
  apiUser: this.apiUser,
7264
7622
  apiKey: this.apiKey,
7265
- tradeportRouterUrl: this.tradeportRouterUrl,
7623
+ defiRouterUrl: this.defiRouterUrl,
7266
7624
  suiClient: this.suiClient,
7267
7625
  kioskClient: this.kioskClient
7268
7626
  };
@@ -7272,7 +7630,7 @@ var SuiTradingClient = class {
7272
7630
  const context = {
7273
7631
  apiUser: this.apiUser,
7274
7632
  apiKey: this.apiKey,
7275
- tradeportRouterUrl: this.tradeportRouterUrl,
7633
+ defiRouterUrl: this.defiRouterUrl,
7276
7634
  suiClient: this.suiClient,
7277
7635
  kioskClient: this.kioskClient
7278
7636
  };
@@ -7282,7 +7640,7 @@ var SuiTradingClient = class {
7282
7640
  const context = {
7283
7641
  apiUser: this.apiUser,
7284
7642
  apiKey: this.apiKey,
7285
- tradeportRouterUrl: this.tradeportRouterUrl,
7643
+ defiRouterUrl: this.defiRouterUrl,
7286
7644
  suiClient: this.suiClient,
7287
7645
  kioskClient: this.kioskClient
7288
7646
  };
@@ -7298,7 +7656,7 @@ var SuiTradingClient = class {
7298
7656
  const context = {
7299
7657
  apiUser: this.apiUser,
7300
7658
  apiKey: this.apiKey,
7301
- tradeportRouterUrl: this.tradeportRouterUrl,
7659
+ defiRouterUrl: this.defiRouterUrl,
7302
7660
  suiClient: this.suiClient,
7303
7661
  kioskClient: this.kioskClient
7304
7662
  };
@@ -7318,7 +7676,7 @@ var SuiTradingClient = class {
7318
7676
  const context = {
7319
7677
  apiUser: this.apiUser,
7320
7678
  apiKey: this.apiKey,
7321
- tradeportRouterUrl: this.tradeportRouterUrl,
7679
+ defiRouterUrl: this.defiRouterUrl,
7322
7680
  suiClient: this.suiClient,
7323
7681
  kioskClient: this.kioskClient
7324
7682
  };
@@ -7331,7 +7689,7 @@ var SuiTradingClient = class {
7331
7689
  const context = {
7332
7690
  apiUser: this.apiUser,
7333
7691
  apiKey: this.apiKey,
7334
- tradeportRouterUrl: this.tradeportRouterUrl,
7692
+ defiRouterUrl: this.defiRouterUrl,
7335
7693
  suiClient: this.suiClient,
7336
7694
  kioskClient: this.kioskClient
7337
7695
  };
@@ -7344,13 +7702,17 @@ var SuiTradingClient = class {
7344
7702
  return cancelMultiBid(args);
7345
7703
  }
7346
7704
  async updateMultiBid(args) {
7347
- return updateMultiBid(args, {
7348
- suiClient: this.suiClient,
7349
- tradeportRouterUrl: this.tradeportRouterUrl
7350
- });
7705
+ return updateMultiBid(args);
7351
7706
  }
7352
7707
  async sponsorNftListing(args) {
7353
- return sponsorNftListing(args);
7708
+ const context = {
7709
+ apiUser: this.apiUser,
7710
+ apiKey: this.apiKey,
7711
+ defiRouterUrl: this.defiRouterUrl,
7712
+ suiClient: this.suiClient,
7713
+ kioskClient: this.kioskClient
7714
+ };
7715
+ return sponsorNftListing(args, context);
7354
7716
  }
7355
7717
  async applyFtStrategy(args) {
7356
7718
  return applyFtStrategy(args);
@@ -7358,6 +7720,15 @@ var SuiTradingClient = class {
7358
7720
  async applyTradeportNftStrategy(args) {
7359
7721
  return applyTradeportNftStrategy(args);
7360
7722
  }
7723
+ async swapCoins(args) {
7724
+ return swapCoins(args, { suiClient: this.suiClient, defiRouterUrl: this.defiRouterUrl });
7725
+ }
7726
+ async buildSwapRoutes(args) {
7727
+ return buildSwapRoutes(args, { defiRouterUrl: this.defiRouterUrl });
7728
+ }
7729
+ async calculateAmountToSwap(args) {
7730
+ return calculateAmountToSwap(args);
7731
+ }
7361
7732
  };
7362
7733
  var SuiTradingClient_default = SuiTradingClient;
7363
7734
  export {