@7kprotocol/sdk-ts 3.5.0 → 3.5.2-beta.0

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 (104) hide show
  1. package/README.md +45 -171
  2. package/lib/cjs/config/index.js +9 -0
  3. package/lib/cjs/constants/_7k.js +2 -1
  4. package/lib/cjs/features/metaAg/common.js +117 -0
  5. package/lib/cjs/features/metaAg/index.js +88 -93
  6. package/lib/cjs/features/metaAg/providers/astro.js +42 -0
  7. package/lib/cjs/features/metaAg/providers/bluefin.js +8 -8
  8. package/lib/cjs/features/metaAg/providers/bluefinx.js +87 -0
  9. package/lib/cjs/features/metaAg/providers/cetus.js +7 -4
  10. package/lib/cjs/features/metaAg/providers/flowx.js +6 -4
  11. package/lib/cjs/features/metaAg/providers/okx.js +181 -0
  12. package/lib/cjs/features/swap/buildTx.js +3 -0
  13. package/lib/cjs/features/swap/buildTxV2.js +10 -6
  14. package/lib/cjs/features/swap/config.js +2 -1
  15. package/lib/cjs/features/swap/getQuote.js +3 -2
  16. package/lib/cjs/libs/protocols/bluefinx/client.js +1 -1
  17. package/lib/cjs/types/config/index.d.ts +4 -0
  18. package/lib/cjs/types/config/index.d.ts.map +1 -1
  19. package/lib/cjs/types/constants/_7k.d.ts +1 -0
  20. package/lib/cjs/types/constants/_7k.d.ts.map +1 -1
  21. package/lib/cjs/types/features/metaAg/common.d.ts +33 -0
  22. package/lib/cjs/types/features/metaAg/common.d.ts.map +1 -0
  23. package/lib/cjs/types/features/metaAg/index.d.ts +11 -2
  24. package/lib/cjs/types/features/metaAg/index.d.ts.map +1 -1
  25. package/lib/cjs/types/features/metaAg/providers/astro.d.ts +9 -0
  26. package/lib/cjs/types/features/metaAg/providers/astro.d.ts.map +1 -0
  27. package/lib/cjs/types/features/metaAg/providers/bluefin.d.ts +3 -3
  28. package/lib/cjs/types/features/metaAg/providers/bluefin.d.ts.map +1 -1
  29. package/lib/cjs/types/features/metaAg/providers/bluefinx.d.ts +10 -0
  30. package/lib/cjs/types/features/metaAg/providers/bluefinx.d.ts.map +1 -0
  31. package/lib/cjs/types/features/metaAg/providers/cetus.d.ts +4 -5
  32. package/lib/cjs/types/features/metaAg/providers/cetus.d.ts.map +1 -1
  33. package/lib/cjs/types/features/metaAg/providers/flowx.d.ts +3 -3
  34. package/lib/cjs/types/features/metaAg/providers/flowx.d.ts.map +1 -1
  35. package/lib/cjs/types/features/metaAg/providers/okx.d.ts +21 -0
  36. package/lib/cjs/types/features/metaAg/providers/okx.d.ts.map +1 -0
  37. package/lib/cjs/types/features/swap/buildTx.d.ts.map +1 -1
  38. package/lib/cjs/types/features/swap/buildTxV2.d.ts +3 -3
  39. package/lib/cjs/types/features/swap/buildTxV2.d.ts.map +1 -1
  40. package/lib/cjs/types/features/swap/config.d.ts.map +1 -1
  41. package/lib/cjs/types/features/swap/getQuote.d.ts +1 -3
  42. package/lib/cjs/types/features/swap/getQuote.d.ts.map +1 -1
  43. package/lib/cjs/types/index.d.ts +3 -1
  44. package/lib/cjs/types/index.d.ts.map +1 -1
  45. package/lib/cjs/types/metaAg.js +11 -4
  46. package/lib/cjs/types/okx.js +6 -0
  47. package/lib/cjs/types/types/metaAg.d.ts +60 -8
  48. package/lib/cjs/types/types/metaAg.d.ts.map +1 -1
  49. package/lib/cjs/types/types/okx.d.ts +193 -0
  50. package/lib/cjs/types/types/okx.d.ts.map +1 -0
  51. package/lib/cjs/types/utils/condition.d.ts +1 -1
  52. package/lib/cjs/types/utils/condition.d.ts.map +1 -1
  53. package/lib/esm/config/index.js +9 -0
  54. package/lib/esm/constants/_7k.js +1 -0
  55. package/lib/esm/features/metaAg/common.js +109 -0
  56. package/lib/esm/features/metaAg/index.js +89 -94
  57. package/lib/esm/features/metaAg/providers/astro.js +39 -0
  58. package/lib/esm/features/metaAg/providers/bluefin.js +8 -8
  59. package/lib/esm/features/metaAg/providers/bluefinx.js +84 -0
  60. package/lib/esm/features/metaAg/providers/cetus.js +7 -4
  61. package/lib/esm/features/metaAg/providers/flowx.js +7 -5
  62. package/lib/esm/features/metaAg/providers/okx.js +146 -0
  63. package/lib/esm/features/swap/buildTx.js +3 -0
  64. package/lib/esm/features/swap/buildTxV2.js +6 -2
  65. package/lib/esm/features/swap/config.js +2 -1
  66. package/lib/esm/features/swap/getQuote.js +3 -2
  67. package/lib/esm/libs/protocols/bluefinx/client.js +1 -1
  68. package/lib/esm/types/config/index.d.ts +4 -0
  69. package/lib/esm/types/config/index.d.ts.map +1 -1
  70. package/lib/esm/types/constants/_7k.d.ts +1 -0
  71. package/lib/esm/types/constants/_7k.d.ts.map +1 -1
  72. package/lib/esm/types/features/metaAg/common.d.ts +33 -0
  73. package/lib/esm/types/features/metaAg/common.d.ts.map +1 -0
  74. package/lib/esm/types/features/metaAg/index.d.ts +11 -2
  75. package/lib/esm/types/features/metaAg/index.d.ts.map +1 -1
  76. package/lib/esm/types/features/metaAg/providers/astro.d.ts +9 -0
  77. package/lib/esm/types/features/metaAg/providers/astro.d.ts.map +1 -0
  78. package/lib/esm/types/features/metaAg/providers/bluefin.d.ts +3 -3
  79. package/lib/esm/types/features/metaAg/providers/bluefin.d.ts.map +1 -1
  80. package/lib/esm/types/features/metaAg/providers/bluefinx.d.ts +10 -0
  81. package/lib/esm/types/features/metaAg/providers/bluefinx.d.ts.map +1 -0
  82. package/lib/esm/types/features/metaAg/providers/cetus.d.ts +4 -5
  83. package/lib/esm/types/features/metaAg/providers/cetus.d.ts.map +1 -1
  84. package/lib/esm/types/features/metaAg/providers/flowx.d.ts +3 -3
  85. package/lib/esm/types/features/metaAg/providers/flowx.d.ts.map +1 -1
  86. package/lib/esm/types/features/metaAg/providers/okx.d.ts +21 -0
  87. package/lib/esm/types/features/metaAg/providers/okx.d.ts.map +1 -0
  88. package/lib/esm/types/features/swap/buildTx.d.ts.map +1 -1
  89. package/lib/esm/types/features/swap/buildTxV2.d.ts +3 -3
  90. package/lib/esm/types/features/swap/buildTxV2.d.ts.map +1 -1
  91. package/lib/esm/types/features/swap/config.d.ts.map +1 -1
  92. package/lib/esm/types/features/swap/getQuote.d.ts +1 -3
  93. package/lib/esm/types/features/swap/getQuote.d.ts.map +1 -1
  94. package/lib/esm/types/index.d.ts +3 -1
  95. package/lib/esm/types/index.d.ts.map +1 -1
  96. package/lib/esm/types/metaAg.js +8 -2
  97. package/lib/esm/types/okx.js +5 -0
  98. package/lib/esm/types/types/metaAg.d.ts +60 -8
  99. package/lib/esm/types/types/metaAg.d.ts.map +1 -1
  100. package/lib/esm/types/types/okx.d.ts +193 -0
  101. package/lib/esm/types/types/okx.d.ts.map +1 -0
  102. package/lib/esm/types/utils/condition.d.ts +1 -1
  103. package/lib/esm/types/utils/condition.d.ts.map +1 -1
  104. package/package.json +3 -2
