@cetusprotocol/aggregator-sdk 0.4.1 → 0.4.3

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.
Files changed (103) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/package.json +1 -1
  4. package/.env.example +0 -4
  5. package/bun.lockb +0 -0
  6. package/dist/src/api.d.ts +0 -104
  7. package/dist/src/client.d.ts +0 -118
  8. package/dist/src/const.d.ts +0 -8
  9. package/dist/src/errors.d.ts +0 -40
  10. package/dist/src/index.d.ts +0 -9
  11. package/dist/src/math.d.ts +0 -6
  12. package/dist/src/transaction/afsui.d.ts +0 -10
  13. package/dist/src/transaction/aftermath.d.ts +0 -13
  14. package/dist/src/transaction/alphafi.d.ts +0 -7
  15. package/dist/src/transaction/bluefin.d.ts +0 -7
  16. package/dist/src/transaction/bluemove.d.ts +0 -7
  17. package/dist/src/transaction/cetus.d.ts +0 -15
  18. package/dist/src/transaction/deepbook_v2.d.ts +0 -14
  19. package/dist/src/transaction/deepbook_v3.d.ts +0 -12
  20. package/dist/src/transaction/flowx_v2.d.ts +0 -7
  21. package/dist/src/transaction/flowx_v3.d.ts +0 -8
  22. package/dist/src/transaction/haedal.d.ts +0 -6
  23. package/dist/src/transaction/haedal_pmm.d.ts +0 -7
  24. package/dist/src/transaction/index.d.ts +0 -10
  25. package/dist/src/transaction/kriya_v2.d.ts +0 -6
  26. package/dist/src/transaction/kriya_v3.d.ts +0 -7
  27. package/dist/src/transaction/metastable.d.ts +0 -8
  28. package/dist/src/transaction/obric.d.ts +0 -8
  29. package/dist/src/transaction/scallop.d.ts +0 -8
  30. package/dist/src/transaction/steamm.d.ts +0 -6
  31. package/dist/src/transaction/suilend.d.ts +0 -7
  32. package/dist/src/transaction/swap.d.ts +0 -4
  33. package/dist/src/transaction/turbos.d.ts +0 -7
  34. package/dist/src/transaction/volo.d.ts +0 -8
  35. package/dist/src/types/CoinAssist.d.ts +0 -122
  36. package/dist/src/types/sui.d.ts +0 -112
  37. package/dist/src/utils/api.d.ts +0 -1
  38. package/dist/src/utils/coin.d.ts +0 -11
  39. package/dist/src/utils/contracts.d.ts +0 -16
  40. package/dist/src/utils/index.d.ts +0 -5
  41. package/dist/src/utils/msafe.d.ts +0 -2
  42. package/dist/src/utils/transaction.d.ts +0 -3
  43. package/dist/tests/math.test.d.ts +0 -1
  44. package/dist/tests/router/alphafi.test.d.ts +0 -2
  45. package/dist/tests/router/metastable.test.d.ts +0 -2
  46. package/dist/tests/router/obric.test.d.ts +0 -2
  47. package/dist/tests/router/scallop.test.d.ts +0 -2
  48. package/dist/tests/router/steamm.test.d.ts +0 -2
  49. package/dist/tests/router.test.d.ts +0 -2
  50. package/dist/tests/test_data.test.d.ts +0 -18
  51. package/dist/tests/wallet.test.d.ts +0 -1
  52. package/example/package.json +0 -17
  53. package/example/swap.ts +0 -21
  54. package/example/tsconfig.json +0 -12
  55. package/jest.config.mjs +0 -13
  56. package/src/api.ts +0 -325
  57. package/src/client.ts +0 -1081
  58. package/src/const.ts +0 -15
  59. package/src/errors.ts +0 -77
  60. package/src/index.ts +0 -10
  61. package/src/math.ts +0 -66
  62. package/src/transaction/afsui.ts +0 -62
  63. package/src/transaction/aftermath.ts +0 -88
  64. package/src/transaction/alphafi.ts +0 -50
  65. package/src/transaction/bluefin.ts +0 -46
  66. package/src/transaction/bluemove.ts +0 -42
  67. package/src/transaction/cetus.ts +0 -118
  68. package/src/transaction/deepbook_v2.ts +0 -122
  69. package/src/transaction/deepbook_v3.ts +0 -60
  70. package/src/transaction/flowx_v2.ts +0 -42
  71. package/src/transaction/flowx_v3.ts +0 -52
  72. package/src/transaction/haedal.ts +0 -33
  73. package/src/transaction/haedal_pmm.ts +0 -80
  74. package/src/transaction/index.ts +0 -42
  75. package/src/transaction/kriya_v2.ts +0 -37
  76. package/src/transaction/kriya_v3.ts +0 -47
  77. package/src/transaction/metastable.ts +0 -141
  78. package/src/transaction/obric.ts +0 -90
  79. package/src/transaction/scallop.ts +0 -64
  80. package/src/transaction/steamm.ts +0 -77
  81. package/src/transaction/suilend.ts +0 -48
  82. package/src/transaction/swap.ts +0 -162
  83. package/src/transaction/turbos.ts +0 -56
  84. package/src/transaction/volo.ts +0 -53
  85. package/src/types/CoinAssist.ts +0 -217
  86. package/src/types/sui.ts +0 -148
  87. package/src/utils/api.ts +0 -6
  88. package/src/utils/coin.ts +0 -136
  89. package/src/utils/contracts.ts +0 -136
  90. package/src/utils/index.ts +0 -5
  91. package/src/utils/msafe.ts +0 -40
  92. package/src/utils/transaction.ts +0 -20
  93. package/tests/math.test.ts +0 -21
  94. package/tests/router/alphafi.test.ts +0 -132
  95. package/tests/router/metastable.test.ts +0 -383
  96. package/tests/router/obric.test.ts +0 -203
  97. package/tests/router/scallop.test.ts +0 -133
  98. package/tests/router/steamm.test.ts +0 -130
  99. package/tests/router.test.ts +0 -379
  100. package/tests/test_data.test.ts +0 -28
  101. package/tests/wallet.test.ts +0 -21
  102. package/tsup.config.ts +0 -23
  103. package/version.mjs +0 -28
