@7kprotocol/sdk-ts 3.6.1-beta.0 → 3.6.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/README.md +13 -10
  2. package/dist/bluefin7k-I6ZCDWDN.js +2 -0
  3. package/dist/bluefin7k-I6ZCDWDN.js.map +1 -0
  4. package/dist/bluefin7k-TERLUCNL.mjs +2 -0
  5. package/dist/bluefin7k-TERLUCNL.mjs.map +1 -0
  6. package/dist/cetus-AU3OMWOY.mjs +2 -0
  7. package/dist/cetus-AU3OMWOY.mjs.map +1 -0
  8. package/dist/cetus-SIPX6FYL.js +2 -0
  9. package/dist/cetus-SIPX6FYL.js.map +1 -0
  10. package/dist/chunk-ETQEI4QC.mjs +2 -0
  11. package/dist/chunk-ETQEI4QC.mjs.map +1 -0
  12. package/dist/chunk-KVGSSW22.js +2 -0
  13. package/dist/chunk-KVGSSW22.js.map +1 -0
  14. package/dist/flowx-6M54WFWO.js +2 -0
  15. package/dist/flowx-6M54WFWO.js.map +1 -0
  16. package/dist/flowx-OXZZX5FD.mjs +2 -0
  17. package/dist/flowx-OXZZX5FD.mjs.map +1 -0
  18. package/dist/index.d.mts +536 -0
  19. package/dist/index.d.ts +536 -0
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/index.mjs +2 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/package.json +12 -20
  25. package/lib/cjs/config/fetchClient.js +0 -12
  26. package/lib/cjs/constants/_7k.js +0 -20
  27. package/lib/cjs/constants/apiEndpoints.js +0 -9
  28. package/lib/cjs/constants/sui.js +0 -4
  29. package/lib/cjs/constants/tokens.js +0 -7
  30. package/lib/cjs/features/limitDca/cancelDcaOrder.js +0 -14
  31. package/lib/cjs/features/limitDca/cancelLimitOrder.js +0 -14
  32. package/lib/cjs/features/limitDca/claimExpiredLimitOrder.js +0 -14
  33. package/lib/cjs/features/limitDca/constants.js +0 -13
  34. package/lib/cjs/features/limitDca/getClosedDcaOrders.js +0 -23
  35. package/lib/cjs/features/limitDca/getClosedLimitOrders.js +0 -22
  36. package/lib/cjs/features/limitDca/getDcaOrderExecutions.js +0 -23
  37. package/lib/cjs/features/limitDca/getOpenDcaOrders.js +0 -22
  38. package/lib/cjs/features/limitDca/getOpenLimitOrders.js +0 -22
  39. package/lib/cjs/features/limitDca/index.js +0 -26
  40. package/lib/cjs/features/limitDca/placeDcaOrder.js +0 -33
  41. package/lib/cjs/features/limitDca/placeLimitOrder.js +0 -27
  42. package/lib/cjs/features/limitDca/types.js +0 -16
  43. package/lib/cjs/features/metaAg/common.js +0 -103
  44. package/lib/cjs/features/metaAg/error.js +0 -31
  45. package/lib/cjs/features/metaAg/index.js +0 -268
  46. package/lib/cjs/features/metaAg/providers/bluefin7k.js +0 -57
  47. package/lib/cjs/features/metaAg/providers/cetus.js +0 -59
  48. package/lib/cjs/features/metaAg/providers/flowx.js +0 -52
  49. package/lib/cjs/features/metaAg/providers/okx.js +0 -182
  50. package/lib/cjs/features/prices/index.js +0 -99
  51. package/lib/cjs/index.js +0 -55
  52. package/lib/cjs/libs/url.js +0 -17
  53. package/lib/cjs/types/config/fetchClient.d.ts +0 -2
  54. package/lib/cjs/types/config/fetchClient.d.ts.map +0 -1
  55. package/lib/cjs/types/constants/_7k.d.ts +0 -6
  56. package/lib/cjs/types/constants/_7k.d.ts.map +0 -1
  57. package/lib/cjs/types/constants/apiEndpoints.d.ts +0 -7
  58. package/lib/cjs/types/constants/apiEndpoints.d.ts.map +0 -1
  59. package/lib/cjs/types/constants/sui.d.ts +0 -2
  60. package/lib/cjs/types/constants/sui.d.ts.map +0 -1
  61. package/lib/cjs/types/constants/tokens.d.ts +0 -5
  62. package/lib/cjs/types/constants/tokens.d.ts.map +0 -1
  63. package/lib/cjs/types/features/limitDca/cancelDcaOrder.d.ts +0 -9
  64. package/lib/cjs/types/features/limitDca/cancelDcaOrder.d.ts.map +0 -1
  65. package/lib/cjs/types/features/limitDca/cancelLimitOrder.d.ts +0 -9
  66. package/lib/cjs/types/features/limitDca/cancelLimitOrder.d.ts.map +0 -1
  67. package/lib/cjs/types/features/limitDca/claimExpiredLimitOrder.d.ts +0 -9
  68. package/lib/cjs/types/features/limitDca/claimExpiredLimitOrder.d.ts.map +0 -1
  69. package/lib/cjs/types/features/limitDca/constants.d.ts +0 -10
  70. package/lib/cjs/types/features/limitDca/constants.d.ts.map +0 -1
  71. package/lib/cjs/types/features/limitDca/getClosedDcaOrders.d.ts +0 -10
  72. package/lib/cjs/types/features/limitDca/getClosedDcaOrders.d.ts.map +0 -1
  73. package/lib/cjs/types/features/limitDca/getClosedLimitOrders.d.ts +0 -10
  74. package/lib/cjs/types/features/limitDca/getClosedLimitOrders.d.ts.map +0 -1
  75. package/lib/cjs/types/features/limitDca/getDcaOrderExecutions.d.ts +0 -10
  76. package/lib/cjs/types/features/limitDca/getDcaOrderExecutions.d.ts.map +0 -1
  77. package/lib/cjs/types/features/limitDca/getOpenDcaOrders.d.ts +0 -10
  78. package/lib/cjs/types/features/limitDca/getOpenDcaOrders.d.ts.map +0 -1
  79. package/lib/cjs/types/features/limitDca/getOpenLimitOrders.d.ts +0 -10
  80. package/lib/cjs/types/features/limitDca/getOpenLimitOrders.d.ts.map +0 -1
  81. package/lib/cjs/types/features/limitDca/index.d.ts +0 -11
  82. package/lib/cjs/types/features/limitDca/index.d.ts.map +0 -1
  83. package/lib/cjs/types/features/limitDca/placeDcaOrder.d.ts +0 -14
  84. package/lib/cjs/types/features/limitDca/placeDcaOrder.d.ts.map +0 -1
  85. package/lib/cjs/types/features/limitDca/placeLimitOrder.d.ts +0 -13
  86. package/lib/cjs/types/features/limitDca/placeLimitOrder.d.ts.map +0 -1
  87. package/lib/cjs/types/features/limitDca/types.d.ts +0 -98
  88. package/lib/cjs/types/features/limitDca/types.d.ts.map +0 -1
  89. package/lib/cjs/types/features/metaAg/common.d.ts +0 -24
  90. package/lib/cjs/types/features/metaAg/common.d.ts.map +0 -1
  91. package/lib/cjs/types/features/metaAg/error.d.ts +0 -54
  92. package/lib/cjs/types/features/metaAg/error.d.ts.map +0 -1
  93. package/lib/cjs/types/features/metaAg/index.d.ts +0 -42
  94. package/lib/cjs/types/features/metaAg/index.d.ts.map +0 -1
  95. package/lib/cjs/types/features/metaAg/providers/bluefin7k.d.ts +0 -11
  96. package/lib/cjs/types/features/metaAg/providers/bluefin7k.d.ts.map +0 -1
  97. package/lib/cjs/types/features/metaAg/providers/cetus.d.ts +0 -11
  98. package/lib/cjs/types/features/metaAg/providers/cetus.d.ts.map +0 -1
  99. package/lib/cjs/types/features/metaAg/providers/flowx.d.ts +0 -13
  100. package/lib/cjs/types/features/metaAg/providers/flowx.d.ts.map +0 -1
  101. package/lib/cjs/types/features/metaAg/providers/okx.d.ts +0 -21
  102. package/lib/cjs/types/features/metaAg/providers/okx.d.ts.map +0 -1
  103. package/lib/cjs/types/features/prices/index.d.ts +0 -18
  104. package/lib/cjs/types/features/prices/index.d.ts.map +0 -1
  105. package/lib/cjs/types/index.d.ts +0 -23
  106. package/lib/cjs/types/index.d.ts.map +0 -1
  107. package/lib/cjs/types/libs/url.d.ts +0 -2
  108. package/lib/cjs/types/libs/url.d.ts.map +0 -1
  109. package/lib/cjs/types/metaAg.js +0 -16
  110. package/lib/cjs/types/okx.js +0 -6
  111. package/lib/cjs/types/types/metaAg.d.ts +0 -165
  112. package/lib/cjs/types/types/metaAg.d.ts.map +0 -1
  113. package/lib/cjs/types/types/okx.d.ts +0 -206
  114. package/lib/cjs/types/types/okx.d.ts.map +0 -1
  115. package/lib/cjs/types/utils/ObjectCache.d.ts +0 -87
  116. package/lib/cjs/types/utils/ObjectCache.d.ts.map +0 -1
  117. package/lib/cjs/types/utils/SuiClientUtils.d.ts +0 -15
  118. package/lib/cjs/types/utils/SuiClientUtils.d.ts.map +0 -1
  119. package/lib/cjs/types/utils/sui.d.ts +0 -27
  120. package/lib/cjs/types/utils/sui.d.ts.map +0 -1
  121. package/lib/cjs/types/utils/swap.d.ts +0 -15
  122. package/lib/cjs/types/utils/swap.d.ts.map +0 -1
  123. package/lib/cjs/types/utils/token.d.ts +0 -4
  124. package/lib/cjs/types/utils/token.d.ts.map +0 -1
  125. package/lib/cjs/utils/ObjectCache.js +0 -273
  126. package/lib/cjs/utils/SuiClientUtils.js +0 -50
  127. package/lib/cjs/utils/sui.js +0 -92
  128. package/lib/cjs/utils/swap.js +0 -37
  129. package/lib/cjs/utils/token.js +0 -15
  130. package/lib/esm/config/fetchClient.js +0 -9
  131. package/lib/esm/constants/_7k.js +0 -17
  132. package/lib/esm/constants/apiEndpoints.js +0 -6
  133. package/lib/esm/constants/sui.js +0 -1
  134. package/lib/esm/constants/tokens.js +0 -4
  135. package/lib/esm/features/limitDca/cancelDcaOrder.js +0 -11
  136. package/lib/esm/features/limitDca/cancelLimitOrder.js +0 -11
  137. package/lib/esm/features/limitDca/claimExpiredLimitOrder.js +0 -11
  138. package/lib/esm/features/limitDca/constants.js +0 -10
  139. package/lib/esm/features/limitDca/getClosedDcaOrders.js +0 -20
  140. package/lib/esm/features/limitDca/getClosedLimitOrders.js +0 -19
  141. package/lib/esm/features/limitDca/getDcaOrderExecutions.js +0 -20
  142. package/lib/esm/features/limitDca/getOpenDcaOrders.js +0 -19
  143. package/lib/esm/features/limitDca/getOpenLimitOrders.js +0 -19
  144. package/lib/esm/features/limitDca/index.js +0 -10
  145. package/lib/esm/features/limitDca/placeDcaOrder.js +0 -30
  146. package/lib/esm/features/limitDca/placeLimitOrder.js +0 -24
  147. package/lib/esm/features/limitDca/types.js +0 -13
  148. package/lib/esm/features/metaAg/common.js +0 -96
  149. package/lib/esm/features/metaAg/error.js +0 -29
  150. package/lib/esm/features/metaAg/index.js +0 -234
  151. package/lib/esm/features/metaAg/providers/bluefin7k.js +0 -55
  152. package/lib/esm/features/metaAg/providers/cetus.js +0 -57
  153. package/lib/esm/features/metaAg/providers/flowx.js +0 -51
  154. package/lib/esm/features/metaAg/providers/okx.js +0 -147
  155. package/lib/esm/features/prices/index.js +0 -94
  156. package/lib/esm/index.mjs +0 -31
  157. package/lib/esm/libs/url.js +0 -14
  158. package/lib/esm/types/config/fetchClient.d.ts +0 -2
  159. package/lib/esm/types/config/fetchClient.d.ts.map +0 -1
  160. package/lib/esm/types/constants/_7k.d.ts +0 -6
  161. package/lib/esm/types/constants/_7k.d.ts.map +0 -1
  162. package/lib/esm/types/constants/apiEndpoints.d.ts +0 -7
  163. package/lib/esm/types/constants/apiEndpoints.d.ts.map +0 -1
  164. package/lib/esm/types/constants/sui.d.ts +0 -2
  165. package/lib/esm/types/constants/sui.d.ts.map +0 -1
  166. package/lib/esm/types/constants/tokens.d.ts +0 -5
  167. package/lib/esm/types/constants/tokens.d.ts.map +0 -1
  168. package/lib/esm/types/features/limitDca/cancelDcaOrder.d.ts +0 -9
  169. package/lib/esm/types/features/limitDca/cancelDcaOrder.d.ts.map +0 -1
  170. package/lib/esm/types/features/limitDca/cancelLimitOrder.d.ts +0 -9
  171. package/lib/esm/types/features/limitDca/cancelLimitOrder.d.ts.map +0 -1
  172. package/lib/esm/types/features/limitDca/claimExpiredLimitOrder.d.ts +0 -9
  173. package/lib/esm/types/features/limitDca/claimExpiredLimitOrder.d.ts.map +0 -1
  174. package/lib/esm/types/features/limitDca/constants.d.ts +0 -10
  175. package/lib/esm/types/features/limitDca/constants.d.ts.map +0 -1
  176. package/lib/esm/types/features/limitDca/getClosedDcaOrders.d.ts +0 -10
  177. package/lib/esm/types/features/limitDca/getClosedDcaOrders.d.ts.map +0 -1
  178. package/lib/esm/types/features/limitDca/getClosedLimitOrders.d.ts +0 -10
  179. package/lib/esm/types/features/limitDca/getClosedLimitOrders.d.ts.map +0 -1
  180. package/lib/esm/types/features/limitDca/getDcaOrderExecutions.d.ts +0 -10
  181. package/lib/esm/types/features/limitDca/getDcaOrderExecutions.d.ts.map +0 -1
  182. package/lib/esm/types/features/limitDca/getOpenDcaOrders.d.ts +0 -10
  183. package/lib/esm/types/features/limitDca/getOpenDcaOrders.d.ts.map +0 -1
  184. package/lib/esm/types/features/limitDca/getOpenLimitOrders.d.ts +0 -10
  185. package/lib/esm/types/features/limitDca/getOpenLimitOrders.d.ts.map +0 -1
  186. package/lib/esm/types/features/limitDca/index.d.ts +0 -11
  187. package/lib/esm/types/features/limitDca/index.d.ts.map +0 -1
  188. package/lib/esm/types/features/limitDca/placeDcaOrder.d.ts +0 -14
  189. package/lib/esm/types/features/limitDca/placeDcaOrder.d.ts.map +0 -1
  190. package/lib/esm/types/features/limitDca/placeLimitOrder.d.ts +0 -13
  191. package/lib/esm/types/features/limitDca/placeLimitOrder.d.ts.map +0 -1
  192. package/lib/esm/types/features/limitDca/types.d.ts +0 -98
  193. package/lib/esm/types/features/limitDca/types.d.ts.map +0 -1
  194. package/lib/esm/types/features/metaAg/common.d.ts +0 -24
  195. package/lib/esm/types/features/metaAg/common.d.ts.map +0 -1
  196. package/lib/esm/types/features/metaAg/error.d.ts +0 -54
  197. package/lib/esm/types/features/metaAg/error.d.ts.map +0 -1
  198. package/lib/esm/types/features/metaAg/index.d.ts +0 -42
  199. package/lib/esm/types/features/metaAg/index.d.ts.map +0 -1
  200. package/lib/esm/types/features/metaAg/providers/bluefin7k.d.ts +0 -11
  201. package/lib/esm/types/features/metaAg/providers/bluefin7k.d.ts.map +0 -1
  202. package/lib/esm/types/features/metaAg/providers/cetus.d.ts +0 -11
  203. package/lib/esm/types/features/metaAg/providers/cetus.d.ts.map +0 -1
  204. package/lib/esm/types/features/metaAg/providers/flowx.d.ts +0 -13
  205. package/lib/esm/types/features/metaAg/providers/flowx.d.ts.map +0 -1
  206. package/lib/esm/types/features/metaAg/providers/okx.d.ts +0 -21
  207. package/lib/esm/types/features/metaAg/providers/okx.d.ts.map +0 -1
  208. package/lib/esm/types/features/prices/index.d.ts +0 -18
  209. package/lib/esm/types/features/prices/index.d.ts.map +0 -1
  210. package/lib/esm/types/index.d.ts +0 -23
  211. package/lib/esm/types/index.d.ts.map +0 -1
  212. package/lib/esm/types/libs/url.d.ts +0 -2
  213. package/lib/esm/types/libs/url.d.ts.map +0 -1
  214. package/lib/esm/types/metaAg.js +0 -11
  215. package/lib/esm/types/okx.js +0 -5
  216. package/lib/esm/types/types/metaAg.d.ts +0 -165
  217. package/lib/esm/types/types/metaAg.d.ts.map +0 -1
  218. package/lib/esm/types/types/okx.d.ts +0 -206
  219. package/lib/esm/types/types/okx.d.ts.map +0 -1
  220. package/lib/esm/types/utils/ObjectCache.d.ts +0 -87
  221. package/lib/esm/types/utils/ObjectCache.d.ts.map +0 -1
  222. package/lib/esm/types/utils/SuiClientUtils.d.ts +0 -15
  223. package/lib/esm/types/utils/SuiClientUtils.d.ts.map +0 -1
  224. package/lib/esm/types/utils/sui.d.ts +0 -27
  225. package/lib/esm/types/utils/sui.d.ts.map +0 -1
  226. package/lib/esm/types/utils/swap.d.ts +0 -15
  227. package/lib/esm/types/utils/swap.d.ts.map +0 -1
  228. package/lib/esm/types/utils/token.d.ts +0 -4
  229. package/lib/esm/types/utils/token.d.ts.map +0 -1
  230. package/lib/esm/utils/ObjectCache.js +0 -250
  231. package/lib/esm/utils/SuiClientUtils.js +0 -34
  232. package/lib/esm/utils/sui.js +0 -88
  233. package/lib/esm/utils/swap.js +0 -33
  234. package/lib/esm/utils/token.js +0 -10