package/README.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # 7K TypeScript SDK
2
2
 
3
+ The 7K Protocol TypeScript SDK provides a comprehensive toolkit for interacting
4
+ with DeFi services on the Sui blockchain. It offers seamless integration with
5
+ token swaps, price feeds, limit orders, dollar-cost averaging (DCA), and
6
+ multi-provider aggregation services.
7
+
8
+ ## Introduction
9
+
10
+ The 7K TypeScript SDK is designed to simplify DeFi development on Sui by
11
+ providing a unified, type-safe interface for accessing liquidity and trading
12
+ services. Whether you're building a wallet, trading application, or DeFi
13
+ protocol, this SDK offers the tools you need to integrate advanced trading
14
+ functionality.
15
+
16
+ Key features:
17
+
18
+ - **Meta Aggregator (Active Simulation)**: The SDK includes an active simulation
19
+ of the Meta Aggregator, allowing developers to test and compare quotes from
20
+ multiple sources — including Bluefin7K, FlowX, and Cetus. This provides a
21
+ preview of how the unified aggregator will optimize routing and liquidity
22
+ aggregation across providers.
23
+
24
+ ➤ Additional aggregators and RFQ-based liquidity sources are planned for
25
+ integration in future releases.
26
+
27
+ - **Price Service**: Fetch token prices with support for single tokens and batch
28
+ queries
29
+ - **Limit Orders**: Place and manage limit orders for token swaps
30
+ - **DCA Orders**: Set up dollar-cost averaging strategies for automated
31
+ recurring purchases
32
+ - **BluefinX Integration**: Access RFQ-based trading with sponsored transactions
33
+ and MEV protection
34
+ - **Type Safety**: Full TypeScript support with comprehensive type definitions
35
+ - **Mainnet Support**: Production-ready SDK for Sui mainnet
36
+ - **Flexible Configuration**: Customize API keys, slippage, commissions, and
37
+ more
38
+
39
+ The SDK is built with developer experience in mind, providing both a default
40
+ export for convenience and named exports for tree-shaking and modular
41
+ development.
42
+
3
43
  ## Installation