@@ -1,77 +0,0 @@
1
- import {
2
- Transaction,
3
- TransactionObjectArgument,
4
- } from "@mysten/sui/transactions"
5
- import { AggregatorClient, CLOCK_ADDRESS, Dex, Env, getAggregatorV2ExtendPublishedAt, Path } from ".."
6
-
7
- export class Steamm implements Dex {
8
- constructor(env: Env) {
9
- if (env !== Env.Mainnet) {
10
- throw new Error("Steamm only supported on mainnet")
11
- }
12
- }
13
-
14
- async swap(
15
- client: AggregatorClient,
16
- txb: Transaction,
17
- path: Path,
18
- inputCoin: TransactionObjectArgument,
19
- packages?: Map<string, string>
20
- ): Promise<TransactionObjectArgument> {
21
- const { direction, from, target } = path
22
-
23
- const [func, coinAType, coinBType] = direction
24
- ? ["swap_a2b", from, target]
25
- : ["swap_b2a", target, from]
26
-
27
- if (path.extendedDetails == null) {
28
- throw new Error("Extended details not supported")
29
- } else {
30
- if (path.extendedDetails.steammBankA == null) {
31
- throw new Error("Steamm bank a type not supported")
32
- }
33
- if (path.extendedDetails.steammBankB == null) {
34
- throw new Error("Steamm bank b type not supported")
35
- }
36
- if (path.extendedDetails.steammLendingMarket == null) {
37
- throw new Error("Steamm lending market not supported")
38
- }
39
- if (path.extendedDetails.steammLendingMarketType == null) {
40
- throw new Error("Steamm lending market type not supported")
41
- }
42
- if (path.extendedDetails.steammBCoinAType == null) {
43
- throw new Error("Steamm b coin a type not supported")
44
- }
45
- if (path.extendedDetails.steammBCoinBType == null) {
46
- throw new Error("Steamm b coin b type not supported")
47
- }
48
- if (path.extendedDetails.steammLPToken == null) {
49
- throw new Error("Steamm lp token not supported")
50
- }
51
- }
52
-
53
- const args = [
54
- txb.object(path.id),
55
- txb.object(path.extendedDetails.steammBankA),
56
- txb.object(path.extendedDetails.steammBankB),
57
- txb.object(path.extendedDetails.steammLendingMarket),
58
- inputCoin,
59
- txb.object(CLOCK_ADDRESS),
60
- ]
61
- const publishedAt = getAggregatorV2ExtendPublishedAt(client.publishedAtV2Extend(), packages)
62
- const res = txb.moveCall({
63
- target: `${publishedAt}::steammfe::${func}`,
64
- typeArguments: [
65
- path.extendedDetails.steammLendingMarketType,
66
- coinAType,
67
- coinBType,
68
- path.extendedDetails.steammBCoinAType,
69
- path.extendedDetails.steammBCoinBType,
70
- path.extendedDetails.steammLPToken,
71
- ],
72
- arguments: args,
73
- }) as TransactionObjectArgument
74
-
75
- return res
76
- }
77
- }
@@ -1,48 +0,0 @@
1
- import {
2
- Transaction,
3
- TransactionObjectArgument,
4
- } from "@mysten/sui/transactions"
5
- import { AggregatorClient, Dex, Env, getAggregatorV2ExtendPublishedAt, Path } from ".."
6
-
7
- export class Suilend implements Dex {
8
- private sui_system_state: string
9
-
10
- constructor(env: Env) {
11
- if (env !== Env.Mainnet) {
12
- throw new Error("Suilend only supported on mainnet")
13
- }
14
-
15
- this.sui_system_state =
16
- env === Env.Mainnet
17
- ? "0x0000000000000000000000000000000000000000000000000000000000000005"
18
- : "0x0"
19
- }
20
-
21
- async swap(
22
- client: AggregatorClient,
23
- txb: Transaction,
24
- path: Path,
25
- inputCoin: TransactionObjectArgument,
26
- packages?: Map<string, string>
27
- ): Promise<TransactionObjectArgument> {
28
- const { direction, from, target } = path
29
-
30
- const [func, springCoinType] = direction
31
- ? ["swap_a2b", target]
32
- : ["swap_b2a", from]
33
-
34
- const args = [
35
- txb.object(path.id),
36
- txb.object(this.sui_system_state),
37
- inputCoin,
38
- ]
39
- const publishedAt = getAggregatorV2ExtendPublishedAt(client.publishedAtV2Extend(), packages)
40
- const res = txb.moveCall({
41
- target: `${publishedAt}::suilend::${func}`,
42
- typeArguments: [springCoinType],
43
- arguments: args,
44
- }) as TransactionObjectArgument
45
-
46
- return res
47
- }
48
- }
@@ -1,162 +0,0 @@
1
- import { Transaction } from "@mysten/sui/transactions"
2
- import { SwapInPoolsParams } from "~/client"
3
- import { compareCoins, completionCoin } from "~/utils/coin"
4
- import { Env, SwapInPoolsResult, U64_MAX_BN, ZERO } from ".."
5
- import { ConfigErrorCode, TransactionErrorCode } from "~/errors"
6
- import { checkInvalidSuiAddress, printTransaction } from "~/utils/transaction"
7
- import { SuiClient } from "@mysten/sui/client"
8
- import { BN } from "bn.js"
9
- import { sqrtPriceX64ToPrice } from "~/math"
10
-
11
- export async function swapInPools(
12
- client: SuiClient,
13
- params: SwapInPoolsParams,
14
- sender: string,
15
- env: Env
16
- ): Promise<SwapInPoolsResult> {
17
- const { from, target, amount, byAmountIn, pools } = params
18
- const fromCoin = completionCoin(from)
19
- const targetCoin = completionCoin(target)
20
-
21
- const tx = new Transaction()
22
- const direction = compareCoins(fromCoin, targetCoin)
23
- const integratePublishedAt = env === Env.Mainnet ?
24
- "0x2d8c2e0fc6dd25b0214b3fa747e0fd27fd54608142cd2e4f64c1cd350cc4add4" :
25
- "0x4f920e1ef6318cfba77e20a0538a419a5a504c14230169438b99aba485db40a6"
26
- const coinA = direction ? fromCoin : targetCoin
27
- const coinB = direction ? targetCoin : fromCoin
28
-
29
- const typeArguments = [coinA, coinB]
30
-
31
- for (let i = 0; i < pools.length; i++) {
32
- const args = [
33
- tx.object(pools[i]),
34
- tx.pure.bool(direction),
35
- tx.pure.bool(byAmountIn),
36
- tx.pure.u64(amount.toString()),
37
- ]
38
- tx.moveCall({
39
- target: `${integratePublishedAt}::fetcher_script::calculate_swap_result`,
40
- arguments: args,
41
- typeArguments,
42
- })
43
- }
44
-
45
- if (!checkInvalidSuiAddress(sender)) {
46
- throw new AggregateError(
47
- "Aggregator package not set",
48
- ConfigErrorCode.InvalidWallet
49
- )
50
- }
51
-
52
- const simulateRes = await client.devInspectTransactionBlock({
53
- transactionBlock: tx,
54
- sender,
55
- })
56
- if (simulateRes.error != null) {
57
- console.log("simulateRes.error", simulateRes.error)
58
- throw new AggregateError(
59
- "Aggregator package not set",
60
- ConfigErrorCode.SimulateError
61
- )
62
- }
63
-
64
- const valueData: any = simulateRes.events?.filter((item: any) => {
65
- return item.type.includes("CalculatedSwapResultEvent")
66
- })
67
-
68
- if (valueData.length === 0 || valueData.length !== pools.length) {
69
- throw new AggregateError(
70
- "Simulate event result error",
71
- TransactionErrorCode.SimulateEventError
72
- )
73
- }
74
-
75
- let tempMaxAmount = byAmountIn ? ZERO : U64_MAX_BN
76
- let tempIndex = 0
77
- for (let i = 0; i < valueData.length; i += 1) {
78
- if (valueData[i].parsedJson.data.is_exceed) {
79
- continue
80
- }
81
-
82
- if (params.byAmountIn) {
83
- const amount = new BN(valueData[i].parsedJson.data.amount_out)
84
- if (amount.gt(tempMaxAmount)) {
85
- tempIndex = i
86
- tempMaxAmount = amount
87
- }
88
- } else {
89
- const amount = new BN(valueData[i].parsedJson.data.amount_out)
90
- if (amount.lt(tempMaxAmount)) {
91
- tempIndex = i
92
- tempMaxAmount = amount
93
- }
94
- }
95
- }
96
-
97
- const event = valueData[tempIndex].parsedJson.data
98
-
99
- const currentSqrtPrice = event.step_results[0].current_sqrt_price
100
-
101
- const [decimalA, decimalB] = await Promise.all([
102
- client
103
- .getCoinMetadata({ coinType: coinA })
104
- .then((metadata) => metadata?.decimals),
105
- client
106
- .getCoinMetadata({ coinType: coinB })
107
- .then((metadata) => metadata?.decimals),
108
- ])
109
-
110
- if (decimalA == null || decimalB == null) {
111
- throw new AggregateError(
112
- "Simulate event result error",
113
- TransactionErrorCode.CannotGetDecimals
114
- )
115
- }
116
- const initialPrice = sqrtPriceX64ToPrice(
117
- currentSqrtPrice,
118
- decimalA!,
119
- decimalB!
120
- )
121
-
122
- const feeRate = Number(event.fee_rate) / 1000000
123
- const pureAmountIn = new BN(event.amount_in ?? 0)
124
- const feeAmount = new BN(event.fee_amount ?? 0)
125
- const amountIn = pureAmountIn.add(feeAmount)
126
-
127
- const routeData = {
128
- amountIn: amountIn,
129
- amountOut: new BN(event.amount_out ?? 0),
130
- routes: [
131
- {
132
- path: [
133
- {
134
- id: pools[tempIndex],
135
- direction,
136
- provider: "CETUS",
137
- from: fromCoin,
138
- target: targetCoin,
139
- feeRate,
140
- amountIn: event.amount_in,
141
- amountOut: event.amount_out,
142
- extendedDetails: {
143
- afterSqrtPrice: event.after_sqrt_price,
144
- },
145
- },
146
- ],
147
- amountIn: amountIn,
148
- amountOut: new BN(event.amount_out ?? 0),
149
- initialPrice,
150
- },
151
- ],
152
- insufficientLiquidity: false,
153
- byAmountIn: params.byAmountIn,
154
- }
155
-
156
- const result = {
157
- isExceed: event.is_exceed,
158
- routeData,
159
- }
160
-
161
- return result
162
- }
@@ -1,56 +0,0 @@
1
- import {
2
- Transaction,
3
- TransactionArgument,
4
- TransactionObjectArgument,
5
- } from "@mysten/sui/transactions"
6
- import { AggregatorClient, CLOCK_ADDRESS, Dex, Env, getAggregatorV2PublishedAt, Path } from ".."
7
-
8
- export class Turbos implements Dex {
9
- private versioned: string
10
-
11
- constructor(env: Env) {
12
- if (env !== Env.Mainnet) {
13
- throw new Error("Turbos only supported on mainnet")
14
- }
15
-
16
- this.versioned =
17
- "0xf1cf0e81048df168ebeb1b8030fad24b3e0b53ae827c25053fff0779c1445b6f"
18
- }
19
-
20
- async swap(
21
- client: AggregatorClient,
22
- txb: Transaction,
23
- path: Path,
24
- inputCoin: TransactionObjectArgument,
25
- packages?: Map<string, string>
26
- ): Promise<TransactionObjectArgument> {
27
- const { direction, from, target } = path
28
-
29
- const [func, coinAType, coinBType] = direction
30
- ? ["swap_a2b", from, target]
31
- : ["swap_b2a", target, from]
32
-
33
- if (path.extendedDetails == null) {
34
- throw new Error("Extended details not supported")
35
- } else {
36
- if (path.extendedDetails.turbosFeeType == null) {
37
- throw new Error("Turbos fee type not supported")
38
- }
39
- }
40
-
41
- const args = [
42
- txb.object(path.id),
43
- inputCoin,
44
- txb.object(CLOCK_ADDRESS),
45
- txb.object(this.versioned),
46
- ]
47
- const publishedAt = getAggregatorV2PublishedAt(client.publishedAtV2(), packages)
48
- const res = txb.moveCall({
49
- target: `${publishedAt}::turbos::${func}`,
50
- typeArguments: [coinAType, coinBType, path.extendedDetails.turbosFeeType],
51
- arguments: args,
52
- }) as TransactionObjectArgument
53
-
54
- return res
55
- }
56
- }
@@ -1,53 +0,0 @@
1
- import {
2
- Transaction,
3
- TransactionObjectArgument,
4
- } from "@mysten/sui/transactions"
5
- import { AggregatorClient, Dex, Env, getAggregatorV2PublishedAt, Path } from ".."
6
-
7
- export class Volo implements Dex {
8
- private nativePool: string
9
- private metadata: string
10
-
11
- constructor(env: Env) {
12
- if (env !== Env.Mainnet) {
13
- throw new Error("Volo only supported on mainnet")
14
- }
15
-
16
- this.nativePool =
17
- "0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf"
18
- this.metadata =
19
- "0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60"
20
- }
21
-
22
- async swap(
23
- client: AggregatorClient,
24
- txb: Transaction,
25
- path: Path,
26
- inputCoin: TransactionObjectArgument,
27
- packages?: Map<string, string>
28
- ): Promise<TransactionObjectArgument> {
29
- const { direction } = path
30
-
31
- if (!direction) {
32
- throw new Error("Volo not support b2a swap")
33
- }
34
-
35
- const func = "swap_a2b"
36
-
37
- const args = [
38
- txb.object(this.nativePool),
39
- txb.object(this.metadata),
40
- txb.object("0x5"),
41
- inputCoin,
42
- ]
43
-
44
- const publishedAt = getAggregatorV2PublishedAt(client.publishedAtV2(), packages)
45
- const res = txb.moveCall({
46
- target: `${publishedAt}::volo::${func}`,
47
- typeArguments: [],
48
- arguments: args,
49
- }) as TransactionObjectArgument
50
-
51
- return res
52
- }
53
- }
@@ -1,217 +0,0 @@
1
- import type { SuiMoveObject } from '@mysten/sui/client'
2
- import type { CoinAsset, SuiAddress } from './sui'
3
- import { extractStructTagFromType, normalizeCoinType } from '../utils/contracts'
4
-
5
- const COIN_TYPE = '0x2::coin::Coin'
6
- const COIN_TYPE_ARG_REGEX = /^0x2::coin::Coin<(.+)>$/
7
-
8
- export const DEFAULT_GAS_BUDGET_FOR_SPLIT = 1000
9
- export const DEFAULT_GAS_BUDGET_FOR_MERGE = 500
10
- export const DEFAULT_GAS_BUDGET_FOR_TRANSFER = 100
11
- export const DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI = 100
12
- export const DEFAULT_GAS_BUDGET_FOR_STAKE = 1000
13
- export const GAS_TYPE_ARG = '0x2::sui::SUI'
14
- export const GAS_TYPE_ARG_LONG = '0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI'
15
- export const GAS_SYMBOL = 'SUI'
16
- export const DEFAULT_NFT_TRANSFER_GAS_FEE = 450
17
- export const SUI_SYSTEM_STATE_OBJECT_ID = '0x0000000000000000000000000000000000000005'
18
-
19
- /**
20
- * This class provides helper methods for working with coins.
21
- */
22
- export class CoinUtils {
23
- /**
24
- * Get the coin type argument from a SuiMoveObject.
25
- *
26
- * @param obj The SuiMoveObject to get the coin type argument from.
27
- * @returns The coin type argument, or null if it is not found.
28
- */
29
- public static getCoinTypeArg(obj: SuiMoveObject) {
30
- const res = obj.type.match(COIN_TYPE_ARG_REGEX)
31
- return res ? res[1] : null
32
- }
33
-
34
- /**
35
- * Get whether a SuiMoveObject is a SUI coin.
36
- *
37
- * @param obj The SuiMoveObject to check.
38
- * @returns Whether the SuiMoveObject is a SUI coin.
39
- */
40
- public static isSUI(obj: SuiMoveObject) {
41
- const arg = CoinUtils.getCoinTypeArg(obj)
42
- return arg ? CoinUtils.getCoinSymbol(arg) === 'SUI' : false
43
- }
44
-
45
- /**
46
- * Get the coin symbol from a coin type argument.
47
- *
48
- * @param coinTypeArg The coin type argument to get the symbol from.
49
- * @returns The coin symbol.
50
- */
51
- public static getCoinSymbol(coinTypeArg: string) {
52
- return coinTypeArg.substring(coinTypeArg.lastIndexOf(':') + 1)
53
- }
54
-
55
- /**
56
- * Get the balance of a SuiMoveObject.
57
- *
58
- * @param obj The SuiMoveObject to get the balance from.
59
- * @returns The balance of the SuiMoveObject.
60
- */
61
- public static getBalance(obj: SuiMoveObject): bigint {
62
- return BigInt((obj.fields as any).balance)
63
- }
64
-
65
- /**
66
- * Get the total balance of a list of CoinAsset objects for a given coin address.
67
- *
68
- * @param objs The list of CoinAsset objects to get the total balance for.
69
- * @param coinAddress The coin address to get the total balance for.
70
- * @returns The total balance of the CoinAsset objects for the given coin address.
71
- */
72
- public static totalBalance(objs: CoinAsset[], coinAddress: SuiAddress): bigint {
73
- let balanceTotal = BigInt(0)
74
- objs.forEach((obj) => {
75
- if (coinAddress === obj.coinAddress) {
76
- balanceTotal += BigInt(obj.balance)
77
- }
78
- })
79
- return balanceTotal
80
- }
81
-
82
- /**
83
- * Get the ID of a SuiMoveObject.
84
- *
85
- * @param obj The SuiMoveObject to get the ID from.
86
- * @returns The ID of the SuiMoveObject.
87
- */
88
- public static getID(obj: SuiMoveObject): string {
89
- return (obj.fields as any).id.id
90
- }
91
-
92
- /**
93
- * Get the coin type from a coin type argument.
94
- *
95
- * @param coinTypeArg The coin type argument to get the coin type from.
96
- * @returns The coin type.
97
- */
98
- public static getCoinTypeFromArg(coinTypeArg: string) {
99
- return `${COIN_TYPE}<${coinTypeArg}>`
100
- }
101
-
102
- /**
103
- * Get the CoinAsset objects for a given coin type.
104
- *
105
- * @param coinType The coin type to get the CoinAsset objects for.
106
- * @param allSuiObjects The list of all SuiMoveObjects.
107
- * @returns The CoinAsset objects for the given coin type.
108
- */
109
- public static getCoinAssets(coinType: string, allSuiObjects: CoinAsset[]): CoinAsset[] {
110
- const coins: CoinAsset[] = []
111
- allSuiObjects.forEach((anObj) => {
112
- if (normalizeCoinType(anObj.coinAddress) === normalizeCoinType(coinType)) {
113
- coins.push(anObj)
114
- }
115
- })
116
- return coins
117
- }
118
-
119
- /**
120
- * Get whether a coin address is a SUI coin.
121
- *
122
- * @param coinAddress The coin address to check.
123
- * @returns Whether the coin address is a SUI coin.
124
- */
125
- public static isSuiCoin(coinAddress: SuiAddress) {
126
- return extractStructTagFromType(coinAddress).full_address === GAS_TYPE_ARG
127
- }
128
-
129
- /**
130
- * Select the CoinAsset objects from a list of CoinAsset objects that have a balance greater than or equal to a given amount.
131
- *
132
- * @param coins The list of CoinAsset objects to select from.
133
- * @param amount The amount to select CoinAsset objects with a balance greater than or equal to.
134
- * @param exclude A list of CoinAsset objects to exclude from the selection.
135
- * @returns The CoinAsset objects that have a balance greater than or equal to the given amount.
136
- */
137
- static selectCoinObjectIdGreaterThanOrEqual(
138
- coins: CoinAsset[],
139
- amount: bigint,
140
- exclude: string[] = []
141
- ): { objectArray: string[]; remainCoins: CoinAsset[]; amountArray: string[] } {
142
- const selectedResult = CoinUtils.selectCoinAssetGreaterThanOrEqual(coins, amount, exclude)
143
- const objectArray = selectedResult.selectedCoins.map((item) => item.coinObjectId)
144
- const remainCoins = selectedResult.remainingCoins
145
- const amountArray = selectedResult.selectedCoins.map((item) => item.balance.toString())
146
- return { objectArray, remainCoins, amountArray }
147
- }
148
-
149
- /**
150
- * Select the CoinAsset objects from a list of CoinAsset objects that have a balance greater than or equal to a given amount.
151
- *
152
- * @param coins The list of CoinAsset objects to select from.
153
- * @param amount The amount to select CoinAsset objects with a balance greater than or equal to.
154
- * @param exclude A list of CoinAsset objects to exclude from the selection.
155
- * @returns The CoinAsset objects that have a balance greater than or equal to the given amount.
156
- */
157
- static selectCoinAssetGreaterThanOrEqual(
158
- coins: CoinAsset[],
159
- amount: bigint,
160
- exclude: string[] = []
161
- ): { selectedCoins: CoinAsset[]; remainingCoins: CoinAsset[] } {
162
- const sortedCoins = CoinUtils.sortByBalance(coins.filter((c) => !exclude.includes(c.coinObjectId)))
163
-
164
- const total = CoinUtils.calculateTotalBalance(sortedCoins)
165
-
166
- if (total < amount) {
167
- return { selectedCoins: [], remainingCoins: sortedCoins }
168
- }
169
- if (total === amount) {
170
- return { selectedCoins: sortedCoins, remainingCoins: [] }
171
- }
172
-
173
- let sum = BigInt(0)
174
- const selectedCoins = []
175
- const remainingCoins = [...sortedCoins]
176
- while (sum < total) {
177
- const target = amount - sum
178
- const coinWithSmallestSufficientBalanceIndex = remainingCoins.findIndex((c) => c.balance >= target)
179
- if (coinWithSmallestSufficientBalanceIndex !== -1) {
180
- selectedCoins.push(remainingCoins[coinWithSmallestSufficientBalanceIndex])
181
- remainingCoins.splice(coinWithSmallestSufficientBalanceIndex, 1)
182
- break
183
- }
184
-
185
- const coinWithLargestBalance = remainingCoins.pop()!
186
- if (coinWithLargestBalance.balance > 0) {
187
- selectedCoins.push(coinWithLargestBalance)
188
- sum += coinWithLargestBalance.balance
189
- }
190
- }
191
- return { selectedCoins: CoinUtils.sortByBalance(selectedCoins), remainingCoins: CoinUtils.sortByBalance(remainingCoins) }
192
- }
193
-
194
- /**
195
- * Sort the CoinAsset objects by their balance.
196
- *
197
- * @param coins The CoinAsset objects to sort.
198
- * @returns The sorted CoinAsset objects.
199
- */
200
- static sortByBalance(coins: CoinAsset[]): CoinAsset[] {
201
- return coins.sort((a, b) => (a.balance < b.balance ? -1 : a.balance > b.balance ? 1 : 0))
202
- }
203
-
204
- static sortByBalanceDes(coins: CoinAsset[]): CoinAsset[] {
205
- return coins.sort((a, b) => (a.balance > b.balance ? -1 : a.balance < b.balance ? 0 : 1))
206
- }
207
-
208
- /**
209
- * Calculate the total balance of a list of CoinAsset objects.
210
- *
211
- * @param coins The list of CoinAsset objects to calculate the total balance for.
212
- * @returns The total balance of the CoinAsset objects.
213
- */
214
- static calculateTotalBalance(coins: CoinAsset[]): bigint {
215
- return coins.reduce((partialSum, c) => partialSum + c.balance, BigInt(0))
216
- }
217
- }