@@ -0,0 +1,536 @@
1
+ import { SourceDex, QuoteResponse } from '@bluefin-exchange/bluefin7k-aggregator-sdk';
2
+ import { PreSwapLpChangeParams, RouterDataV3 } from '@cetusprotocol/aggregator-sdk';
3
+ import { Protocol, AggregatorQuoter } from '@flowx-finance/sdk';
4
+ import { GasCostSummary, SuiClient, GetTransactionBlockParams, SuiTransactionBlockResponse } from '@mysten/sui/client';
5
+ import { SignatureWithBytes } from '@mysten/sui/cryptography';
6
+ import { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
7
+
8
+ /**
9
+ * Swap mode options
10
+ */
11
+ type SwapMode = "exactIn" | "exactOut";
12
+ /**
13
+ * Token information
14
+ */
15
+ interface OkxTokenInfo {
16
+ /** Token contract address */
17
+ tokenContractAddress: string;
18
+ /** Token symbol (e.g., "USDC") */
19
+ tokenSymbol: string;
20
+ /** Token unit price in USD (may be null for special cases) */
21
+ tokenUnitPrice: string | null;
22
+ /** Decimal number defining smallest unit */
23
+ decimal: string;
24
+ /** Whether the token is a honeypot token */
25
+ isHoneyPot: boolean;
26
+ /** Token tax rate (0-1, where 0.01 = 1%) */
27
+ taxRate: string;
28
+ }
29
+ /**
30
+ * DEX Protocol information
31
+ */
32
+ interface OkxDexProtocol {
33
+ /** Name of the liquidity protocol (e.g., "Uniswap V3") */
34
+ dexName: string;
35
+ /** Percentage of assets handled by the protocol */
36
+ percent: string;
37
+ }
38
+ /**
39
+ * Sub-router information
40
+ */
41
+ interface OkxSubRouter {
42
+ /** Liquidity protocol used on the path */
43
+ dexProtocol: OkxDexProtocol;
44
+ /** Index of the from token */
45
+ fromTokenIndex: string;
46
+ /** Index of the to token */
47
+ toTokenIndex: string;
48
+ /** Information of token to be sold */
49
+ fromToken: OkxTokenInfo;
50
+ /** Information of token to be bought */
51
+ toToken: OkxTokenInfo;
52
+ }
53
+ /**
54
+ * Quote comparison information
55
+ */
56
+ interface OkxQuoteCompare {
57
+ /** DEX name of the quote route */
58
+ dexName: string;
59
+ /** DEX logo of the quote route */
60
+ dexLogo: string;
61
+ /** Estimated network fee (USD) of the quote route */
62
+ tradeFee: string;
63
+ /** Received amount of the quote route */
64
+ amountOut: string;
65
+ /** Price impact percentage */
66
+ priceImpactPercentage: string;
67
+ }
68
+ /**
69
+ * Transaction data model
70
+ */
71
+ interface OkxTransactionData {
72
+ /** Additional signing data (if required). When tips is specified, represents calldata of jito tips transfer */
73
+ signatureData?: string[];
74
+ /** User's wallet address */
75
+ from: string;
76
+ /** Estimated amount of the gas limit (increase by 50% for accurate data) */
77
+ gas: string;
78
+ /** Gas price in wei */
79
+ gasPrice?: string;
80
+ /** EIP-1559: Recommended priority cost of gas per unit */
81
+ maxPriorityFeePerGas?: string;
82
+ /** The contract address of OKX DEX router */
83
+ to: string;
84
+ /** The amount of native tokens (in wei) to be sent to the contract */
85
+ value: string;
86
+ /** The maximum amount of a token to spend when price reaches upper limit of slippage (applies to exactOut mode) */
87
+ maxSpendAmount?: string;
88
+ /** The minimum amount of a token to buy when price reaches upper limit of slippage */
89
+ minReceiveAmount: string;
90
+ /** Call data */
91
+ data: string;
92
+ /** Current transaction slippage value */
93
+ slippagePercent: string;
94
+ }
95
+ /**
96
+ * Router result data
97
+ */
98
+ interface OkxRouterResult {
99
+ /** Unique identifier for the chain */
100
+ chainIndex: string;
101
+ /** Context slot (for Solana) */
102
+ contextSlot?: number;
103
+ /** Quote path data set - array of sub-routers */
104
+ dexRouterList: OkxSubRouter[];
105
+ /** Estimated gas consumption in smallest units (e.g., wei) */
106
+ estimateGasFee: string;
107
+ /** Information of token to be sold */
108
+ fromToken: OkxTokenInfo;
109
+ /** The input amount of a token to be sold */
110
+ fromTokenAmount: string;
111
+ /** Price impact percentage = (Received value – Paid value) / Paid value. Can be positive if received value exceeds paid value */
112
+ priceImpactPercent: string;
113
+ /** Router identifier */
114
+ router: string;
115
+ /** Swap mode: "exactIn" or "exactOut" */
116
+ swapMode: SwapMode;
117
+ /** Information of token to be bought */
118
+ toToken: OkxTokenInfo;
119
+ /** The resulting amount of a token to be bought */
120
+ toTokenAmount: string;
121
+ /** Estimated network fee (USD) of the quote route */
122
+ tradeFee: string;
123
+ /** Comparison of quote routes */
124
+ quoteCompareList?: OkxQuoteCompare[];
125
+ }
126
+ /**
127
+ * Swap API Response Data
128
+ */
129
+ interface OkxSwapResponseData {
130
+ /** Quote path data */
131
+ routerResult: OkxRouterResult;
132
+ /** Contract data model */
133
+ tx: OkxTransactionData;
134
+ }
135
+
136
+ declare enum EProvider {
137
+ BLUEFIN7K = "bluefin7k",
138
+ CETUS = "cetus",
139
+ FLOWX = "flowx",
140
+ OKX = "okx"
141
+ }
142
+ type ProviderBaseOptions = {
143
+ api?: string;
144
+ apiKey?: string;
145
+ disabled?: boolean;
146
+ };
147
+ type Bluefin7kProviderOptions = ProviderBaseOptions & {
148
+ sources?: SourceDex[];
149
+ excludedPools?: string[];
150
+ targetPools?: string[];
151
+ };
152
+ type FlowxProviderOptions = ProviderBaseOptions & {
153
+ sources?: Protocol[];
154
+ excludePools?: string[];
155
+ excludeSources?: Protocol[];
156
+ maxHops?: number;
157
+ splitDistributionPercent?: number;
158
+ };
159
+ type CetusProviderOptions = ProviderBaseOptions & {
160
+ sources?: string[];
161
+ splitCount?: number;
162
+ splitAlgorithm?: string;
163
+ splitFactor?: number;
164
+ depth?: number;
165
+ liquidityChanges?: PreSwapLpChangeParams[];
166
+ };
167
+ type OkxProviderOptions = Required<Omit<ProviderBaseOptions, "api">> & {
168
+ api?: string;
169
+ secretKey: string;
170
+ apiPassphrase: string;
171
+ projectId: string;
172
+ };
173
+ interface MetaAgOptions {
174
+ /**If not specified, all providers will be used */
175
+ providers?: {
176
+ [EProvider.BLUEFIN7K]?: Bluefin7kProviderOptions;
177
+ [EProvider.FLOWX]?: FlowxProviderOptions;
178
+ [EProvider.CETUS]?: CetusProviderOptions;
179
+ [EProvider.OKX]?: OkxProviderOptions;
180
+ };
181
+ /**Mainnet Json Rpc url, if not specified, the default mainnet url will be used */
182
+ fullnodeUrl?: string;
183
+ /**Hermes Api url, if not specified, the default hermes api url will be used */
184
+ hermesApi?: string;
185
+ /**Address to receive commission, if not specified, the commission will not be used */
186
+ partner?: string;
187
+ /**@default 0 */
188
+ partnerCommissionBps?: number;
189
+ /**@default 100 */
190
+ slippageBps?: number;
191
+ /**
192
+ * Tip to support 7k
193
+ * @default 0 */
194
+ tipBps?: number;
195
+ }
196
+ interface MetaQuoteOptions {
197
+ coinTypeIn: string;
198
+ coinTypeOut: string;
199
+ amountIn: string;
200
+ /** Required for api-tx providers (ie: Okx) */
201
+ signer?: string;
202
+ /**
203
+ * Timeout for quote operation in milliseconds
204
+ * @default 2000ms
205
+ */
206
+ timeout?: number;
207
+ }
208
+ interface MetaSimulationOptions {
209
+ sender: string;
210
+ /**
211
+ * Timeout for simulation operation in milliseconds
212
+ * @default 2000ms
213
+ */
214
+ timeout?: number;
215
+ /** If specify, defer the simulation that could reduce the time to display quote result, you must update the quote via the id on callback
216
+ * else await all quote and simulation before return
217
+ */
218
+ onSimulated?: (payload: MetaQuote) => void;
219
+ }
220
+ interface MetaFastSwapOptions {
221
+ /** Quote object from the quote operation */
222
+ quote: MetaQuote;
223
+ /** Signer address (owner of `coinIn`) */
224
+ signer: string;
225
+ /** If true, use the gas coin for the swap
226
+ * @default true */
227
+ useGasCoin?: boolean;
228
+ /**
229
+ * Sign the transaction bytes
230
+ * @param txBytes - base64 transaction bytes
231
+ * @returns - signature with bytes
232
+ */
233
+ signTransaction: (txBytes: string) => Promise<SignatureWithBytes>;
234
+ }
235
+ interface MetaSwapOptions {
236
+ /** Quote object from the quote operation */
237
+ quote: MetaQuote;
238
+ /** Signer address (owner of `coinIn`) */
239
+ signer: string;
240
+ /** Transaction object to add the swap operation */
241
+ tx: Transaction;
242
+ /**
243
+ * Coin object used for the swap, must be consumed completely, no `coinIn` left, user must pass the coinIn object with the balance required for the swap - ie in quote `amountIn`
244
+ * @warning `coinIn` value must match the quote `amountIn` */
245
+ coinIn: TransactionObjectArgument;
246
+ }
247
+ type FlowxQuoteResponse = Awaited<ReturnType<AggregatorQuoter["getRoutes"]>>;
248
+ type MetaQuote = ({
249
+ provider: EProvider.BLUEFIN7K;
250
+ quote: QuoteResponse;
251
+ } | {
252
+ provider: EProvider.CETUS;
253
+ quote: RouterDataV3;
254
+ } | {
255
+ provider: EProvider.FLOWX;
256
+ quote: FlowxQuoteResponse;
257
+ } | {
258
+ provider: EProvider.OKX;
259
+ quote: OkxSwapResponseData;
260
+ }) & {
261
+ /** uuid to keep track the quote result, used to apply simulation result on quote on callback `onSimulated`*/
262
+ id: string;
263
+ /** coin type: ie 0x2::sui::SUI */
264
+ coinTypeIn: string;
265
+ /** coin type: ie 0x2::sui::SUI */
266
+ coinTypeOut: string;
267
+ /** Amount in as u64 */
268
+ amountIn: string;
269
+ /** Amount out as u64 if there're no commission be applied to the amount out */
270
+ rawAmountOut: string;
271
+ /** Amount as u64 after minus any commission kind */
272
+ amountOut: string;
273
+ /** Simulated amount out if the transaction is executed */
274
+ simulatedAmountOut?: string;
275
+ /** Estimate gas consumption if the transaction is executed */
276
+ gasUsed?: GasCostSummary;
277
+ };
278
+ interface QuoteProvider {
279
+ readonly kind: EProvider;
280
+ quote(_quoteOptions: MetaQuoteOptions): Promise<MetaQuote | null>;
281
+ }
282
+ interface SwapAPIProvider extends QuoteProvider {
283
+ readonly kind: EProvider.OKX;
284
+ fastSwap(options: MetaFastSwapOptions): Promise<string>;
285
+ }
286
+ interface AggregatorProvider extends QuoteProvider {
287
+ readonly kind: EProvider.BLUEFIN7K | EProvider.CETUS | EProvider.FLOWX;
288
+ swap(options: MetaSwapOptions): Promise<TransactionObjectArgument>;
289
+ }
290
+ declare const isAggregatorProvider: (provider: QuoteProvider) => provider is AggregatorProvider;
291
+ declare const isSwapAPIProvider: (provider: QuoteProvider) => provider is SwapAPIProvider;
292
+
293
+ declare class MetaAg {
294
+ client: SuiClient;
295
+ private providers;
296
+ private inspector;
297
+ private options;
298
+ constructor(options?: MetaAgOptions);
299
+ private _getProvider;
300
+ private _simulate;
301
+ private _quote;
302
+ private _fastSwap;
303
+ /**
304
+ * Get quotes from all providers
305
+ * @param options - quote options
306
+ * @param simulation - if present, the quote will be simulated
307
+ * @returns quotes from all providers
308
+ */
309
+ quote(options: MetaQuoteOptions, simulation?: MetaSimulationOptions): Promise<MetaQuote[]>;
310
+ /**
311
+ * Build transaction from quote
312
+ * @info Use this function to build composable transaction (ie: add more commands after the swap, consume the coin out object)
313
+ * @warning Providers that build transaction on the fly (typically RFQ, Swap-API providers ie: Okx, ...) are not supported, please use `fastSwap` instead
314
+ * @param options - build tx options
315
+ * @param slippageBps - slippage bps if not specified, fallback to global slippage bps, if none of them specified, default to 100
316
+ * @returns coin out object, you must consume it by transferObjects, or other sub sequence commands
317
+ */
318
+ swap(options: MetaSwapOptions, slippageBps?: number): Promise<TransactionObjectArgument>;
319
+ /**
320
+ * Build, Sign, and Execute transaction in one step
321
+ * @param options - fast swap options
322
+ * @returns - txDigest of the transaction
323
+ */
324
+ fastSwap(options: MetaFastSwapOptions, getTransactionBlockParams?: Omit<GetTransactionBlockParams, "digest">): Promise<SuiTransactionBlockResponse>;
325
+ /**
326
+ * Update meta aggregator options
327
+ * @param options - update options payload
328
+ */
329
+ updateMetaAgOptions(options: MetaAgOptions): void;
330
+ }
331
+
332
+ /**
333
+ * Get price for a single token
334
+ * @param id - Token ID (coin type)
335
+ * @returns Token price, or 0 if not found or on error
336
+ */
337
+ declare function getTokenPrice(id: string): Promise<number>;
338
+ /**
339
+ * Get prices for multiple tokens
340
+ * @param ids - Array of token IDs (coin types)
341
+ * @returns Record mapping token IDs to their prices
342
+ */
343
+ declare function getTokenPrices(ids: string[]): Promise<Record<string, number>>;
344
+ /**
345
+ * Get the current SUI token price
346
+ * @returns SUI price, or 0 if not found or on error
347
+ */
348
+ declare function getSuiPrice(): Promise<number>;
349
+
350
+ interface PlaceLimitOrderParams {
351
+ accountAddress: string;
352
+ payCoinType: string;
353
+ targetCoinType: string;
354
+ payCoinAmount: bigint;
355
+ rate: bigint;
356
+ slippage: bigint;
357
+ expireTs: bigint;
358
+ devInspect?: boolean;
359
+ }
360
+ declare function placeLimitOrder({ accountAddress, payCoinType, targetCoinType, payCoinAmount, rate, slippage, expireTs, devInspect, }: PlaceLimitOrderParams): Promise<Transaction>;
361
+
362
+ interface CancelLimitOrderParams {
363
+ orderId: string;
364
+ payCoinType: string;
365
+ targetCoinType: string;
366
+ }
367
+ declare function cancelLimitOrder({ orderId, payCoinType, targetCoinType, }: CancelLimitOrderParams): Promise<Transaction>;
368
+
369
+ interface ClaimExpiredLimitOrderParams {
370
+ orderId: string;
371
+ payCoinType: string;
372
+ targetCoinType: string;
373
+ }
374
+ declare function claimExpiredLimitOrder({ orderId, payCoinType, targetCoinType, }: ClaimExpiredLimitOrderParams): Promise<Transaction>;
375
+
376
+ declare enum LoDcaOrderStatus {
377
+ PENDING = "PENDING",
378
+ ACTIVE = "ACTIVE",
379
+ EXPIRED = "EXPIRED",
380
+ CANCELED = "CANCELED"
381
+ }
382
+ interface LimitOrder {
383
+ id: number;
384
+ createdAt: string;
385
+ updatedAt: string;
386
+ softDeleteAt: string;
387
+ orderId: string;
388
+ owner: string;
389
+ payCoinName: string;
390
+ targetCoinName: string;
391
+ totalPayAmount: string;
392
+ paidAmount: string;
393
+ obtainedAmount: string;
394
+ claimedAmount: string;
395
+ targetBalance: string;
396
+ createdTs: number;
397
+ expireTs: number;
398
+ canceledTs: number;
399
+ lastExecutedTs: number;
400
+ status: LoDcaOrderStatus;
401
+ payBalance: string;
402
+ rate: string;
403
+ slippageBps: string;
404
+ filled: number;
405
+ volume: number;
406
+ digest: string | null;
407
+ }
408
+ interface DcaOrder {
409
+ id: number;
410
+ createdAt: string;
411
+ updatedAt: string;
412
+ softDeletedAt: string;
413
+ orderId: string;
414
+ owner: string;
415
+ payCoinName: string;
416
+ targetCoinName: string;
417
+ totalPayAmount: string;
418
+ paidAmount: string;
419
+ obtainedAmount: string;
420
+ claimedAmount: string;
421
+ targetBalance: string;
422
+ createdTs: number;
423
+ expireTs: number;
424
+ canceledTs: number;
425
+ status: LoDcaOrderStatus;
426
+ slippage: number;
427
+ minRate: string;
428
+ maxRate: string;
429
+ amountPerOrder: string;
430
+ interval: number;
431
+ filled: number;
432
+ volume: number;
433
+ digest: string | null;
434
+ numOrders: number;
435
+ }
436
+ declare enum LoDcaOrderExecutionStatus {
437
+ PENDING = "PENDING",
438
+ SUCCESS = "SUCCESS",
439
+ FAILED = "FAILED"
440
+ }
441
+ interface LoDcaOrderExecution {
442
+ id: number;
443
+ createdAt: string;
444
+ updatedAt: string;
445
+ softDeletedAt: null;
446
+ orderId: string;
447
+ digest: string;
448
+ payCoinName: string;
449
+ targetCoinName: string;
450
+ payAmount: string;
451
+ repayAmount: string;
452
+ obtainedAmount: string;
453
+ executedTs: number;
454
+ slippage: number;
455
+ status: LoDcaOrderExecutionStatus;
456
+ orderType: string;
457
+ volume: number | null;
458
+ }
459
+
460
+ interface Params$4 {
461
+ owner: string;
462
+ offset: number;
463
+ limit: number;
464
+ tokenPair?: string;
465
+ }
466
+ declare function getOpenLimitOrders({ owner, offset, limit, tokenPair, }: Params$4): Promise<LimitOrder[]>;
467
+
468
+ interface Params$3 {
469
+ owner: string;
470
+ offset: number;
471
+ limit: number;
472
+ tokenPair?: string;
473
+ }
474
+ declare function getClosedLimitOrders({ owner, offset, limit, tokenPair, }: Params$3): Promise<LimitOrder[]>;
475
+
476
+ interface PlaceDcaOrderParams {
477
+ payCoinType: string;
478
+ targetCoinType: string;
479
+ payCoinAmountEach: bigint;
480
+ numOrders: number;
481
+ interval: number;
482
+ slippage: bigint;
483
+ minRate: bigint;
484
+ maxRate: bigint;
485
+ }
486
+ declare function placeDcaOrder({ payCoinType, targetCoinType, payCoinAmountEach, numOrders, interval, slippage, minRate, maxRate, }: PlaceDcaOrderParams): Promise<Transaction>;
487
+
488
+ interface CancelDcaOrderParams {
489
+ orderId: string;
490
+ payCoinType: string;
491
+ targetCoinType: string;
492
+ }
493
+ declare function cancelDcaOrder({ orderId, payCoinType, targetCoinType, }: CancelDcaOrderParams): Promise<Transaction>;
494
+
495
+ interface Params$2 {
496
+ owner: string;
497
+ offset: number;
498
+ limit: number;
499
+ tokenPair?: string;
500
+ }
501
+ declare function getOpenDcaOrders({ owner, offset, limit, tokenPair, }: Params$2): Promise<DcaOrder[]>;
502
+
503
+ interface Params$1 {
504
+ owner: string;
505
+ offset: number;
506
+ limit: number;
507
+ tokenPair?: string;
508
+ }
509
+ declare function getClosedDcaOrders({ owner, offset, limit, tokenPair, }: Params$1): Promise<LoDcaOrderExecution[]>;
510
+
511
+ interface Params {
512
+ owner: string;
513
+ orderId: string;
514
+ offset: number;
515
+ limit: number;
516
+ }
517
+ declare function getDcaOrderExecutions({ owner, orderId, offset, limit, }: Params): Promise<LoDcaOrderExecution[]>;
518
+
519
+ declare const _default: {
520
+ getTokenPrice: typeof getTokenPrice;
521
+ getTokenPrices: typeof getTokenPrices;
522
+ getSuiPrice: typeof getSuiPrice;
523
+ placeLimitOrder: typeof placeLimitOrder;
524
+ getOpenLimitOrders: typeof getOpenLimitOrders;
525
+ cancelLimitOrder: typeof cancelLimitOrder;
526
+ claimExpiredLimitOrder: typeof claimExpiredLimitOrder;
527
+ getClosedLimitOrders: typeof getClosedLimitOrders;
528
+ placeDcaOrder: typeof placeDcaOrder;
529
+ getOpenDcaOrders: typeof getOpenDcaOrders;
530
+ cancelDcaOrder: typeof cancelDcaOrder;
531
+ getClosedDcaOrders: typeof getClosedDcaOrders;
532
+ getDcaOrderExecutions: typeof getDcaOrderExecutions;
533
+ MetaAg: typeof MetaAg;
534
+ };
535
+
536
+ export { type AggregatorProvider, type Bluefin7kProviderOptions, type CetusProviderOptions, EProvider, type FlowxProviderOptions, type FlowxQuoteResponse, MetaAg, type MetaAgOptions, type MetaFastSwapOptions, type MetaQuote, type MetaQuoteOptions, type MetaSimulationOptions, type MetaSwapOptions, type OkxProviderOptions, type QuoteProvider, type SwapAPIProvider, cancelDcaOrder, cancelLimitOrder, claimExpiredLimitOrder, _default as default, getClosedDcaOrders, getClosedLimitOrders, getDcaOrderExecutions, getOpenDcaOrders, getOpenLimitOrders, getSuiPrice, getTokenPrice, getTokenPrices, isAggregatorProvider, isSwapAPIProvider, placeDcaOrder, placeLimitOrder };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkKVGSSW22js = require('./chunk-KVGSSW22.js');var _client = require('@mysten/sui/client');var _transactions = require('@mysten/sui/transactions');var _utils = require('@mysten/sui/utils');var tt="0x0000000000000000000000000000000000000000000000000000000000000000";var St=["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000003","0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000005","0x0000000000000000000000000000000000000000000000000000000000000006","0x0000000000000000000000000000000000000000000000000000000000000007","0x0000000000000000000000000000000000000000000000000000000000000008","0x0000000000000000000000000000000000000000000000000000000000000009","0x0000000000000000000000000000000000000000000000000000000000000403","0x000000000000000000000000000000000000000000000000000000000000000c"],v=s=>{let t=_utils.normalizeSuiAddress.call(void 0, s);return St.includes(t)};var V=class{async getObject(t){let[e,r]=await Promise.all([this.get("OwnedObject",t),this.get("SharedOrImmutableObject",t)]);return _nullishCoalesce(_nullishCoalesce(e, () => (r)), () => (null))}async getObjects(t){return Promise.all(t.map(e=>this.getObject(e)))}async addObject(t){return t.owner?await this.set("OwnedObject",t.objectId,t):await this.set("SharedOrImmutableObject",t.objectId,t),t}async addObjects(t){await Promise.all(t.map(async e=>this.addObject(e)))}async deleteObject(t){await Promise.all([this.delete("OwnedObject",t),this.delete("SharedOrImmutableObject",t)])}async deleteObjects(t){await Promise.all(t.map(e=>this.deleteObject(e)))}async getMoveFunctionDefinition(t){let e=`${_utils.normalizeSuiAddress.call(void 0, t.package)}::${t.module}::${t.function}`;return this.get("MoveFunction",e)}async addMoveFunctionDefinition(t){let e=_utils.normalizeSuiAddress.call(void 0, t.package),r=`${e}::${t.module}::${t.function}`,i={...t,package:e};return await this.set("MoveFunction",r,i),i}async deleteMoveFunctionDefinition(t){let e=`${_utils.normalizeSuiAddress.call(void 0, t.package)}::${t.module}::${t.function}`;await this.delete("MoveFunction",e)}async getCustom(t){return this.get("Custom",t)}async setCustom(t,e){return this.set("Custom",t,e)}async deleteCustom(t){return this.delete("Custom",t)}},h,q=class extends V{constructor(){super(...arguments);_chunkKVGSSW22js.b.call(void 0, this,h,{OwnedObject:new Map,SharedOrImmutableObject:new Map,MoveFunction:new Map,Custom:new Map})}async get(e,r){return _nullishCoalesce(_chunkKVGSSW22js.a.call(void 0, this,h)[e].get(r), () => (null))}async set(e,r,i){_chunkKVGSSW22js.a.call(void 0, this,h)[e].set(r,i)}async delete(e,r){_chunkKVGSSW22js.a.call(void 0, this,h)[e].delete(r)}async clear(e){if(e)_chunkKVGSSW22js.a.call(void 0, this,h)[e].clear();else for(let r of Object.values(_chunkKVGSSW22js.a.call(void 0, this,h)))r.clear()}};h=new WeakMap;var S,l,A,M=class{constructor({cache:t=new q,onEffects:e,client:r}){_chunkKVGSSW22js.b.call(void 0, this,S);_chunkKVGSSW22js.b.call(void 0, this,l);_chunkKVGSSW22js.b.call(void 0, this,A);_chunkKVGSSW22js.c.call(void 0, this,S,r),_chunkKVGSSW22js.c.call(void 0, this,l,t),_chunkKVGSSW22js.c.call(void 0, this,A,e)}async applyCache(t,e){let r=(await _chunkKVGSSW22js.a.call(void 0, this,l).getObjects(e)).filter(n=>n!==null),i=new Map(r.map(n=>[n.objectId,n])),o=[];for(let n of t.inputs){if(!n.UnresolvedObject)continue;let a=i.get(n.UnresolvedObject.objectId);if(!a){o.push(n.UnresolvedObject.objectId);continue}a.initialSharedVersion&&!n.UnresolvedObject.initialSharedVersion?n.UnresolvedObject.initialSharedVersion=a.initialSharedVersion:(a.version&&!n.UnresolvedObject.version&&(n.UnresolvedObject.version=a.version),a.digest&&!n.UnresolvedObject.digest&&(n.UnresolvedObject.digest=a.digest))}return o}async resolveObjects(t,e){let r=await this.applyCache(t,e);if(r.length===0)return[];let i=[...new Set(r)],o=await _chunkKVGSSW22js.a.call(void 0, this,S).multiGetObjects({ids:i,options:{showOwner:!0}}),n=[];for(let a of o||[]){if(!a.data)continue;let c=a.data.owner,p=c&&typeof c=="object"&&"Shared"in c?c.Shared.initial_shared_version:null,g=c&&typeof c=="object"&&"AddressOwner"in c?c.AddressOwner:null,_={objectId:a.data.objectId,version:a.data.version,digest:a.data.digest,initialSharedVersion:p,owner:g};n.push(_)}return await _chunkKVGSSW22js.a.call(void 0, this,l).addObjects(n),await this.applyCache(t,r)}asPlugin(){return async(t,e,r)=>{let i=t.inputs.filter(o=>o.UnresolvedObject).map(o=>o.UnresolvedObject.objectId);await this.resolveObjects(t,i),await Promise.all(t.commands.map(async o=>{if(o.MoveCall){let n=await this.getMoveFunctionDefinition({package:o.MoveCall.package,module:o.MoveCall.module,function:o.MoveCall.function});n&&(o.MoveCall._argumentTypes=n.parameters)}})),await r(),await Promise.all(t.commands.map(async o=>{_optionalChain([o, 'access', _2 => _2.MoveCall, 'optionalAccess', _3 => _3._argumentTypes])&&await _chunkKVGSSW22js.a.call(void 0, this,l).addMoveFunctionDefinition({package:o.MoveCall.package,module:o.MoveCall.module,function:o.MoveCall.function,parameters:o.MoveCall._argumentTypes})}))}}async clear(){await _chunkKVGSSW22js.a.call(void 0, this,l).clear()}async getMoveFunctionDefinition(t){return _chunkKVGSSW22js.a.call(void 0, this,l).getMoveFunctionDefinition(t)}async getObjects(t){return _chunkKVGSSW22js.a.call(void 0, this,l).getObjects(t)}async deleteObjects(t){return _chunkKVGSSW22js.a.call(void 0, this,l).deleteObjects(t)}async clearOwnedObjects(){await _chunkKVGSSW22js.a.call(void 0, this,l).clear("OwnedObject")}async clearCustom(){await _chunkKVGSSW22js.a.call(void 0, this,l).clear("Custom")}async getCustom(t){return _chunkKVGSSW22js.a.call(void 0, this,l).getCustom(t)}async setCustom(t,e){return _chunkKVGSSW22js.a.call(void 0, this,l).setCustom(t,e)}async deleteCustom(t){return _chunkKVGSSW22js.a.call(void 0, this,l).deleteCustom(t)}async applyEffects(t){var n;if(!t.V2)throw new Error(`Unsupported transaction effects version ${t.$kind}`);let{lamportVersion:e,changedObjects:r}=t.V2,i=[],o=[];r.forEach(([a,c])=>{if(c.outputState.NotExist)i.push(a);else if(c.outputState.ObjectWrite){let[p,g]=c.outputState.ObjectWrite;o.push({objectId:a,digest:p,version:e,owner:_nullishCoalesce(_nullishCoalesce(g.AddressOwner, () => (g.ObjectOwner)), () => (null)),initialSharedVersion:_nullishCoalesce(_optionalChain([g, 'access', _4 => _4.Shared, 'optionalAccess', _5 => _5.initialSharedVersion]), () => (null))})}}),await Promise.all([_chunkKVGSSW22js.a.call(void 0, this,l).addObjects(o),_chunkKVGSSW22js.a.call(void 0, this,l).deleteObjects(i),(n=_chunkKVGSSW22js.a.call(void 0, this,A))==null?void 0:n.call(this,t)])}};S=new WeakMap,l=new WeakMap,A=new WeakMap;var T,E=class{constructor(t){this.client=t;_chunkKVGSSW22js.b.call(void 0, this,T);this.devInspectTransactionBlock=async t=>{t.transactionBlock instanceof _transactions.Transaction&&t.transactionBlock.addBuildPlugin(_chunkKVGSSW22js.a.call(void 0, this,T).asPlugin());try{return await this.client.devInspectTransactionBlock(t)}catch(e){throw await _chunkKVGSSW22js.a.call(void 0, this,T).clear(),e}finally{await _chunkKVGSSW22js.a.call(void 0, this,T).clearOwnedObjects()}};_chunkKVGSSW22js.c.call(void 0, this,T,new M({client:this.client}))}};T=new WeakMap;var k=(s,t,e,r=0)=>{if(t>1e4)throw new Error("Slippage must be less than 100%");if(e>1e4)throw new Error("Commission must be less than 100%");if(r>1e4)throw new Error("Tip must be less than 100%");let i=BigInt(s),o=i*BigInt(r||0)/10000n,n=(i-o)*BigInt(e)/10000n,a=i-o-n,c=a*BigInt(1e4-t)/10000n;return{tipAmount:o,minAmount:c,commissionAmount:n,expectedAmount:a.toString(10)}};var X=async(s,t,e)=>{let r=await G(()=>t.devInspectTransactionBlock({sender:e.sender,transactionBlock:s}),_nullishCoalesce(e.timeout, () => (2e3)));if(r.effects.status.status==="failure")throw new (0, _chunkKVGSSW22js.l)(_nullishCoalesce(r.error, () => ("Simulation failed")),1008,{error:r.error});return{simulatedAmountOut:It(r.events),gasUsed:r.effects.gasUsed}},rt=async(s,t,e,r,i)=>{let o=new _transactions.Transaction,n=await s.swap({quote:t,coinIn:_transactions.coinWithBalance.call(void 0, {balance:BigInt(t.amountIn),type:t.coinTypeIn,useGasCoin:!1}),signer:e.sender,tx:o});o.add(P(t,n,1e4,i.tipBps,i.partner,i.partnerCommissionBps)),o.transferObjects([n],e.sender);let a=await X(o,r,e);return{id:t.id,provider:s.kind,...a}},P=(s,t,e=100,r=0,i,o=0)=>n=>{let{minAmount:a,expectedAmount:c}=k(s.rawAmountOut,e,o,r);r>0&&n.moveCall({target:`${_chunkKVGSSW22js.g}::vault::collect_tip`,typeArguments:[s.coinTypeOut],arguments:[n.object(_chunkKVGSSW22js.i),n.object(_chunkKVGSSW22js.j),t,n.pure.u64(r)]}),n.moveCall({target:`${_chunkKVGSSW22js.g}::settle::settle`,typeArguments:[s.coinTypeIn,s.coinTypeOut],arguments:[n.object(_chunkKVGSSW22js.j),n.object(_chunkKVGSSW22js.i),n.pure.u64(s.amountIn),t,n.pure.u64(a),n.pure.u64(c),n.pure.option("address",i),n.pure.u64(o),n.pure.u64(0)]})},It=s=>_optionalChain([s, 'access', _6 => _6.filter, 'call', _7 => _7(e=>e.type===`${_chunkKVGSSW22js.h}::settle::Swap`), 'optionalAccess', _8 => _8.pop, 'call', _9 => _9(), 'optionalAccess', _10 => _10.parsedJson, 'optionalAccess', _11 => _11.amount_out]),G=async(s,t,e)=>t<=0?s():new Promise((r,i)=>{let o=setTimeout(()=>i(new (0, _chunkKVGSSW22js.l)(`Timeout ${_nullishCoalesce(e, () => ("operation"))}`,1001,{timeout:t})),t);s().then(r).catch(i).finally(()=>clearTimeout(o))});var _uuid = require('uuid');var w="0x2::sui::SUI",j="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Lt="https://web3.okx.com",ot="/api/v6/dex/aggregator/swap",Ut="784",st=_utils.normalizeStructTag.call(void 0, w),L=class{constructor(t,e,r){this.options=t;this.metaOptions=e;this.client=r;this.kind="okx"}async quote({amountIn:t,coinTypeIn:e,coinTypeOut:r,signer:i}){if(!i||v(i))return null;let o={chainIndex:Ut,amount:t,fromTokenAddress:e===st?w:e,toTokenAddress:r===st?w:r,slippagePercent:(this.metaOptions.slippageBps/100).toString(),userWalletAddress:i},n="?"+new URLSearchParams(o).toString(),a=`${_nullishCoalesce(this.options.api, () => (Lt))}${ot}${n}`,p=await(await fetch(a,{headers:await Bt(this.options,"GET",ot,n)})).json();return _chunkKVGSSW22js.l.assert(p.code==="0"&&p.data.length>0,"No quote found",1005,{provider:this.kind}),{id:_uuid.v4.call(void 0, ),provider:this.kind,coinTypeIn:e,coinTypeOut:r,amountIn:t,amountOut:p.data[0].routerResult.toTokenAmount,rawAmountOut:p.data[0].routerResult.toTokenAmount,quote:p.data[0]}}async fastSwap(t){let{quote:e,signer:r,signTransaction:i}=t;_chunkKVGSSW22js.l.assert(e.provider==="okx","Invalid quote",1004,{quote:e,expectedProvider:"okx"});let{tx:o,coin:n}=at({quote:e,signer:r});o.add(P(e,n,this.metaOptions.slippageBps,this.metaOptions.tipBps,this.metaOptions.partner,this.metaOptions.partnerCommissionBps)),o.transferObjects([n],r);let a=await o.build({client:this.client}),{bytes:c,signature:p}=await i(_utils.toBase64.call(void 0, a));return(await this.client.executeTransactionBlock({signature:p,transactionBlock:c})).digest}};async function Rt(s,t){let e=new TextEncoder,r=o=>{if(typeof Buffer<"u")return Buffer.from(o).toString("base64");let n="";for(let a=0;a<o.byteLength;a++)n+=String.fromCharCode(o[a]);if(typeof btoa<"u")return btoa(n);throw new (0, _chunkKVGSSW22js.l)("Base64 encoder not available in this environment")};if(typeof globalThis<"u"&&_optionalChain([globalThis, 'access', _12 => _12.crypto, 'optionalAccess', _13 => _13.subtle])){let o=await globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await globalThis.crypto.subtle.sign("HMAC",o,e.encode(s));return r(new Uint8Array(n))}let{createHmac:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("crypto")));return i("sha256",t).update(s).digest("base64")}async function Bt(s,t,e,r=""){let{apiKey:i,secretKey:o,apiPassphrase:n,projectId:a}=s;if(!i||!o||!n||!a)throw new (0, _chunkKVGSSW22js.l)("Missing required environment variables");let c=new Date().toISOString(),p=c+t+e+r;return{"Content-Type":"application/json","OK-ACCESS-KEY":i,"OK-ACCESS-SIGN":await Rt(p,o),"OK-ACCESS-TIMESTAMP":c,"OK-ACCESS-PASSPHRASE":n,"OK-ACCESS-PROJECT":a}}var $t=(s,t)=>{let e=_transactions.TransactionDataBuilder.restore(s.getData()),r=e.commands.findIndex(n=>n.$kind==="MoveCall"&&_utils.normalizeSuiAddress.call(void 0, n.MoveCall.package)===_utils.normalizeSuiAddress.call(void 0, t)&&n.MoveCall.module==="router"&&n.MoveCall.function==="finalize"),i=e.commands[r];return _chunkKVGSSW22js.l.assert(i.MoveCall,"OKX: Finalize command not found",1100,{packageId:t}),e.replaceCommand(r,_transactions.Commands.MoveCall({package:t,module:"router",function:"finalize_without_transfer",typeArguments:i.MoveCall.typeArguments,arguments:[i.MoveCall.arguments[0],i.MoveCall.arguments[5],i.MoveCall.arguments[6]]})),{tx:_transactions.Transaction.from(e.build()),coin:{NestedResult:[r,0]}}},at=s=>{let{quote:t,signer:e}=s;_chunkKVGSSW22js.l.assert(t.provider==="okx","Invalid quote",1004,{quote:t,expectedProvider:"okx"});let r=_transactions.Transaction.from(t.quote.tx.data);r.setSenderIfNotSet(e);let{tx:i,coin:o}=$t(r,t.quote.tx.to);return{tx:i,coin:o}},ct=async(s,t,e,r)=>{let{tx:i,coin:o}=at({quote:s,signer:s.quote.tx.from});i.add(P(s,o,1e4,r.tipBps,r.partner,r.partnerCommissionBps)),i.transferObjects([o],s.quote.tx.from);let n=await X(i,t,e);return{id:s.id,provider:s.provider,...n}};var Vt="https://hermes.pyth.network",qt={bluefin7k:{},flowx:{},cetus:{}},U= exports.MetaAg =class{constructor(t){this.providers={};this.options={providers:{...qt,..._optionalChain([t, 'optionalAccess', _14 => _14.providers])},slippageBps:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _15 => _15.slippageBps]), () => (100)),fullnodeUrl:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _16 => _16.fullnodeUrl]), () => (_client.getFullnodeUrl.call(void 0, "mainnet"))),hermesApi:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _17 => _17.hermesApi]), () => (Vt)),partner:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _18 => _18.partner]), () => (tt)),partnerCommissionBps:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _19 => _19.partnerCommissionBps]), () => (0)),tipBps:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _20 => _20.tipBps]), () => (0))},this.client=new (0, _client.SuiClient)({url:this.options.fullnodeUrl}),this.inspector=new E(this.client)}async _getProvider(t){let e=this.providers[t];if(e)return e;let r=this.options.providers[t];switch(_chunkKVGSSW22js.l.assert(!!r,`Provider not found: ${t}`,1002,{provider:t}),t){case"bluefin7k":let{Bluefin7kProvider:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("./bluefin7k-I6ZCDWDN.js"))).catch(W("bluefin7k"));this.providers.bluefin7k=new i(r,this.options,this.client);break;case"flowx":let{FlowxProvider:o}=await Promise.resolve().then(() => _interopRequireWildcard(require("./flowx-6M54WFWO.js"))).catch(W("flowx"));this.providers.flowx=new o(r,this.client);break;case"cetus":let{CetusProvider:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./cetus-SIPX6FYL.js"))).catch(W("cetus"));this.providers.cetus=new n(r,this.options,this.client);break;case"okx":this.providers.okx=new L(r,this.options,this.client);break;default:throw new (0, _chunkKVGSSW22js.l)(`Provider not supported: ${t}`,1003,{provider:t})}return this.providers[t]}async _simulate(t,e,r){try{if(_chunkKVGSSW22js.e.call(void 0, t))return rt(t,e,r,this.inspector,this.options);if(e.provider==="okx")return ct(e,this.inspector,r,this.options);throw new (0, _chunkKVGSSW22js.l)(`Provider not supported: ${t.kind}`,1003,{provider:t.kind})}catch(i){console.warn(i,{provider:t.kind,quote:e.id})}}async _quote(t,e){return await G(async()=>{let i=await t.quote(e);if(!i)return null;let{expectedAmount:o}=k(i.rawAmountOut,0,this.options.partnerCommissionBps,this.options.tipBps);return i.amountOut=o,i},_nullishCoalesce(e.timeout, () => (2e3)),`quote for ${t.kind} provider from ${e.coinTypeIn} to ${e.coinTypeOut}`)}async _fastSwap({quote:t,signer:e,useGasCoin:r,signTransaction:i},o){let n=new _transactions.Transaction,a=await this.swap({quote:t,signer:e,tx:n,coinIn:_transactions.coinWithBalance.call(void 0, {type:t.coinTypeIn,balance:BigInt(t.amountIn),useGasCoin:r})});n.transferObjects([a],e),n.setSenderIfNotSet(e);let c=await n.build({client:this.client}),{signature:p,bytes:g}=await i(_utils.toBase64.call(void 0, c));return this.client.executeTransactionBlock({transactionBlock:g,signature:p,options:_optionalChain([o, 'optionalAccess', _21 => _21.options]),signal:_optionalChain([o, 'optionalAccess', _22 => _22.signal])})}async quote(t,e){let r={...t,coinTypeIn:_utils.normalizeStructTag.call(void 0, t.coinTypeIn),coinTypeOut:_utils.normalizeStructTag.call(void 0, t.coinTypeOut)},o=(await Promise.allSettled(Object.entries(this.options.providers).filter(([n,a])=>!a.disabled).map(async([n])=>{let a=await this._getProvider(n);return this._quote(a,r)}))).map(n=>n.status==="fulfilled"?n.value:(console.warn(n.reason),null)).filter(n=>n!==null);if(e){let n=o.map(async a=>{let c=await this._getProvider(a.provider),p=await this._simulate(c,a,e);a.simulatedAmountOut=_optionalChain([p, 'optionalAccess', _23 => _23.simulatedAmountOut]),a.gasUsed=_optionalChain([p, 'optionalAccess', _24 => _24.gasUsed]),_optionalChain([e, 'optionalAccess', _25 => _25.onSimulated, 'optionalCall', _26 => _26({...a})])});e.onSimulated||await Promise.all(n)}return o}async swap(t,e){let r=await this._getProvider(t.quote.provider);_chunkKVGSSW22js.l.assert(!!r,`Provider not found: ${t.quote.provider}`,1002,{provider:t.quote.provider}),_chunkKVGSSW22js.l.assert(_chunkKVGSSW22js.e.call(void 0, r),`Provider does not support swap: ${r.kind}, use fastSwap instead`,1007,{provider:r.kind}),_chunkKVGSSW22js.l.assert(t.signer&&!v(t.signer),"Invalid signer address",1006,{signer:t.signer});let i=await r.swap(t);return t.tx.add(P(t.quote,i,_nullishCoalesce(_nullishCoalesce(e, () => (this.options.slippageBps)), () => (100)),this.options.tipBps,this.options.partner,this.options.partnerCommissionBps)),t.tx.setSenderIfNotSet(t.signer),i}async fastSwap(t,e){_chunkKVGSSW22js.l.assert(t.signer&&!v(t.signer),"Invalid signer address",1006,{signer:t.signer});let r=await this._getProvider(t.quote.provider);if(_chunkKVGSSW22js.e.call(void 0, r))return this._fastSwap(t,e);if(_chunkKVGSSW22js.f.call(void 0, r))return this.client.waitForTransaction({...e,digest:await r.fastSwap(t)});throw new (0, _chunkKVGSSW22js.l)(`Provider not supported: ${r.kind}`,1003,{provider:r.kind})}updateMetaAgOptions(t){if(Object.keys(t).length!==0){this.options.slippageBps=_nullishCoalesce(t.slippageBps, () => (this.options.slippageBps)),this.options.partner=_nullishCoalesce(t.partner, () => (this.options.partner)),this.options.partnerCommissionBps=_nullishCoalesce(t.partnerCommissionBps, () => (this.options.partnerCommissionBps)),this.options.tipBps=_nullishCoalesce(t.tipBps, () => (this.options.tipBps)),t.fullnodeUrl&&t.fullnodeUrl!==this.options.fullnodeUrl&&(this.client=new (0, _client.SuiClient)({url:t.fullnodeUrl}),this.inspector=new E(this.client),this.options.fullnodeUrl=t.fullnodeUrl),t.hermesApi&&t.hermesApi!==this.options.hermesApi&&(this.providers={},this.options.hermesApi=t.hermesApi);for(let[e,r]of Object.entries(t.providers||{}))this.options.providers[e]={...r,...this.options.providers[e]},delete this.providers[e]}}},W=s=>t=>{let e={cetus:"@cetusprotocol/aggregator-sdk",flowx:"@flowx-finance/sdk",bluefin7k:"@bluefin-exchange/bluefin7k-aggregator-sdk",okx:""};throw console.warn(`Please install ${e[s]} to use ${s} provider`),t};async function d(s,t){let e=new Headers(_optionalChain([t, 'optionalAccess', _27 => _27.headers])),r={...t,headers:e};return fetch(s,r)}var R={MAIN:"https://api.7k.ag",LO_DCA:"https://lod-dca.7k.ag",PRICES:"https://lp-pro-api.7k.ag/price",STATISTIC:"https://statistic.7k.ag"};function B(s){return s===w?j:s}var Xt=(s,t)=>{let e=[];for(let r=0;r<s.length;r+=t)e.push(s.slice(r,r+t));return e},mt=500,Gt=100;function Wt(){return Math.floor(Date.now()/1e3).toString()}async function z(s){try{let t=B(s);return(await H([t]))[t]||0}catch (e2){return 0}}async function H(s){try{if(s.length===0)return{};let t=s.slice(0,mt).map(B),e=Xt(t,Gt),r=Wt(),o=(await Promise.all(e.map(async a=>{let c={timestamp:r,token_ids:a},p=await d(`${R.PRICES}/prices/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!p.ok)throw new Error(`Price API returned status ${p.status}`);return await p.json()}))).reduce((a,c)=>(c.forEach(p=>{a[p.token_id]=p.price}),a),{});return t.reduce((a,c)=>(a[c]=o[c]||0,a),{})}catch (e3){return s.slice(0,mt).reduce((e,r)=>(e[B(r)]=0,e),{})}}async function lt(){return await z(j)}var $="0xffc7f420b481ed7a012b42e125fd7e5716b5673759cf4629e5fcfebce970a72d",br=BigInt("1000000000000"),vr=BigInt("10000"),Y="0x0ef0f805710cf53c10f29c4f73e1144a662747e1839689a846e2520cae122adc",b=`${Y}::limit_order`,F=`${Y}::dca_order`,Sr=`${Y}::config`,Ar=BigInt("18446744073709551615"),f=`${R.LO_DCA}/api`;async function dt({accountAddress:s,payCoinType:t,targetCoinType:e,payCoinAmount:r,rate:i,slippage:o,expireTs:n,devInspect:a}){let c=new _transactions.Transaction,p=c.add(_transactions.coinWithBalance.call(void 0, {type:t,balance:r,useGasCoin:!a}));return c.moveCall({target:`${b}::place_limit_order`,arguments:[c.object($),p,c.pure.u64(i),c.pure.u64(o),c.pure.u64(n),c.object.clock()],typeArguments:[t,e]}),c.setSenderIfNotSet(s),c}async function gt({orderId:s,payCoinType:t,targetCoinType:e}){let r=new _transactions.Transaction;return r.moveCall({target:`${b}::cancel_limit_order`,typeArguments:[t,e],arguments:[r.object(s),r.object.clock()]}),r}async function ft({orderId:s,payCoinType:t,targetCoinType:e}){let r=new _transactions.Transaction;return r.moveCall({target:`${b}::claim_expired_order`,typeArguments:[t,e],arguments:[r.object(s),r.object.clock()]}),r}function O(s){let t="";return Object.entries(s).forEach(([e,r])=>{if(Array.isArray(r))for(let i of r)t+=t?`&${e}=${i}`:`${e}=${i}`;else r!==void 0&&(t+=t?`&${e}=${r}`:`${e}=${r}`)}),t}async function Ot({owner:s,offset:t=0,limit:e=10,tokenPair:r}){let o=O({owner:s,statuses:["ACTIVE","EXPIRED"],offset:t,limit:e,tokenPair:r}),n=await d(`${f}/limit-orders?${o}`);if(!n.ok)throw new Error("Failed to fetch open limit orders");return await n.json()}async function ht({owner:s,offset:t=0,limit:e=10,tokenPair:r}){let o=O({owner:s,statuses:["CLOSED"],offset:t,limit:e,tokenPair:r}),n=await d(`${f}/limit-orders?${o}`);if(!n.ok)throw new Error("Failed to fetch closed limit orders");return await n.json()}async function yt({payCoinType:s,targetCoinType:t,payCoinAmountEach:e,numOrders:r,interval:i,slippage:o,minRate:n,maxRate:a}){let c=new _transactions.Transaction,p=[];for(let _=0;_<r;_++){let bt=_transactions.coinWithBalance.call(void 0, {type:s,balance:e});p.push(bt)}let g=c.makeMoveVec({elements:p});return c.moveCall({target:`${F}::place_dca_order`,arguments:[c.object($),g,c.pure.u64(i),c.pure.u64(o),c.pure.u64(n),c.pure.u64(a),c.object.clock()],typeArguments:[s,t]}),c}async function Tt({orderId:s,payCoinType:t,targetCoinType:e}){let r=new _transactions.Transaction;return r.moveCall({target:`${F}::cancel_dca_order`,arguments:[r.object(s),r.object.clock()],typeArguments:[t,e]}),r}async function Ct({owner:s,offset:t=0,limit:e=10,tokenPair:r}){let o=O({owner:s,statuses:["ACTIVE","EXPIRED"],offset:t,limit:e,tokenPair:r}),n=await d(`${f}/dca-orders?${o}`);if(!n.ok)throw new Error("Failed to fetch open dca orders");return await n.json()}async function Pt({owner:s,offset:t=0,limit:e=10,tokenPair:r}){let o=O({owner:s,statuses:["SUCCESS"],offset:t,limit:e,orderType:"DCA",tokenPair:r}),n=await d(`${f}/order-executions?${o}`);if(!n.ok)throw new Error("Failed to fetch closed dca orders");return await n.json()}async function wt({owner:s,orderId:t,offset:e=0,limit:r=10}){let o=O({owner:s,orderId:t,statuses:["SUCCESS"],offset:e,limit:r,orderType:"DCA"}),n=await d(`${f}/order-executions?${o}`);if(!n.ok)throw new Error("Failed to fetch dca order executions");return await n.json()}var An={getTokenPrice:z,getTokenPrices:H,getSuiPrice:lt,placeLimitOrder:dt,getOpenLimitOrders:Ot,cancelLimitOrder:gt,claimExpiredLimitOrder:ft,getClosedLimitOrders:ht,placeDcaOrder:yt,getOpenDcaOrders:Ct,cancelDcaOrder:Tt,getClosedDcaOrders:Pt,getDcaOrderExecutions:wt,MetaAg:U};exports.EProvider = _chunkKVGSSW22js.d; exports.MetaAg = U; exports.cancelDcaOrder = Tt; exports.cancelLimitOrder = gt; exports.claimExpiredLimitOrder = ft; exports.default = An; exports.getClosedDcaOrders = Pt; exports.getClosedLimitOrders = ht; exports.getDcaOrderExecutions = wt; exports.getOpenDcaOrders = Ct; exports.getOpenLimitOrders = Ot; exports.getSuiPrice = lt; exports.getTokenPrice = z; exports.getTokenPrices = H; exports.isAggregatorProvider = _chunkKVGSSW22js.e; exports.isSwapAPIProvider = _chunkKVGSSW22js.f; exports.placeDcaOrder = yt; exports.placeLimitOrder = dt;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/otis/Documents/7k-ts-sdk/dist/index.js","../src/features/metaAg/index.ts","../src/constants/sui.ts","../src/utils/sui.ts","../src/utils/SuiClientUtils.ts","../src/utils/ObjectCache.ts"],"names":["SUI_ADDRESS_ZERO","RESERVED_ADDRESSES","isSystemAddress","address","addr","normalizeSuiAddress","AsyncCache","id","owned","shared","ids","object","objects","ref","functionName"],"mappings":"AAAA,y/BAA6G,4CCKtG,wDAKA,0CACsC,ICXhCA,EAAAA,CACX,oEAAA,CCAF,IAiHMC,EAAAA,CAAqB,CACzB,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEAAA,CACA,oEACF,CAAA,CAEaC,CAAAA,CAAmBC,CAAAA,EAAoB,CAClD,IAAMC,CAAAA,CAAOC,wCAAAA,CAA2B,CAAA,CACxC,OAAOJ,EAAAA,CAAmB,QAAA,CAASG,CAAI,CACzC,CAAA,CChIA,IC0BsBE,CAAAA,CAAf,KAA0B,CAgB/B,MAAM,SAAA,CAAUC,CAAAA,CAAY,CAC1B,GAAM,CAACC,CAAAA,CAAOC,CAAM,CAAA,CAAI,MAAM,OAAA,CAAQ,GAAA,CAAI,CACxC,IAAA,CAAK,GAAA,CAAI,aAAA,CAAeF,CAAE,CAAA,CAC1B,IAAA,CAAK,GAAA,CAAI,yBAAA,CAA2BA,CAAE,CACxC,CAAC,CAAA,CAED,yCAAOC,CAAAA,SAASC,GAAAA,SAAU,MAC5B,CAEA,MAAM,UAAA,CAAWC,CAAAA,CAAe,CAC9B,OAAO,OAAA,CAAQ,GAAA,CAAIA,CAAAA,CAAI,GAAA,CAAKH,CAAAA,EAAO,IAAA,CAAK,SAAA,CAAUA,CAAE,CAAC,CAAC,CACxD,CAEA,MAAM,SAAA,CAAUI,CAAAA,CAA0B,CACxC,OAAIA,CAAAA,CAAO,KAAA,CACT,MAAM,IAAA,CAAK,GAAA,CAAI,aAAA,CAAeA,CAAAA,CAAO,QAAA,CAAUA,CAAM,CAAA,CAErD,MAAM,IAAA,CAAK,GAAA,CAAI,yBAAA,CAA2BA,CAAAA,CAAO,QAAA,CAAUA,CAAM,CAAA,CAG5DA,CACT,CAEA,MAAM,UAAA,CAAWC,CAAAA,CAA6B,CAC5C,MAAM,OAAA,CAAQ,GAAA,CAAIA,CAAAA,CAAQ,GAAA,CAAI,MAAOD,CAAAA,EAAW,IAAA,CAAK,SAAA,CAAUA,CAAM,CAAC,CAAC,CACzE,CAEA,MAAM,YAAA,CAAaJ,CAAAA,CAAY,CAC7B,MAAM,OAAA,CAAQ,GAAA,CAAI,CAChB,IAAA,CAAK,MAAA,CAAO,aAAA,CAAeA,CAAE,CAAA,CAC7B,IAAA,CAAK,MAAA,CAAO,yBAAA,CAA2BA,CAAE,CAC3C,CAAC,CACH,CAEA,MAAM,aAAA,CAAcG,CAAAA,CAAe,CACjC,MAAM,OAAA,CAAQ,GAAA,CAAIA,CAAAA,CAAI,GAAA,CAAKH,CAAAA,EAAO,IAAA,CAAK,YAAA,CAAaA,CAAE,CAAC,CAAC,CAC1D,CAEA,MAAM,yBAAA,CAA0BM,CAAAA,CAI7B,CACD,IAAMC,CAAAA,CAAe,CAAA,EAAA","file":"/Users/otis/Documents/7k-ts-sdk/dist/index.js","sourcesContent":[null,"import {\n getFullnodeUrl,\n GetTransactionBlockParams,\n SuiClient,\n SuiTransactionBlockResponse,\n} from \"@mysten/sui/client\";\nimport {\n coinWithBalance,\n Transaction,\n TransactionObjectArgument,\n} from \"@mysten/sui/transactions\";\nimport { normalizeStructTag, toBase64 } from \"@mysten/sui/utils\";\nimport { SUI_ADDRESS_ZERO } from \"../../constants/sui\";\nimport {\n Bluefin7kProviderOptions,\n CetusProviderOptions,\n EProvider,\n FlowxProviderOptions,\n isAggregatorProvider,\n isSwapAPIProvider,\n MetaAgOptions,\n MetaFastSwapOptions,\n MetaQuote,\n MetaQuoteOptions,\n MetaSimulationOptions,\n MetaSwapOptions,\n OkxProviderOptions,\n QuoteProvider,\n} from \"../../types/metaAg\";\nimport { isSystemAddress } from \"../../utils/sui\";\nimport { SuiClientUtils } from \"../../utils/SuiClientUtils\";\nimport { getExpectedReturn } from \"../../utils/swap\";\nimport { metaSettle, simulateAggregator, timeout } from \"./common\";\nimport { MetaAgError, MetaAgErrorCode } from \"./error\";\nimport { OkxProvider, simulateOKXSwap } from \"./providers/okx\";\n\nconst HERMES_API = \"https://hermes.pyth.network\";\n\nconst DEFAULT_PROVIDERS: Required<MetaAgOptions>[\"providers\"] = {\n [EProvider.BLUEFIN7K]: {},\n [EProvider.FLOWX]: {},\n [EProvider.CETUS]: {},\n};\n\nexport class MetaAg {\n client: SuiClient;\n private providers: Partial<Record<EProvider, QuoteProvider>> = {};\n private inspector: SuiClientUtils;\n private options: Required<MetaAgOptions>;\n constructor(options?: MetaAgOptions) {\n this.options = {\n providers: { ...DEFAULT_PROVIDERS, ...options?.providers },\n slippageBps: options?.slippageBps ?? 100,\n fullnodeUrl: options?.fullnodeUrl ?? getFullnodeUrl(\"mainnet\"),\n hermesApi: options?.hermesApi ?? HERMES_API,\n partner: options?.partner ?? SUI_ADDRESS_ZERO,\n partnerCommissionBps: options?.partnerCommissionBps ?? 0,\n tipBps: options?.tipBps ?? 0,\n };\n\n this.client = new SuiClient({\n url: this.options.fullnodeUrl,\n });\n\n this.inspector = new SuiClientUtils(this.client);\n }\n\n private async _getProvider(provider: EProvider) {\n const p = this.providers[provider];\n if (p) return p;\n\n const providerOptions = this.options.providers[provider];\n MetaAgError.assert(\n !!providerOptions,\n `Provider not found: ${provider}`,\n MetaAgErrorCode.PROVIDER_NOT_FOUND,\n { provider }\n );\n switch (provider) {\n case EProvider.BLUEFIN7K:\n const { Bluefin7kProvider } = await import(\n \"./providers/bluefin7k\"\n ).catch(catchImportError(EProvider.BLUEFIN7K));\n this.providers[EProvider.BLUEFIN7K] = new Bluefin7kProvider(\n providerOptions as Bluefin7kProviderOptions,\n this.options,\n this.client\n );\n break;\n case EProvider.FLOWX:\n const { FlowxProvider } = await import(\"./providers/flowx\").catch(\n catchImportError(EProvider.FLOWX)\n );\n this.providers[EProvider.FLOWX] = new FlowxProvider(\n providerOptions as FlowxProviderOptions,\n this.client\n );\n break;\n case EProvider.CETUS:\n const { CetusProvider } = await import(\"./providers/cetus\").catch(\n catchImportError(EProvider.CETUS)\n );\n this.providers[EProvider.CETUS] = new CetusProvider(\n providerOptions as CetusProviderOptions,\n this.options,\n this.client\n );\n break;\n case EProvider.OKX:\n this.providers[EProvider.OKX] = new OkxProvider(\n providerOptions as OkxProviderOptions,\n this.options,\n this.client\n );\n break;\n default:\n throw new MetaAgError(\n `Provider not supported: ${provider}`,\n MetaAgErrorCode.PROVIDER_NOT_SUPPORTED,\n { provider }\n );\n }\n return this.providers[provider]!;\n }\n\n private async _simulate(\n provider: QuoteProvider,\n quote: MetaQuote,\n simulation: MetaSimulationOptions\n ) {\n try {\n if (isAggregatorProvider(provider)) {\n return simulateAggregator(\n provider,\n quote,\n simulation,\n this.inspector,\n this.options\n );\n }\n\n switch (quote.provider) {\n case EProvider.OKX:\n return simulateOKXSwap(\n quote,\n this.inspector,\n simulation,\n this.options\n );\n default:\n throw new MetaAgError(\n `Provider not supported: ${provider.kind}`,\n MetaAgErrorCode.PROVIDER_NOT_SUPPORTED,\n { provider: provider.kind }\n );\n }\n } catch (error) {\n console.warn(error, { provider: provider.kind, quote: quote.id });\n }\n }\n\n private async _quote(provider: QuoteProvider, options: MetaQuoteOptions) {\n const quote = await timeout(\n async () => {\n const quote = await provider.quote(options);\n if (!quote) return null;\n const { expectedAmount } = getExpectedReturn(\n quote.rawAmountOut,\n 0,\n this.options.partnerCommissionBps,\n this.options.tipBps\n );\n quote.amountOut = expectedAmount;\n return quote;\n },\n options.timeout ?? 2000,\n `quote for ${provider.kind} provider from ${options.coinTypeIn} to ${options.coinTypeOut}`\n );\n\n return quote;\n }\n\n private async _fastSwap(\n { quote, signer, useGasCoin, signTransaction }: MetaFastSwapOptions,\n getTransactionBlockParams?: Omit<GetTransactionBlockParams, \"digest\">\n ) {\n const tx = new Transaction();\n const coin = await this.swap({\n quote,\n signer,\n tx,\n coinIn: coinWithBalance({\n type: quote.coinTypeIn,\n balance: BigInt(quote.amountIn),\n useGasCoin,\n }),\n });\n tx.transferObjects([coin], signer);\n tx.setSenderIfNotSet(signer);\n const txBytes = await tx.build({ client: this.client });\n const { signature, bytes } = await signTransaction(toBase64(txBytes));\n return this.client.executeTransactionBlock({\n transactionBlock: bytes,\n signature,\n options: getTransactionBlockParams?.options,\n signal: getTransactionBlockParams?.signal,\n });\n }\n\n /**\n * Get quotes from all providers\n * @param options - quote options\n * @param simulation - if present, the quote will be simulated\n * @returns quotes from all providers\n */\n async quote(\n options: MetaQuoteOptions,\n simulation?: MetaSimulationOptions\n ): Promise<MetaQuote[]> {\n const opts: MetaQuoteOptions = {\n ...options,\n coinTypeIn: normalizeStructTag(options.coinTypeIn),\n coinTypeOut: normalizeStructTag(options.coinTypeOut),\n };\n const quotes = await Promise.allSettled(\n Object.entries(this.options.providers)\n .filter(([_k, v]) => !v.disabled)\n .map(async ([provider]) => {\n const p = await this._getProvider(provider as EProvider);\n return this._quote(p, opts);\n })\n );\n const result = quotes\n .map((quote) =>\n quote.status === \"fulfilled\"\n ? quote.value\n : (console.warn(quote.reason), null)\n )\n .filter((quote) => quote !== null);\n\n if (simulation) {\n const requests = result.map(async (quote) => {\n const provider = await this._getProvider(quote.provider);\n const updated = await this._simulate(provider, quote, simulation);\n quote.simulatedAmountOut = updated?.simulatedAmountOut;\n quote.gasUsed = updated?.gasUsed;\n simulation?.onSimulated?.({ ...quote });\n });\n if (!simulation.onSimulated) {\n await Promise.all(requests);\n }\n }\n\n return result;\n }\n\n /**\n * Build transaction from quote\n * @info Use this function to build composable transaction (ie: add more commands after the swap, consume the coin out object)\n * @warning Providers that build transaction on the fly (typically RFQ, Swap-API providers ie: Okx, ...) are not supported, please use `fastSwap` instead\n * @param options - build tx options\n * @param slippageBps - slippage bps if not specified, fallback to global slippage bps, if none of them specified, default to 100\n * @returns coin out object, you must consume it by transferObjects, or other sub sequence commands\n */\n async swap(\n options: MetaSwapOptions,\n slippageBps?: number\n ): Promise<TransactionObjectArgument> {\n const provider = await this._getProvider(options.quote.provider);\n MetaAgError.assert(\n !!provider,\n `Provider not found: ${options.quote.provider}`,\n MetaAgErrorCode.PROVIDER_NOT_FOUND,\n { provider: options.quote.provider }\n );\n MetaAgError.assert(\n isAggregatorProvider(provider),\n `Provider does not support swap: ${provider.kind}, use fastSwap instead`,\n MetaAgErrorCode.PROVIDER_NOT_SUPPORT_SWAP,\n { provider: provider.kind }\n );\n MetaAgError.assert(\n options.signer && !isSystemAddress(options.signer),\n \"Invalid signer address\",\n MetaAgErrorCode.INVALID_SIGNER_ADDRESS,\n { signer: options.signer }\n );\n const coinOut = await provider.swap(options);\n options.tx.add(\n metaSettle(\n options.quote,\n coinOut,\n slippageBps ?? this.options.slippageBps ?? 100,\n this.options.tipBps,\n this.options.partner,\n this.options.partnerCommissionBps\n )\n );\n options.tx.setSenderIfNotSet(options.signer);\n return coinOut;\n }\n\n /**\n * Build, Sign, and Execute transaction in one step\n * @param options - fast swap options\n * @returns - txDigest of the transaction\n */\n async fastSwap(\n options: MetaFastSwapOptions,\n getTransactionBlockParams?: Omit<GetTransactionBlockParams, \"digest\">\n ): Promise<SuiTransactionBlockResponse> {\n MetaAgError.assert(\n options.signer && !isSystemAddress(options.signer),\n \"Invalid signer address\",\n MetaAgErrorCode.INVALID_SIGNER_ADDRESS,\n { signer: options.signer }\n );\n const provider = await this._getProvider(options.quote.provider);\n if (isAggregatorProvider(provider)) {\n return this._fastSwap(options, getTransactionBlockParams);\n } else if (isSwapAPIProvider(provider)) {\n return this.client.waitForTransaction({\n ...getTransactionBlockParams,\n digest: await provider.fastSwap(options),\n });\n } else {\n throw new MetaAgError(\n `Provider not supported: ${provider.kind}`,\n MetaAgErrorCode.PROVIDER_NOT_SUPPORTED,\n { provider: provider.kind }\n );\n }\n }\n\n /**\n * Update meta aggregator options\n * @param options - update options payload\n */\n updateMetaAgOptions(options: MetaAgOptions) {\n if (Object.keys(options).length === 0) return;\n this.options.slippageBps = options.slippageBps ?? this.options.slippageBps;\n this.options.partner = options.partner ?? this.options.partner;\n this.options.partnerCommissionBps =\n options.partnerCommissionBps ?? this.options.partnerCommissionBps;\n this.options.tipBps = options.tipBps ?? this.options.tipBps;\n if (\n options.fullnodeUrl &&\n options.fullnodeUrl !== this.options.fullnodeUrl\n ) {\n this.client = new SuiClient({ url: options.fullnodeUrl });\n this.inspector = new SuiClientUtils(this.client);\n this.options.fullnodeUrl = options.fullnodeUrl;\n }\n if (options.hermesApi && options.hermesApi !== this.options.hermesApi) {\n this.providers = {};\n this.options.hermesApi = options.hermesApi;\n }\n // if update provider's options, we need to re-initialize the provider\n for (const [provider, opt] of Object.entries(options.providers || {})) {\n this.options.providers[provider as EProvider] = {\n ...opt,\n ...this.options.providers[provider as EProvider],\n } as any;\n delete this.providers[provider as EProvider];\n }\n }\n}\n\nconst catchImportError = (provider: EProvider) => {\n return (e: any) => {\n const map = {\n [EProvider.CETUS]: \"@cetusprotocol/aggregator-sdk\",\n [EProvider.FLOWX]: \"@flowx-finance/sdk\",\n [EProvider.BLUEFIN7K]: \"@bluefin-exchange/bluefin7k-aggregator-sdk\",\n [EProvider.OKX]: \"\",\n };\n console.warn(`Please install ${map[provider]} to use ${provider} provider`);\n throw e;\n };\n};\n","export const SUI_ADDRESS_ZERO =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n","import { Transaction, TransactionArgument } from \"@mysten/sui/transactions\";\nimport { normalizeSuiAddress, parseStructTag } from \"@mysten/sui/utils\";\nimport {\n _7K_META_CONFIG,\n _7K_META_PACKAGE_ID,\n _7K_META_VAULT,\n} from \"../constants/_7k\";\n\nexport const SuiUtils = {\n getSuiCoin(\n amount: bigint | TransactionArgument,\n txb: Transaction,\n ): TransactionArgument {\n const [coin] = txb.splitCoins(txb.gas, [amount]);\n return coin;\n },\n\n getCoinValue(\n coinType: string,\n coinObject: string | TransactionArgument,\n txb: Transaction,\n ): TransactionArgument {\n const inputCoinObject =\n typeof coinObject == \"string\" ? txb.object(coinObject) : coinObject;\n const [value] = txb.moveCall({\n target: `0x2::coin::value`,\n typeArguments: [coinType],\n arguments: [inputCoinObject],\n });\n return value;\n },\n\n isValidStructTag(value: string) {\n try {\n return !!parseStructTag(value);\n } catch (_) {\n return false;\n }\n },\n\n zeroBalance(tx: Transaction, coinType: string) {\n return tx.moveCall({\n target: `0x2::balance::zero`,\n typeArguments: [coinType],\n arguments: [],\n })[0];\n },\n\n zeroCoin(tx: Transaction, coinType: string) {\n return tx.moveCall({\n target: `0x2::coin::zero`,\n typeArguments: [coinType],\n arguments: [],\n })[0];\n },\n\n coinIntoBalance(\n tx: Transaction,\n coinType: string,\n coinObject: TransactionArgument,\n ) {\n return tx.moveCall({\n target: `0x2::coin::into_balance`,\n typeArguments: [coinType],\n arguments: [coinObject],\n })[0];\n },\n\n coinFromBalance(\n tx: Transaction,\n coinType: string,\n balance: TransactionArgument,\n ) {\n return tx.moveCall({\n target: `0x2::coin::from_balance`,\n typeArguments: [coinType],\n arguments: [balance],\n })[0];\n },\n\n balanceDestroyZero(\n tx: Transaction,\n coinType: string,\n balance: TransactionArgument,\n ) {\n tx.moveCall({\n target: `0x2::balance::destroy_zero`,\n typeArguments: [coinType],\n arguments: [balance],\n });\n },\n\n collectDust(tx: Transaction, coinType: string, coin: TransactionArgument) {\n tx.moveCall({\n target: `${_7K_META_PACKAGE_ID}::vault::collect_dust`,\n typeArguments: [coinType],\n arguments: [tx.object(_7K_META_VAULT), tx.object(_7K_META_CONFIG), coin],\n });\n },\n\n transferOrDestroyZeroCoin(\n tx: Transaction,\n coinType: string,\n coin: TransactionArgument,\n address: string,\n ) {\n tx.moveCall({\n target: `${_7K_META_PACKAGE_ID}::utils::transfer_or_destroy`,\n typeArguments: [coinType],\n arguments: [coin, tx.pure.address(address)],\n });\n },\n};\n\nconst RESERVED_ADDRESSES = [\n \"0x0000000000000000000000000000000000000000000000000000000000000000\", // zero\n \"0x0000000000000000000000000000000000000000000000000000000000000001\", // std\n \"0x0000000000000000000000000000000000000000000000000000000000000002\", // sui framework\n \"0x0000000000000000000000000000000000000000000000000000000000000003\", // unknown but we reserved to be safe\n \"0x0000000000000000000000000000000000000000000000000000000000000004\", // unknown but we reserved to be safe\n \"0x0000000000000000000000000000000000000000000000000000000000000005\", // system state\n \"0x0000000000000000000000000000000000000000000000000000000000000006\", // time\n \"0x0000000000000000000000000000000000000000000000000000000000000007\", // unknown but we reserved to be safe\n \"0x0000000000000000000000000000000000000000000000000000000000000008\", // random\n \"0x0000000000000000000000000000000000000000000000000000000000000009\", // unknown but we reserved to be safe\n \"0x0000000000000000000000000000000000000000000000000000000000000403\", // coin deny list\n \"0x000000000000000000000000000000000000000000000000000000000000000c\", // coin registry\n];\n\nexport const isSystemAddress = (address: string) => {\n const addr = normalizeSuiAddress(address);\n return RESERVED_ADDRESSES.includes(addr);\n};\n","import {\n DevInspectTransactionBlockParams,\n SuiClient,\n} from \"@mysten/sui/client\";\nimport { Transaction } from \"@mysten/sui/transactions\";\nimport { CustomObjectCache } from \"./ObjectCache\";\n\n/**\n * Utility class for interacting with Sui blockchain coins\n */\nexport class SuiClientUtils {\n #devInspectCache: CustomObjectCache;\n /**\n * Creates a new instance of SuiClientUtils\n * @param client - The Sui client instance to use for blockchain interactions\n */\n constructor(private client: SuiClient) {\n this.#devInspectCache = new CustomObjectCache({ client: this.client });\n }\n\n devInspectTransactionBlock = async (\n params: DevInspectTransactionBlockParams,\n ) => {\n if (params.transactionBlock instanceof Transaction) {\n params.transactionBlock.addBuildPlugin(this.#devInspectCache.asPlugin());\n }\n try {\n const res = await this.client.devInspectTransactionBlock(params);\n return res;\n } catch (error) {\n // clear all cache if devInspectTransactionBlock fails\n await this.#devInspectCache.clear();\n throw error;\n } finally {\n await this.#devInspectCache.clearOwnedObjects();\n }\n };\n}\n","import { bcs } from \"@mysten/sui/bcs\";\nimport { SuiClient } from \"@mysten/sui/client\";\nimport {\n OpenMoveTypeSignature,\n TransactionDataBuilder,\n TransactionPlugin,\n} from \"@mysten/sui/transactions\";\nimport { normalizeSuiAddress } from \"@mysten/sui/utils\";\n\nexport interface ObjectCacheEntry {\n objectId: string;\n version: string;\n digest: string;\n owner: string | null;\n initialSharedVersion: string | null;\n}\n\nexport interface MoveFunctionCacheEntry {\n package: string;\n module: string;\n function: string;\n parameters: OpenMoveTypeSignature[];\n}\n\nexport interface CacheEntryTypes {\n OwnedObject: ObjectCacheEntry;\n SharedOrImmutableObject: ObjectCacheEntry;\n MoveFunction: MoveFunctionCacheEntry;\n Custom: unknown;\n}\nexport abstract class AsyncCache {\n protected abstract get<T extends keyof CacheEntryTypes>(\n type: T,\n key: string,\n ): Promise<CacheEntryTypes[T] | null>;\n protected abstract set<T extends keyof CacheEntryTypes>(\n type: T,\n key: string,\n value: CacheEntryTypes[T],\n ): Promise<void>;\n protected abstract delete<T extends keyof CacheEntryTypes>(\n type: T,\n key: string,\n ): Promise<void>;\n abstract clear<T extends keyof CacheEntryTypes>(type?: T): Promise<void>;\n\n async getObject(id: string) {\n const [owned, shared] = await Promise.all([\n this.get(\"OwnedObject\", id),\n this.get(\"SharedOrImmutableObject\", id),\n ]);\n\n return owned ?? shared ?? null;\n }\n\n async getObjects(ids: string[]) {\n return Promise.all(ids.map((id) => this.getObject(id)));\n }\n\n async addObject(object: ObjectCacheEntry) {\n if (object.owner) {\n await this.set(\"OwnedObject\", object.objectId, object);\n } else {\n await this.set(\"SharedOrImmutableObject\", object.objectId, object);\n }\n\n return object;\n }\n\n async addObjects(objects: ObjectCacheEntry[]) {\n await Promise.all(objects.map(async (object) => this.addObject(object)));\n }\n\n async deleteObject(id: string) {\n await Promise.all([\n this.delete(\"OwnedObject\", id),\n this.delete(\"SharedOrImmutableObject\", id),\n ]);\n }\n\n async deleteObjects(ids: string[]) {\n await Promise.all(ids.map((id) => this.deleteObject(id)));\n }\n\n async getMoveFunctionDefinition(ref: {\n package: string;\n module: string;\n function: string;\n }) {\n const functionName = `${normalizeSuiAddress(ref.package)}::${ref.module}::${ref.function}`;\n return this.get(\"MoveFunction\", functionName);\n }\n\n async addMoveFunctionDefinition(functionEntry: MoveFunctionCacheEntry) {\n const pkg = normalizeSuiAddress(functionEntry.package);\n const functionName = `${pkg}::${functionEntry.module}::${functionEntry.function}`;\n const entry = {\n ...functionEntry,\n package: pkg,\n };\n\n await this.set(\"MoveFunction\", functionName, entry);\n\n return entry;\n }\n\n async deleteMoveFunctionDefinition(ref: {\n package: string;\n module: string;\n function: string;\n }) {\n const functionName = `${normalizeSuiAddress(ref.package)}::${ref.module}::${ref.function}`;\n await this.delete(\"MoveFunction\", functionName);\n }\n\n async getCustom<T>(key: string) {\n return this.get(\"Custom\", key) as Promise<T | null>;\n }\n\n async setCustom<T>(key: string, value: T) {\n return this.set(\"Custom\", key, value);\n }\n\n async deleteCustom(key: string) {\n return this.delete(\"Custom\", key);\n }\n}\n\nexport class InMemoryObjectCache extends AsyncCache {\n #caches = {\n OwnedObject: new Map<string, ObjectCacheEntry>(),\n SharedOrImmutableObject: new Map<string, ObjectCacheEntry>(),\n MoveFunction: new Map<string, MoveFunctionCacheEntry>(),\n Custom: new Map<string, unknown>(),\n };\n\n protected async get<T extends keyof CacheEntryTypes>(type: T, key: string) {\n return (this.#caches[type].get(key) as CacheEntryTypes[T]) ?? null;\n }\n\n protected async set<T extends keyof CacheEntryTypes>(\n type: T,\n key: string,\n value: CacheEntryTypes[T],\n ) {\n (this.#caches[type] as Map<string, typeof value>).set(key, value as never);\n }\n\n protected async delete<T extends keyof CacheEntryTypes>(\n type: T,\n key: string,\n ) {\n this.#caches[type].delete(key);\n }\n\n async clear<T extends keyof CacheEntryTypes>(type?: T) {\n if (type) {\n this.#caches[type].clear();\n } else {\n for (const cache of Object.values(this.#caches)) {\n cache.clear();\n }\n }\n }\n}\n\nexport interface ObjectCacheOptions {\n cache?: AsyncCache;\n client: SuiClient;\n onEffects?: (\n effects: typeof bcs.TransactionEffects.$inferType,\n ) => Promise<void>;\n}\n\nexport class CustomObjectCache {\n #client: SuiClient;\n #cache: AsyncCache;\n #onEffects?: (\n effects: typeof bcs.TransactionEffects.$inferType,\n ) => Promise<void>;\n\n constructor({\n cache = new InMemoryObjectCache(),\n onEffects,\n client,\n }: ObjectCacheOptions) {\n this.#client = client;\n this.#cache = cache;\n this.#onEffects = onEffects;\n }\n\n private async applyCache(\n transactionData: TransactionDataBuilder,\n unresolvedObjects: string[],\n ) {\n const cached = (await this.#cache.getObjects(unresolvedObjects)).filter(\n (obj) => obj !== null,\n );\n\n const byId = new Map(cached.map((obj) => [obj!.objectId, obj]));\n const unresolved: string[] = [];\n for (const input of transactionData.inputs) {\n if (!input.UnresolvedObject) {\n continue;\n }\n\n const cached = byId.get(input.UnresolvedObject.objectId);\n\n if (!cached) {\n unresolved.push(input.UnresolvedObject.objectId);\n continue;\n }\n\n if (\n cached.initialSharedVersion &&\n !input.UnresolvedObject.initialSharedVersion\n ) {\n input.UnresolvedObject.initialSharedVersion =\n cached.initialSharedVersion;\n } else {\n if (cached.version && !input.UnresolvedObject.version) {\n input.UnresolvedObject.version = cached.version;\n }\n\n if (cached.digest && !input.UnresolvedObject.digest) {\n input.UnresolvedObject.digest = cached.digest;\n }\n }\n }\n return unresolved;\n }\n\n private async resolveObjects(\n transactionData: TransactionDataBuilder,\n unresolved: string[],\n ) {\n const unresolvedObjects = await this.applyCache(\n transactionData,\n unresolved,\n );\n if (unresolvedObjects.length === 0) {\n return [];\n }\n const dedup = [...new Set(unresolvedObjects)];\n const res = await this.#client.multiGetObjects({\n ids: dedup,\n options: {\n showOwner: true,\n },\n });\n const objects: ObjectCacheEntry[] = [];\n for (const obj of res || []) {\n if (!obj.data) {\n continue;\n }\n const owner = obj.data.owner;\n\n const initialSharedVersion =\n owner && typeof owner === \"object\" && \"Shared\" in owner\n ? owner.Shared.initial_shared_version\n : null;\n const ownerAddress =\n owner && typeof owner === \"object\" && \"AddressOwner\" in owner\n ? owner.AddressOwner\n : null;\n const cached: ObjectCacheEntry = {\n objectId: obj.data.objectId,\n version: obj.data.version,\n digest: obj.data.digest,\n initialSharedVersion,\n owner: ownerAddress,\n };\n objects.push(cached);\n }\n await this.#cache.addObjects(objects);\n return await this.applyCache(transactionData, unresolvedObjects);\n }\n\n asPlugin(): TransactionPlugin {\n return async (transactionData, _options, next) => {\n const unresolvedObjects = transactionData.inputs\n .filter((input) => input.UnresolvedObject)\n .map((input) => input.UnresolvedObject!.objectId);\n\n // if object is not in cache yet, fetch from RPC and save to cache and resolve all objects\n await this.resolveObjects(transactionData, unresolvedObjects);\n\n await Promise.all(\n transactionData.commands.map(async (commands) => {\n if (commands.MoveCall) {\n const def = await this.getMoveFunctionDefinition({\n package: commands.MoveCall.package,\n module: commands.MoveCall.module,\n function: commands.MoveCall.function,\n });\n\n if (def) {\n commands.MoveCall._argumentTypes = def.parameters;\n }\n }\n }),\n );\n\n await next();\n\n await Promise.all(\n transactionData.commands.map(async (commands) => {\n if (commands.MoveCall?._argumentTypes) {\n await this.#cache.addMoveFunctionDefinition({\n package: commands.MoveCall.package,\n module: commands.MoveCall.module,\n function: commands.MoveCall.function,\n parameters: commands.MoveCall._argumentTypes,\n });\n }\n }),\n );\n };\n }\n\n async clear() {\n await this.#cache.clear();\n }\n\n async getMoveFunctionDefinition(ref: {\n package: string;\n module: string;\n function: string;\n }) {\n return this.#cache.getMoveFunctionDefinition(ref);\n }\n\n async getObjects(ids: string[]) {\n return this.#cache.getObjects(ids);\n }\n\n async deleteObjects(ids: string[]) {\n return this.#cache.deleteObjects(ids);\n }\n\n async clearOwnedObjects() {\n await this.#cache.clear(\"OwnedObject\");\n }\n\n async clearCustom() {\n await this.#cache.clear(\"Custom\");\n }\n\n async getCustom<T>(key: string) {\n return this.#cache.getCustom<T>(key);\n }\n\n async setCustom<T>(key: string, value: T) {\n return this.#cache.setCustom(key, value);\n }\n\n async deleteCustom(key: string) {\n return this.#cache.deleteCustom(key);\n }\n\n async applyEffects(effects: typeof bcs.TransactionEffects.$inferType) {\n if (!effects.V2) {\n throw new Error(\n `Unsupported transaction effects version ${effects.$kind}`,\n );\n }\n\n const { lamportVersion, changedObjects } = effects.V2;\n\n const deletedIds: string[] = [];\n const addedObjects: ObjectCacheEntry[] = [];\n\n changedObjects.forEach(([id, change]) => {\n if (change.outputState.NotExist) {\n deletedIds.push(id);\n } else if (change.outputState.ObjectWrite) {\n const [digest, owner] = change.outputState.ObjectWrite;\n\n addedObjects.push({\n objectId: id,\n digest,\n version: lamportVersion,\n owner: owner.AddressOwner ?? owner.ObjectOwner ?? null,\n initialSharedVersion: owner.Shared?.initialSharedVersion ?? null,\n });\n }\n });\n\n await Promise.all([\n this.#cache.addObjects(addedObjects),\n this.#cache.deleteObjects(deletedIds),\n this.#onEffects?.(effects),\n ]);\n }\n}\n"]}