4
44
 
5
45
  ```bash
@@ -12,7 +52,7 @@ This package has peer dependencies that are required for core functionality:
12
52
 
13
53
  | Package | Version | Purpose | Required For |
14
54
  | -------------------------- | --------- | ---------------------------- | ------------------ |
15
- | `@mysten/sui` | `^1.39.0` | Sui blockchain interaction | Core functionality |
55
+ | `@mysten/sui` | `^1.44.0` | Sui blockchain interaction | Core functionality |
16
56
  | `@pythnetwork/pyth-sui-js` | `^2.2.0` | Pyth price feeds integration | Price feeds |
17
57
 
18
58
  **Required peer dependencies:**
@@ -75,65 +115,11 @@ or import specific functions as needed:
75
115
  import { getQuote, buildTx } from "@7kprotocol/sdk-ts";
76
116
  ```
77
117
 
78
- ## Config
79
-
80
- Configuration is optional, but if provided, it must be set before invoking any
81
- SDK functions.
82
-
83
- ### Set API Key
84
-
85
- You can use our SDK with a default rate limit of **5 requests per second**
86
- without needing an API key.
87
-
88
- - For **frontend (in-browser) usage**, no API key is required, and the rate
89
- limit cannot be increased.
90
-
91
- - For **backend (server-side) usage**, the API key is **optional** for default
92
- usage. However, to request a **higher rate limit**, you must provide both an
93
- **API key** and **partner information**.
94
-
95
- To request a rate limit increase, please submit your request at:
96
-
97
- 🔗 <https://7k.ag/collab> and select **"SDK - increase request rate"**.
98
-
99
- | Usage | API Key Required | Default Rate Limit | Can Request Higher Rate Limit |
100
- | -------- | ------------------------------------- | ------------------------------- | -------------------------------------------- |
101
- | Frontend | No | 5 requests/second | No |
102
- | Backend | Optional (required to increase limit) | 5 requests/second (without key) | Yes (requires API Key & partner information) |
103
-
104
- ```typescript
105
- import { Config } from "@7kprotocol/sdk-ts";
106
-
107
- Config.setApiKey("YOUR_API_KEY");
108
- console.log("API key", Config.getApiKey());
109
- ```
110
-
111
- ### Set BluefinX API key
112
-
113
- Setting a BluefinX API key is optional. However, if you'd like to use one — for
114
- example, to avoid rate limits when routing through BluefinX — you'll need to
115
- request an API key directly from Bluefin.
116
-
117
- ```typescript
118
- import { Config } from "@7kprotocol/sdk-ts";
119
-
120
- Config.setBluefinXApiKey("YOUR_BLUEFINX_API_KEY");
121
- console.log("BluefinX API key", Config.getBluefinXApiKey());
122
- ```
123
-
124
- ### Set Sui Client
125
-
126
- ```typescript
127
- import { SuiClient, getFullnodeUrl } from "@mysten/sui/client";
128
- import { Config } from "@7kprotocol/sdk-ts";
118
+ Note: this package only supports **mainnet**.
129
119
 
130
- const network = "mainnet";
131
- const suiClient = new SuiClient({ url: getFullnodeUrl(network) });
132
- Config.setSuiClient(suiClient);
133
- console.log("Sui client", Config.getSuiClient());
134
- ```
120
+ ## MetaAg (Multi-Provider Aggregation)
135
121
 
136
- Note: this package only supports **mainnet**.
122
+ See [Meta Aggregator](docs/META_AG.md).
137
123
 
138
124
  ## Swap
139
125
 
@@ -151,121 +137,9 @@ See [Limit Orders](docs/LIMIT.md).
151
137
 
152
138
  See [DCA Orders](docs/DCA.md).
153
139
 
154
- ## MetaAg (Multi-Provider Aggregation)
155
-
156
- The MetaAg feature allows you to aggregate quotes from multiple DEX Aggregator
157
- providers. By default, all available providers are enabled. You can optionally
158
- configure specific providers or install optional dependencies to enable
159
- additional providers.
160
-
161
- ### Using Default Providers
162
-
163
- The Bluefin7K provider is built-in and works without additional dependencies:
164
-
165
- ```typescript
166
- import { MetaAg, EProvider } from "@7kprotocol/sdk-ts";
167
-
168
- const metaAg = new MetaAg();
169
-
170
- // Get quotes from all available providers
171
- const quotes = await metaAg.quote({
172
- amountIn: "1000000000", // 1 SUI (9 decimals)
173
- coinInType:
174
- "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
175
- coinOutType:
176
- "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",
177
- });
178
-
179
- // Find the best quote
180
- const bestQuote = quotes.reduce((best, current) =>
181
- Number(current.amountOut) > Number(best.amountOut) ? current : best,
182
- );
183
- ```
184
-
185
- ### Configuring Specific Providers
186
-
187
- You can configure specific providers and their options:
188
-
189
- ```typescript
190
- const metaAg = new MetaAg({
191
- providers: {
192
- [EProvider.BLUEFIN7K]: {
193
- apiKey: "your-bluefin-api-key", // Optional
194
- },
195
- [EProvider.FLOWX]: {
196
- apiKey: "your-flowx-api-key", // Optional
197
- },
198
- [EProvider.CETUS]: {
199
- apiKey: "your-cetus-api-key", // Optional
200
- },
201
- },
202
- });
203
- ```
204
-
205
- **Note**: To use Flowx or Cetus providers, you must install their respective
206
- optional dependencies. See the
207
- [Optional Dependencies](#optional-dependencies-for-metaag-providers) section
208
- above.
209
-
210
- ### Sponsored Transactions
211
-
212
- When building sponsored transactions, `tx.gas` can not be used for swap.
213
-
214
- **Important considerations:**
215
-
216
- 1. **Gas coin usage**: Set `useGasCoin: false` when creating your coin input
217
- object to prevent the SDK from trying to use `tx.gas`.
218
-
219
- 2. **Pyth oracle dependencies**: Transactions that use the gas coin cannot be
220
- sponsored because Pyth oracle fees are paid from `tx.gas`. Exclude DEX
221
- sources that depend on Pyth oracles.
222
-
223
- **Example configuration:**
224
-
225
- ```typescript
226
- import { MetaAg, EProvider } from "@7kprotocol/sdk-ts";
227
- import { coinWithBalance } from "@mysten/sui/transactions";
228
- import { Protocol } from "@flowx-finance/sdk"; // Required for Flowx sources
229
- import { CETUS, BLUEFIN } from "@cetusprotocol/aggregator-sdk
230
-
231
- const metaAg = new MetaAg({
232
- providers: {
233
- [EProvider.BLUEFIN7K]: {
234
- sources: ["cetus", "bluefin"], // Excludes Pyth oracle-based DEX
235
- },
236
- [EProvider.FLOWX]: {
237
- sources: [Protocol.BLUEFIN, Protocol.CETUS, Protocol.FLOWX_V3],
238
- },
239
- [EProvider.CETUS]: {
240
- sources: [CETUS, BLUEFIN],
241
- },
242
- },
243
- });
244
-
245
- // Create coin input WITHOUT using the gas coin
246
- const coinIn = coinWithBalance({
247
- balance: 1000000000n, // 1 SUI
248
- type: "0x2::sui::SUI",
249
- useGasCoin: false, // Important: must be false for sponsored transactions
250
- });
251
- ```
252
-
253
140
  ## Prices
254
141
 
255
- ```typescript
256
- import { getTokenPrice, getTokenPrices, getSuiPrice } from "@7kprotocol/sdk-ts";
257
-
258
- const tokenPrice = await getTokenPrice(
259
- "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",
260
- );
261
-
262
- const tokenPrices = await getTokenPrices([
263
- "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
264
- "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",
265
- ]);
266
-
267
- const suiPrice = await getSuiPrice();
268
- ```
142
+ See [Prices](docs/PRICE.md).
269
143
 
270
144
  ## Miscellaneous
271
145
 
@@ -6,6 +6,7 @@ const pyth_sui_js_1 = require("@pythnetwork/pyth-sui-js");
6
6
  const HERMES_API = "https://hermes.pyth.network";
7
7
  const WORMHOLE_STATE_ID = "0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c";
8
8
  const PYTH_STATE_ID = "0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8";
9
+ let api = "";
9
10
  let apiKey = "";
10
11
  let bluefinXApiKey = "";
11
12
  let suiClient = new client_1.SuiClient({
@@ -13,6 +14,12 @@ let suiClient = new client_1.SuiClient({
13
14
  });
14
15
  let pythClient = new pyth_sui_js_1.SuiPythClient(suiClient, PYTH_STATE_ID, WORMHOLE_STATE_ID);
15
16
  let pythConnection = new pyth_sui_js_1.SuiPriceServiceConnection(HERMES_API);
17
+ function setApi(url) {
18
+ api = url;
19
+ }
20
+ function getApi() {
21
+ return api;
22
+ }
16
23
  function setApiKey(key) {
17
24
  apiKey = key;
18
25
  }
@@ -44,6 +51,8 @@ function getPythConnection() {
44
51
  return pythConnection;
45
52
  }
46
53
  const Config = {
54
+ setApi,
55
+ getApi,
47
56
  setApiKey,
48
57
  getApiKey,
49
58
  setBluefinXApiKey,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._7K_META_CONFIG = exports._7K_META_VAULT = exports._7K_META_PACKAGE_ID = exports._7K_META_PUBLISHED_AT = exports._7K_VAULT = exports._7K_CONFIG = exports._7K_PACKAGE_ID = void 0;
3
+ exports._7K_PARTNER_ADDRESS = exports._7K_META_CONFIG = exports._7K_META_VAULT = exports._7K_META_PACKAGE_ID = exports._7K_META_PUBLISHED_AT = exports._7K_VAULT = exports._7K_CONFIG = exports._7K_PACKAGE_ID = void 0;
4
4
  exports._7K_PACKAGE_ID = "0x62412b7268c35f3808336aee57a52836501f40b8ba5d936f8ad275e672befd04";
5
5
  //legacy V4: "0xe8f996ea6ff38c557c253d3b93cfe2ebf393816487266786371aa4532a9229f2";
6
6
  //legacy V3: "0x7ea6e27ad7af6f3b8671d59df1aaebd7c03dddab893e52a714227b2f4fe91519";
@@ -14,3 +14,4 @@ exports._7K_META_PUBLISHED_AT = "0x17c0b1f7a6ad73f51268f16b8c06c049eecc2f28a270c
14
14
  exports._7K_META_PACKAGE_ID = "0x17c0b1f7a6ad73f51268f16b8c06c049eecc2f28a270cdd29c06e3d2dea23302";
15
15
  exports._7K_META_VAULT = "0x9a8abd32fe5721307ce3b697cf982ee84e9ffbd58d667a4a199f1683c1a3d23c";
16
16
  exports._7K_META_CONFIG = "0xbbb3a51877ed9b492f26f4e2181811cfb2bd70c532f6f7621263d122d5e96b56";
17
+ exports._7K_PARTNER_ADDRESS = "0x93ead46c1e48a9b62e25b6787f2ea6f75caedabb21726f12431acc4381f5f4c5";
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.timeout = exports.metaSettle = exports.simulateAggregator = exports.simulateSwapTx = exports.simulateBluefinX = void 0;
4
+ const transactions_1 = require("@mysten/sui/transactions");
5
+ const _7k_1 = require("../../constants/_7k");
6
+ const buildTx_1 = require("../swap/buildTx");
7
+ const DEFAULT_GAS_USED = {
8
+ computationCost: "0",
9
+ nonRefundableStorageFee: "0",
10
+ storageCost: "0",
11
+ storageRebate: "0",
12
+ };
13
+ const simulateBluefinX = (quote) => {
14
+ return {
15
+ id: quote.id,
16
+ simulatedAmountOut: quote.amountOut,
17
+ gasUsed: DEFAULT_GAS_USED,
18
+ provider: quote.provider,
19
+ };
20
+ };
21
+ exports.simulateBluefinX = simulateBluefinX;
22
+ const simulateSwapTx = async (tx, inspector, simulation) => {
23
+ const res = await (0, exports.timeout)(() => inspector.devInspectTransactionBlock({
24
+ sender: simulation.sender,
25
+ transactionBlock: tx,
26
+ }), simulation.timeout ?? 2000);
27
+ if (res.effects.status.status === "failure") {
28
+ throw new Error(res.error ?? "Simulation failed");
29
+ }
30
+ const amountOut = extractAmountOutWrapper(res.events);
31
+ return {
32
+ simulatedAmountOut: amountOut,
33
+ gasUsed: res.effects.gasUsed,
34
+ };
35
+ };
36
+ exports.simulateSwapTx = simulateSwapTx;
37
+ const simulateAggregator = async (provider, quote, simulation, inspector, options) => {
38
+ const tx = new transactions_1.Transaction();
39
+ const coinOut = await provider.swap({
40
+ quote,
41
+ coinIn: (0, transactions_1.coinWithBalance)({
42
+ balance: BigInt(quote.amountIn),
43
+ type: quote.coinTypeIn,
44
+ useGasCoin: false,
45
+ }),
46
+ signer: simulation.sender,
47
+ tx,
48
+ });
49
+ tx.add((0, exports.metaSettle)(quote, coinOut, 10000, options.tipBps, options.partner, options.partnerCommissionBps));
50
+ tx.transferObjects([coinOut], simulation.sender);
51
+ const res = await (0, exports.simulateSwapTx)(tx, inspector, simulation);
52
+ return {
53
+ id: quote.id,
54
+ provider: provider.kind,
55
+ ...res,
56
+ };
57
+ };
58
+ exports.simulateAggregator = simulateAggregator;
59
+ /**
60
+ * this settlement does not charge commission fee for partner, since all integrated aggregators already charge commission fee for partner
61
+ * @param quote Meta Aggregator Quote
62
+ * @param coinOut Coin Out Object
63
+ * @param slippageBps Slippage Bps
64
+ * @param tipBps Tip Bps default = 0
65
+ * @param partner address of partner for analytic default is zero address
66
+ */
67
+ const metaSettle = (quote, coinOut, slippageBps = 100, tipBps = 0, partner, commissionBps = 0) => {
68
+ return (tx) => {
69
+ const { minAmount, expectedAmount } = (0, buildTx_1.getExpectedReturn)(quote.rawAmountOut, slippageBps, commissionBps, tipBps);
70
+ if (tipBps > 0) {
71
+ tx.moveCall({
72
+ target: `${_7k_1._7K_META_PUBLISHED_AT}::vault::collect_tip`,
73
+ typeArguments: [quote.coinTypeOut],
74
+ arguments: [
75
+ tx.object(_7k_1._7K_META_VAULT),
76
+ tx.object(_7k_1._7K_META_CONFIG),
77
+ coinOut,
78
+ tx.pure.u64(tipBps),
79
+ ],
80
+ });
81
+ }
82
+ tx.moveCall({
83
+ target: `${_7k_1._7K_META_PUBLISHED_AT}::settle::settle`,
84
+ typeArguments: [quote.coinTypeIn, quote.coinTypeOut],
85
+ arguments: [
86
+ tx.object(_7k_1._7K_META_CONFIG),
87
+ tx.object(_7k_1._7K_META_VAULT),
88
+ tx.pure.u64(quote.amountIn),
89
+ coinOut,
90
+ tx.pure.u64(minAmount),
91
+ tx.pure.u64(expectedAmount),
92
+ tx.pure.option("address", partner),
93
+ tx.pure.u64(commissionBps),
94
+ tx.pure.u64(0), // ps
95
+ ],
96
+ });
97
+ };
98
+ };
99
+ exports.metaSettle = metaSettle;
100
+ const extractAmountOutWrapper = (events) => {
101
+ const swapEvent = events
102
+ .filter((event) => event.type === `${_7k_1._7K_META_PACKAGE_ID}::settle::Swap`)
103
+ ?.pop();
104
+ return swapEvent?.parsedJson?.amount_out;
105
+ };
106
+ const timeout = async (fn, timeout, msg) => {
107
+ if (timeout <= 0)
108
+ return fn();
109
+ return new Promise((resolve, reject) => {
110
+ const timer = setTimeout(() => reject(new Error(`Timeout ${msg ?? "operation"}`)), timeout);
111
+ fn()
112
+ .then(resolve)
113
+ .catch(reject)
114
+ .finally(() => clearTimeout(timer));
115
+ });
116
+ };
117
+ exports.timeout = timeout;
@@ -37,18 +37,22 @@ exports.MetaAg = void 0;
37
37
  const client_1 = require("@mysten/sui/client");
38
38
  const transactions_1 = require("@mysten/sui/transactions");
39
39
  const utils_1 = require("@mysten/sui/utils");
40
- const _7k_1 = require("../../constants/_7k");
41
40
  const sui_1 = require("../../constants/sui");
42
41
  const metaAg_1 = require("../../types/metaAg");
43
42
  const condition_1 = require("../../utils/condition");
44
43
  const SuiClientUtils_1 = require("../../utils/SuiClientUtils");
45
44
  const buildTx_1 = require("../swap/buildTx");
45
+ const common_1 = require("./common");
46
46
  const bluefin_1 = require("./providers/bluefin");
47
+ const bluefinx_1 = require("./providers/bluefinx");
48
+ const okx_1 = require("./providers/okx");
47
49
  const HERMES_API = "https://hermes.pyth.network";
48
50
  const DEFAULT_PROVIDERS = {
49
51
  [metaAg_1.EProvider.BLUEFIN7K]: {},
50
52
  [metaAg_1.EProvider.FLOWX]: {},
51
53
  [metaAg_1.EProvider.CETUS]: {},
54
+ [metaAg_1.EProvider.ASTRO]: {},
55
+ [metaAg_1.EProvider.BLUEFINX]: {},
52
56
  };
53
57
  class MetaAg {
54
58
  constructor(options) {
@@ -85,6 +89,16 @@ class MetaAg {
85
89
  const { CetusProvider } = await Promise.resolve().then(() => __importStar(require("./providers/cetus"))).catch(catchImportError(metaAg_1.EProvider.CETUS));
86
90
  this.providers[metaAg_1.EProvider.CETUS] = new CetusProvider(providerOptions, this.options, this.client);
87
91
  break;
92
+ case metaAg_1.EProvider.OKX:
93
+ this.providers[metaAg_1.EProvider.OKX] = new okx_1.OkxProvider(providerOptions, this.options, this.client);
94
+ break;
95
+ case metaAg_1.EProvider.BLUEFINX:
96
+ this.providers[metaAg_1.EProvider.BLUEFINX] = new bluefinx_1.BluefinXProvider(providerOptions);
97
+ break;
98
+ case metaAg_1.EProvider.ASTRO:
99
+ const { AstroProvider } = await Promise.resolve().then(() => __importStar(require("./providers/astro"))).catch(catchImportError(metaAg_1.EProvider.ASTRO));
100
+ this.providers[metaAg_1.EProvider.ASTRO] = new AstroProvider(providerOptions);
101
+ break;
88
102
  default:
89
103
  throw new Error(`Provider not supported: ${provider}`);
90
104
  }
@@ -92,51 +106,40 @@ class MetaAg {
92
106
  }
93
107
  async _simulate(provider, quote, simulation) {
94
108
  try {
95
- const tx = new transactions_1.Transaction();
96
- const id = quote.id;
97
- const coinOut = await provider.swap({
98
- quote,
99
- coinIn: (0, transactions_1.coinWithBalance)({
100
- balance: BigInt(quote.amountIn),
101
- type: quote.coinTypeIn,
102
- useGasCoin: false,
103
- }),
104
- signer: simulation.sender,
105
- tx,
106
- });
107
- tx.add(metaSettle(quote, coinOut, 10000, this.options.tipBps, this.options.partner, this.options.partnerCommissionBps));
108
- tx.transferObjects([coinOut], simulation.sender);
109
- const res = await timeout(() => this.inspector.devInspectTransactionBlock({
110
- sender: simulation.sender,
111
- transactionBlock: tx,
112
- }), simulation.timeout ?? 2000, `simulation for ${provider.kind} provider with id ${id}`);
113
- if (res.effects.status.status === "failure") {
114
- throw new Error(res.error ?? "Simulation failed");
109
+ if ((0, metaAg_1.isAggregatorProvider)(provider)) {
110
+ return (0, common_1.simulateAggregator)(provider, quote, simulation, this.inspector, this.options);
111
+ }
112
+ switch (quote.provider) {
113
+ case metaAg_1.EProvider.BLUEFINX:
114
+ return (0, common_1.simulateBluefinX)(quote);
115
+ case metaAg_1.EProvider.OKX:
116
+ return (0, okx_1.simulateOKXSwap)(quote, this.inspector, simulation, this.options);
117
+ default:
118
+ throw new Error(`Provider not supported: ${provider.kind}`);
115
119
  }
116
- const amountOut = extractAmountOutWrapper(res.events);
117
- return {
118
- id,
119
- simulatedAmountOut: amountOut,
120
- gasUsed: res.effects.gasUsed,
121
- provider: provider.kind,
122
- };
123
120
  }
124
121
  catch (error) {
125
- console.warn(`Failed to simulate ${provider.kind}: `, error);
122
+ console.warn(error, { provider: provider.kind, quote: quote.id });
126
123
  }
127
124
  }
128
125
  async _quote(provider, options, simulation) {
129
- const quote = await timeout(async () => {
126
+ const quote = await (0, common_1.timeout)(async () => {
130
127
  const quote = await provider.quote(options);
128
+ if (!quote)
129
+ return null;
131
130
  const { expectedAmount } = (0, buildTx_1.getExpectedReturn)(quote.rawAmountOut, 0, this.options.partnerCommissionBps, this.options.tipBps);
132
131
  quote.amountOut = expectedAmount;
133
132
  return quote;
134
- }, options.timeout ?? 2000, `quote for ${provider.kind} provider from ${options.coinInType} to ${options.coinOutType}`);
135
- if (simulation) {
133
+ }, options.timeout ?? 2000, `quote for ${provider.kind} provider from ${options.coinTypeIn} to ${options.coinTypeOut}`);
134
+ if (quote && simulation) {
136
135
  if (simulation.onSimulated) {
137
136
  this._simulate(provider, quote, simulation).then((payload) => {
138
137
  if (payload) {
139
- simulation.onSimulated?.(payload);
138
+ setTimeout(() => {
139
+ quote.simulatedAmountOut = payload.simulatedAmountOut;
140
+ quote.gasUsed = payload.gasUsed;
141
+ simulation.onSimulated?.({ ...quote });
142
+ });
140
143
  }
141
144
  });
142
145
  }
@@ -148,6 +151,29 @@ class MetaAg {
148
151
  }
149
152
  return quote;
150
153
  }
154
+ async _fastSwap({ quote, signer, useGasCoin, signTransaction }, getTransactionBlockParams) {
155
+ const tx = new transactions_1.Transaction();
156
+ const coin = await this.swap({
157
+ quote,
158
+ signer,
159
+ tx,
160
+ coinIn: (0, transactions_1.coinWithBalance)({
161
+ type: quote.coinTypeIn,
162
+ balance: BigInt(quote.amountIn),
163
+ useGasCoin,
164
+ }),
165
+ });
166
+ tx.transferObjects([coin], signer);
167
+ tx.setSenderIfNotSet(signer);
168
+ const txBytes = await tx.build({ client: this.client });
169
+ const { signature, bytes } = await signTransaction((0, utils_1.toBase64)(txBytes));
170
+ return this.client.executeTransactionBlock({
171
+ transactionBlock: bytes,
172
+ signature,
173
+ options: getTransactionBlockParams?.options,
174
+ signal: getTransactionBlockParams?.signal,
175
+ });
176
+ }
151
177
  /**
152
178
  * Get quotes from all providers
153
179
  * @param options - quote options
@@ -157,8 +183,8 @@ class MetaAg {
157
183
  async quote(options, simulation) {
158
184
  const opts = {
159
185
  ...options,
160
- coinInType: (0, utils_1.normalizeStructTag)(options.coinInType),
161
- coinOutType: (0, utils_1.normalizeStructTag)(options.coinOutType),
186
+ coinTypeIn: (0, utils_1.normalizeStructTag)(options.coinTypeIn),
187
+ coinTypeOut: (0, utils_1.normalizeStructTag)(options.coinTypeOut),
162
188
  };
163
189
  const quotes = await Promise.allSettled(Object.entries(this.options.providers)
164
190
  .filter(([_k, v]) => !v.disabled)
@@ -174,6 +200,8 @@ class MetaAg {
174
200
  }
175
201
  /**
176
202
  * Build transaction from quote
203
+ * @info Use this function to build composable transaction (ie: add more commands after the swap, consume the coin out object)
204
+ * @warning Providers that build transaction on the fly (typically RFQ, Swap-API providers ie: BluefinX, Okx, ...) are not supported, please use `fastSwap` instead
177
205
  * @param options - build tx options
178
206
  * @param slippageBps - slippage bps if not specified, fallback to global slippage bps, if none of them specified, default to 100
179
207
  * @returns coin out object, you must consume it by transferObjects, or other sub sequence commands
@@ -181,11 +209,32 @@ class MetaAg {
181
209
  async swap(options, slippageBps) {
182
210
  const provider = await this._getProvider(options.quote.provider);
183
211
  (0, condition_1.assert)(!!provider, `Provider not found: ${options.quote.provider}`);
212
+ (0, condition_1.assert)((0, metaAg_1.isAggregatorProvider)(provider), `Provider does not support swap: ${provider.kind}`);
184
213
  const coinOut = await provider.swap(options);
185
- options.tx.add(metaSettle(options.quote, coinOut, slippageBps ?? this.options.slippageBps ?? 100, this.options.tipBps, this.options.partner, this.options.partnerCommissionBps));
214
+ options.tx.add((0, common_1.metaSettle)(options.quote, coinOut, slippageBps ?? this.options.slippageBps ?? 100, this.options.tipBps, this.options.partner, this.options.partnerCommissionBps));
186
215
  options.tx.setSenderIfNotSet(options.signer);
187
216
  return coinOut;
188
217
  }
218
+ /**
219
+ * Build, Sign, and Execute transaction in one step
220
+ * @param options - fast swap options
221
+ * @returns - txDigest of the transaction
222
+ */
223
+ async fastSwap(options, getTransactionBlockParams) {
224
+ const provider = await this._getProvider(options.quote.provider);
225
+ if ((0, metaAg_1.isAggregatorProvider)(provider)) {
226
+ return this._fastSwap(options, getTransactionBlockParams);
227
+ }
228
+ else if ((0, metaAg_1.isSwapAPIProvider)(provider)) {
229
+ return this.client.waitForTransaction({
230
+ ...getTransactionBlockParams,
231
+ digest: await provider.fastSwap(options),
232
+ });
233
+ }
234
+ else {
235
+ throw new Error(`Provider not supported: ${provider.kind}`);
236
+ }
237
+ }
189
238
  /**
190
239
  * Update meta aggregator options
191
240
  * @param options - update options payload
@@ -219,71 +268,17 @@ class MetaAg {
219
268
  }
220
269
  }
221
270
  exports.MetaAg = MetaAg;
222
- /**
223
- * this settlement does not charge commission fee for partner, since all integrated aggregators already charge commission fee for partner
224
- * @param quote Meta Aggregator Quote
225
- * @param coinOut Coin Out Object
226
- * @param slippageBps Slippage Bps
227
- * @param tipBps Tip Bps default = 0
228
- * @param partner address of partner for analytic default is zero address
229
- */
230
- const metaSettle = (quote, coinOut, slippageBps = 100, tipBps = 0, partner, commissionBps = 0) => {
231
- return (tx) => {
232
- const { minAmount, expectedAmount } = (0, buildTx_1.getExpectedReturn)(quote.rawAmountOut, slippageBps, commissionBps, tipBps);
233
- if (tipBps > 0) {
234
- tx.moveCall({
235
- target: `${_7k_1._7K_META_PUBLISHED_AT}::vault::collect_tip`,
236
- typeArguments: [quote.coinTypeOut],
237
- arguments: [
238
- tx.object(_7k_1._7K_META_VAULT),
239
- tx.object(_7k_1._7K_META_CONFIG),
240
- coinOut,
241
- tx.pure.u64(tipBps),
242
- ],
243
- });
244
- }
245
- tx.moveCall({
246
- target: `${_7k_1._7K_META_PUBLISHED_AT}::settle::settle`,
247
- typeArguments: [quote.coinTypeIn, quote.coinTypeOut],
248
- arguments: [
249
- tx.object(_7k_1._7K_META_CONFIG),
250
- tx.object(_7k_1._7K_META_VAULT),
251
- tx.pure.u64(quote.amountIn),
252
- coinOut,
253
- tx.pure.u64(minAmount),
254
- tx.pure.u64(expectedAmount),
255
- tx.pure.option("address", partner),
256
- tx.pure.u64(commissionBps),
257
- tx.pure.u64(0), // ps
258
- ],
259
- });
260
- };
261
- };
262
- const extractAmountOutWrapper = (events) => {
263
- const swapEvent = events
264
- .filter((event) => event.type === `${_7k_1._7K_META_PACKAGE_ID}::settle::Swap`)
265
- ?.pop();
266
- return swapEvent?.parsedJson?.amount_out;
267
- };
268
271
  const catchImportError = (provider) => {
269
272
  return (e) => {
270
273
  const map = {
271
274
  [metaAg_1.EProvider.CETUS]: "@cetusprotocol/aggregator-sdk",
272
275
  [metaAg_1.EProvider.FLOWX]: "@flowx-finance/sdk",
273
276
  [metaAg_1.EProvider.BLUEFIN7K]: "@7kprotocol/sdk-ts",
277
+ [metaAg_1.EProvider.ASTRO]: "@naviprotocol/astros-aggregator-sdk",
278
+ [metaAg_1.EProvider.OKX]: "",
279
+ [metaAg_1.EProvider.BLUEFINX]: "",
274
280
  };
275
281
  console.warn(`Please install ${map[provider]} to use ${provider} provider`);
276
282
  throw e;
277
283
  };
278
284
  };
279
- const timeout = async (fn, timeout, msg) => {
280
- if (timeout <= 0)
281
- return fn();
282
- return new Promise((resolve, reject) => {
283
- const timer = setTimeout(() => reject(new Error(`Timeout ${msg ?? "operation"}`)), timeout);
284
- fn()
285
- .then(resolve)
286
- .catch(reject)
287
- .finally(() => clearTimeout(timer));
288
- });
289
- };