@7kprotocol/sdk-ts 5.0.0-beta.0 → 5.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -8
- package/dist/flowx-FTPJ3RYF.mjs +2 -0
- package/dist/flowx-FTPJ3RYF.mjs.map +1 -0
- package/dist/{flowx-SIZHC2DP.js → flowx-RRIX3SC4.js} +2 -2
- package/dist/flowx-RRIX3SC4.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/flowx-533PLKYB.mjs +0 -2
- package/dist/flowx-533PLKYB.mjs.map +0 -1
- package/dist/flowx-SIZHC2DP.js.map +0 -1
package/README.md
CHANGED
|
@@ -61,8 +61,8 @@ npm i @mysten/sui@^2.17.0 @pythnetwork/pyth-sui-js@^2.2.0
|
|
|
61
61
|
|
|
62
62
|
> **v5 note**: `@mysten/sui` v2 ships gRPC, GraphQL, and JSON-RPC transports
|
|
63
63
|
> behind a unified `ClientWithCoreApi`. The SDK constructs a `SuiGrpcClient`
|
|
64
|
-
> against Sui mainnet by default; pass `MetaAgOptions.client` to override
|
|
65
|
-
>
|
|
64
|
+
> against Sui mainnet by default; pass `MetaAgOptions.client` to override with
|
|
65
|
+
> any transport (see the [MetaAg docs](docs/META_AG.md)).
|
|
66
66
|
|
|
67
67
|
### Optional Dependencies (for MetaAg providers)
|
|
68
68
|
|
|
@@ -88,12 +88,11 @@ npm i @cetusprotocol/aggregator-sdk@^1.5.4
|
|
|
88
88
|
npm i @bluefin-exchange/bluefin7k-aggregator-sdk@^7.2.0
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
-
> **Cetus transport caveat (v5)**: Cetus 1.5.4 still types its internal
|
|
92
|
-
>
|
|
93
|
-
>
|
|
94
|
-
>
|
|
95
|
-
>
|
|
96
|
-
> `SuiJsonRpcClient` via `MetaAgOptions.client`.
|
|
91
|
+
> **Cetus transport caveat (v5)**: Cetus 1.5.4 still types its internal client
|
|
92
|
+
> as `SuiJsonRpcClient` and calls legacy JSON-RPC methods on Pyth-priced and
|
|
93
|
+
> DeepBookV3-driven routes. Most routes work with the default `SuiGrpcClient`,
|
|
94
|
+
> but routes that touch Pyth oracles (e.g. `HAEDALPMM`) will fail. If you need
|
|
95
|
+
> full Cetus coverage, pass a `SuiJsonRpcClient` via `MetaAgOptions.client`.
|
|
97
96
|
|
|
98
97
|
### Graceful Degradation
|
|
99
98
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as o,h as i,j as n,k as u}from"./chunk-CYI4MM5C.mjs";import{AggregatorQuoter as a,Commission as m,CommissionType as c,TradeBuilder as p}from"@flowx-finance/sdk";import{v4 as d}from"uuid";var s=class{constructor(t,e){this.options=t;this.client=e;o(this,"kind","flowx");o(this,"quoter");this.quoter=new a("mainnet",t.apiKey)}async quote(t){let e=await this.quoter.getRoutes({amountIn:t.amountIn,tokenIn:t.coinTypeIn,tokenOut:t.coinTypeOut,includeSources:this.options.sources,excludePools:this.options.excludePools,excludeSources:this.options.excludeSources,maxHops:this.options.maxHops,splitDistributionPercent:this.options.splitDistributionPercent});return{id:d(),provider:"flowx",quote:e,amountIn:e.amountIn?.toString()??"0",rawAmountOut:e.amountOut?.toString()??"0",amountOut:e.amountOut?.toString()??"0",coinTypeIn:t.coinTypeIn,coinTypeOut:t.coinTypeOut}}async swap(t){u(t.quote,"flowx");let e=new p("mainnet",t.quote.quote.routes);e.sender(t.signer),e.slippage(1e4*100),e.commission(new m(i,t.quote.quote.coinOut,c.PERCENTAGE,0,!0));let r=await e.build().swap({tx:t.tx,client:this.client,coinIn:t.coinIn});return n.assert(!!r,"FlowX swap returned no coin out",1004,{quote:t.quote,expectedProvider:"flowx"}),r}};export{s as FlowxProvider};
|
|
2
|
+
//# sourceMappingURL=flowx-FTPJ3RYF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/features/metaAg/providers/flowx.ts"],"sourcesContent":["import {\n AggregatorQuoter,\n Commission,\n CommissionType,\n TradeBuilder,\n} from \"@flowx-finance/sdk\";\nimport { ClientWithCoreApi } from \"@mysten/sui/client\";\nimport { SuiGrpcClient } from \"@mysten/sui/grpc\";\nimport { TransactionObjectArgument } from \"@mysten/sui/transactions\";\nimport { v4 } from \"uuid\";\nimport { _7K_PARTNER_ADDRESS } from \"../../../constants/_7k\";\nimport {\n AggregatorProvider,\n EProvider,\n FlowxProviderOptions,\n MetaQuote,\n MetaQuoteOptions,\n MetaSwapOptions,\n QuoteProvider,\n} from \"../../../types/metaAg\";\nimport { assertQuoteProvider } from \"../common\";\nimport { MetaAgError, MetaAgErrorCode } from \"../error\";\n\nexport class FlowxProvider implements QuoteProvider, AggregatorProvider {\n readonly kind = EProvider.FLOWX;\n private quoter: AggregatorQuoter;\n constructor(\n private readonly options: FlowxProviderOptions,\n private readonly client: ClientWithCoreApi,\n ) {\n this.quoter = new AggregatorQuoter(\"mainnet\", options.apiKey);\n }\n\n async quote(quoteOptions: MetaQuoteOptions): Promise<MetaQuote> {\n const quote = await this.quoter.getRoutes({\n amountIn: quoteOptions.amountIn,\n tokenIn: quoteOptions.coinTypeIn,\n tokenOut: quoteOptions.coinTypeOut,\n includeSources: this.options.sources,\n excludePools: this.options.excludePools,\n excludeSources: this.options.excludeSources,\n maxHops: this.options.maxHops,\n splitDistributionPercent: this.options.splitDistributionPercent,\n });\n return {\n id: v4(),\n provider: EProvider.FLOWX,\n quote: quote,\n amountIn: quote.amountIn?.toString() ?? \"0\",\n rawAmountOut: quote.amountOut?.toString() ?? \"0\",\n amountOut: quote.amountOut?.toString() ?? \"0\",\n coinTypeIn: quoteOptions.coinTypeIn,\n coinTypeOut: quoteOptions.coinTypeOut,\n };\n }\n\n async swap(options: MetaSwapOptions): Promise<TransactionObjectArgument> {\n assertQuoteProvider(options.quote, EProvider.FLOWX);\n const builder = new TradeBuilder(\"mainnet\", options.quote.quote.routes);\n builder.sender(options.signer);\n builder.slippage(10000 * 100);\n builder.commission(\n new Commission(\n _7K_PARTNER_ADDRESS,\n options.quote.quote.coinOut,\n CommissionType.PERCENTAGE,\n 0,\n true,\n ),\n );\n const res = await builder.build().swap({\n tx: options.tx,\n client: this.client as unknown as SuiGrpcClient,\n coinIn: options.coinIn,\n });\n MetaAgError.assert(\n !!res,\n \"FlowX swap returned no coin out\",\n MetaAgErrorCode.INVALID_QUOTE,\n { quote: options.quote, expectedProvider: EProvider.FLOWX },\n );\n return res;\n }\n}\n"],"mappings":"8DAAA,OACE,oBAAAA,EACA,cAAAC,EACA,kBAAAC,EACA,gBAAAC,MACK,qBAIP,OAAS,MAAAC,MAAU,OAcZ,IAAMC,EAAN,KAAiE,CAGtE,YACmBC,EACAC,EACjB,CAFiB,aAAAD,EACA,YAAAC,EAJnBC,EAAA,KAAS,gBACTA,EAAA,KAAQ,UAKN,KAAK,OAAS,IAAIC,EAAiB,UAAWH,EAAQ,MAAM,CAC9D,CAEA,MAAM,MAAMI,EAAoD,CAC9D,IAAMC,EAAQ,MAAM,KAAK,OAAO,UAAU,CACxC,SAAUD,EAAa,SACvB,QAASA,EAAa,WACtB,SAAUA,EAAa,YACvB,eAAgB,KAAK,QAAQ,QAC7B,aAAc,KAAK,QAAQ,aAC3B,eAAgB,KAAK,QAAQ,eAC7B,QAAS,KAAK,QAAQ,QACtB,yBAA0B,KAAK,QAAQ,wBACzC,CAAC,EACD,MAAO,CACL,GAAIE,EAAG,EACP,iBACA,MAAOD,EACP,SAAUA,EAAM,UAAU,SAAS,GAAK,IACxC,aAAcA,EAAM,WAAW,SAAS,GAAK,IAC7C,UAAWA,EAAM,WAAW,SAAS,GAAK,IAC1C,WAAYD,EAAa,WACzB,YAAaA,EAAa,WAC5B,CACF,CAEA,MAAM,KAAKJ,EAA8D,CACvEO,EAAoBP,EAAQ,aAAsB,EAClD,IAAMQ,EAAU,IAAIC,EAAa,UAAWT,EAAQ,MAAM,MAAM,MAAM,EACtEQ,EAAQ,OAAOR,EAAQ,MAAM,EAC7BQ,EAAQ,SAAS,IAAQ,GAAG,EAC5BA,EAAQ,WACN,IAAIE,EACFC,EACAX,EAAQ,MAAM,MAAM,QACpBY,EAAe,WACf,EACA,EACF,CACF,EACA,IAAMC,EAAM,MAAML,EAAQ,MAAM,EAAE,KAAK,CACrC,GAAIR,EAAQ,GACZ,OAAQ,KAAK,OACb,OAAQA,EAAQ,MAClB,CAAC,EACD,OAAAc,EAAY,OACV,CAAC,CAACD,EACF,uCAEA,CAAE,MAAOb,EAAQ,MAAO,wBAAkC,CAC5D,EACOa,CACT,CACF","names":["AggregatorQuoter","Commission","CommissionType","TradeBuilder","v4","FlowxProvider","options","client","__publicField","AggregatorQuoter","quoteOptions","quote","v4","assertQuoteProvider","builder","TradeBuilder","Commission","_7K_PARTNER_ADDRESS","CommissionType","res","MetaAgError"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkE5KM5OVWjs = require('./chunk-E5KM5OVW.js');var _sdk = require('@flowx-finance/sdk');var _uuid = require('uuid');var
|
|
2
|
-
//# sourceMappingURL=flowx-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkE5KM5OVWjs = require('./chunk-E5KM5OVW.js');var _sdk = require('@flowx-finance/sdk');var _uuid = require('uuid');var s=class{constructor(t,e){this.options=t;this.client=e;_chunkE5KM5OVWjs.a.call(void 0, this,"kind","flowx");_chunkE5KM5OVWjs.a.call(void 0, this,"quoter");this.quoter=new (0, _sdk.AggregatorQuoter)("mainnet",t.apiKey)}async quote(t){let e=await this.quoter.getRoutes({amountIn:t.amountIn,tokenIn:t.coinTypeIn,tokenOut:t.coinTypeOut,includeSources:this.options.sources,excludePools:this.options.excludePools,excludeSources:this.options.excludeSources,maxHops:this.options.maxHops,splitDistributionPercent:this.options.splitDistributionPercent});return{id:_uuid.v4.call(void 0, ),provider:"flowx",quote:e,amountIn:_nullishCoalesce(_optionalChain([e, 'access', _ => _.amountIn, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()]), () => ("0")),rawAmountOut:_nullishCoalesce(_optionalChain([e, 'access', _4 => _4.amountOut, 'optionalAccess', _5 => _5.toString, 'call', _6 => _6()]), () => ("0")),amountOut:_nullishCoalesce(_optionalChain([e, 'access', _7 => _7.amountOut, 'optionalAccess', _8 => _8.toString, 'call', _9 => _9()]), () => ("0")),coinTypeIn:t.coinTypeIn,coinTypeOut:t.coinTypeOut}}async swap(t){_chunkE5KM5OVWjs.k.call(void 0, t.quote,"flowx");let e=new (0, _sdk.TradeBuilder)("mainnet",t.quote.quote.routes);e.sender(t.signer),e.slippage(1e4*100),e.commission(new (0, _sdk.Commission)(_chunkE5KM5OVWjs.h,t.quote.quote.coinOut,_sdk.CommissionType.PERCENTAGE,0,!0));let r=await e.build().swap({tx:t.tx,client:this.client,coinIn:t.coinIn});return _chunkE5KM5OVWjs.j.assert(!!r,"FlowX swap returned no coin out",1004,{quote:t.quote,expectedProvider:"flowx"}),r}};exports.FlowxProvider = s;
|
|
2
|
+
//# sourceMappingURL=flowx-RRIX3SC4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/otis/Documents/7k-ts-sdk/dist/flowx-RRIX3SC4.js","../src/features/metaAg/providers/flowx.ts"],"names":["FlowxProvider","options","client","__publicField","AggregatorQuoter","quoteOptions","quote","v4","assertQuoteProvider","builder","TradeBuilder","Commission","_7K_PARTNER_ADDRESS","CommissionType","res","MetaAgError"],"mappings":"AAAA,uuBAA4D,yCCKrD,4BAIY,IAcNA,CAAAA,CAAN,KAAiE,CAGtE,WAAA,CACmBC,CAAAA,CACAC,CAAAA,CACjB,CAFiB,IAAA,CAAA,OAAA,CAAAD,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAC,CAAAA,CAJnBC,gCAAAA,IAAA,CAAS,MAAA,CAAA,OAAA,CAAA,CACTA,gCAAAA,IAAA,CAAQ,QAAA,CAAA,CAKN,IAAA,CAAK,MAAA,CAAS,IAAIC,0BAAAA,CAAiB,SAAA,CAAWH,CAAAA,CAAQ,MAAM,CAC9D,CAEA,MAAM,KAAA,CAAMI,CAAAA,CAAoD,CAC9D,IAAMC,CAAAA,CAAQ,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,CAAU,CACxC,QAAA,CAAUD,CAAAA,CAAa,QAAA,CACvB,OAAA,CAASA,CAAAA,CAAa,UAAA,CACtB,QAAA,CAAUA,CAAAA,CAAa,WAAA,CACvB,cAAA,CAAgB,IAAA,CAAK,OAAA,CAAQ,OAAA,CAC7B,YAAA,CAAc,IAAA,CAAK,OAAA,CAAQ,YAAA,CAC3B,cAAA,CAAgB,IAAA,CAAK,OAAA,CAAQ,cAAA,CAC7B,OAAA,CAAS,IAAA,CAAK,OAAA,CAAQ,OAAA,CACtB,wBAAA,CAA0B,IAAA,CAAK,OAAA,CAAQ,wBACzC,CAAC,CAAA,CACD,MAAO,CACL,EAAA,CAAIE,sBAAAA,CAAG,CACP,QAAA,CAAA,OAAA,CACA,KAAA,CAAOD,CAAAA,CACP,QAAA,kCAAUA,CAAAA,mBAAM,QAAA,6BAAU,QAAA,mBAAS,GAAA,SAAK,KAAA,CACxC,YAAA,kCAAcA,CAAAA,qBAAM,SAAA,6BAAW,QAAA,mBAAS,GAAA,SAAK,KAAA,CAC7C,SAAA,kCAAWA,CAAAA,qBAAM,SAAA,6BAAW,QAAA,mBAAS,GAAA,SAAK,KAAA,CAC1C,UAAA,CAAYD,CAAAA,CAAa,UAAA,CACzB,WAAA,CAAaA,CAAAA,CAAa,WAC5B,CACF,CAEA,MAAM,IAAA,CAAKJ,CAAAA,CAA8D,CACvEO,gCAAAA,CAAoBP,CAAQ,KAAA,CAAA,OAAsB,CAAA,CAClD,IAAMQ,CAAAA,CAAU,IAAIC,sBAAAA,CAAa,SAAA,CAAWT,CAAAA,CAAQ,KAAA,CAAM,KAAA,CAAM,MAAM,CAAA,CACtEQ,CAAAA,CAAQ,MAAA,CAAOR,CAAAA,CAAQ,MAAM,CAAA,CAC7BQ,CAAAA,CAAQ,QAAA,CAAS,GAAA,CAAQ,GAAG,CAAA,CAC5BA,CAAAA,CAAQ,UAAA,CACN,IAAIE,oBAAAA,CACFC,kBAAAA,CACAX,CAAAA,CAAQ,KAAA,CAAM,KAAA,CAAM,OAAA,CACpBY,mBAAAA,CAAe,UAAA,CACf,CAAA,CACA,CAAA,CACF,CACF,CAAA,CACA,IAAMC,CAAAA,CAAM,MAAML,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAE,IAAA,CAAK,CACrC,EAAA,CAAIR,CAAAA,CAAQ,EAAA,CACZ,MAAA,CAAQ,IAAA,CAAK,MAAA,CACb,MAAA,CAAQA,CAAAA,CAAQ,MAClB,CAAC,CAAA,CACD,OAAAc,kBAAAA,CAAY,MAAA,CACV,CAAC,CAACD,CAAAA,CACF,iCAAA,CAAA,IAAA,CAEA,CAAE,KAAA,CAAOb,CAAAA,CAAQ,KAAA,CAAO,gBAAA,CAAA,OAAkC,CAC5D,CAAA,CACOa,CACT,CACF,CAAA,CAAA,0BAAA","file":"/Users/otis/Documents/7k-ts-sdk/dist/flowx-RRIX3SC4.js","sourcesContent":[null,"import {\n AggregatorQuoter,\n Commission,\n CommissionType,\n TradeBuilder,\n} from \"@flowx-finance/sdk\";\nimport { ClientWithCoreApi } from \"@mysten/sui/client\";\nimport { SuiGrpcClient } from \"@mysten/sui/grpc\";\nimport { TransactionObjectArgument } from \"@mysten/sui/transactions\";\nimport { v4 } from \"uuid\";\nimport { _7K_PARTNER_ADDRESS } from \"../../../constants/_7k\";\nimport {\n AggregatorProvider,\n EProvider,\n FlowxProviderOptions,\n MetaQuote,\n MetaQuoteOptions,\n MetaSwapOptions,\n QuoteProvider,\n} from \"../../../types/metaAg\";\nimport { assertQuoteProvider } from \"../common\";\nimport { MetaAgError, MetaAgErrorCode } from \"../error\";\n\nexport class FlowxProvider implements QuoteProvider, AggregatorProvider {\n readonly kind = EProvider.FLOWX;\n private quoter: AggregatorQuoter;\n constructor(\n private readonly options: FlowxProviderOptions,\n private readonly client: ClientWithCoreApi,\n ) {\n this.quoter = new AggregatorQuoter(\"mainnet\", options.apiKey);\n }\n\n async quote(quoteOptions: MetaQuoteOptions): Promise<MetaQuote> {\n const quote = await this.quoter.getRoutes({\n amountIn: quoteOptions.amountIn,\n tokenIn: quoteOptions.coinTypeIn,\n tokenOut: quoteOptions.coinTypeOut,\n includeSources: this.options.sources,\n excludePools: this.options.excludePools,\n excludeSources: this.options.excludeSources,\n maxHops: this.options.maxHops,\n splitDistributionPercent: this.options.splitDistributionPercent,\n });\n return {\n id: v4(),\n provider: EProvider.FLOWX,\n quote: quote,\n amountIn: quote.amountIn?.toString() ?? \"0\",\n rawAmountOut: quote.amountOut?.toString() ?? \"0\",\n amountOut: quote.amountOut?.toString() ?? \"0\",\n coinTypeIn: quoteOptions.coinTypeIn,\n coinTypeOut: quoteOptions.coinTypeOut,\n };\n }\n\n async swap(options: MetaSwapOptions): Promise<TransactionObjectArgument> {\n assertQuoteProvider(options.quote, EProvider.FLOWX);\n const builder = new TradeBuilder(\"mainnet\", options.quote.quote.routes);\n builder.sender(options.signer);\n builder.slippage(10000 * 100);\n builder.commission(\n new Commission(\n _7K_PARTNER_ADDRESS,\n options.quote.quote.coinOut,\n CommissionType.PERCENTAGE,\n 0,\n true,\n ),\n );\n const res = await builder.build().swap({\n tx: options.tx,\n client: this.client as unknown as SuiGrpcClient,\n coinIn: options.coinIn,\n });\n MetaAgError.assert(\n !!res,\n \"FlowX swap returned no coin out\",\n MetaAgErrorCode.INVALID_QUOTE,\n { quote: options.quote, expectedProvider: EProvider.FLOWX },\n );\n return res;\n }\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +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 _chunkE5KM5OVWjs = require('./chunk-E5KM5OVW.js');var _grpc = require('@mysten/sui/grpc');var _jsonRpc = require('@mysten/sui/jsonRpc');var _transactions = require('@mysten/sui/transactions');var _utils = require('@mysten/sui/utils');var ee="0x0000000000000000000000000000000000000000000000000000000000000000";var be=["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000003","0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000005","0x0000000000000000000000000000000000000000000000000000000000000006","0x0000000000000000000000000000000000000000000000000000000000000007","0x0000000000000000000000000000000000000000000000000000000000000008","0x0000000000000000000000000000000000000000000000000000000000000009","0x0000000000000000000000000000000000000000000000000000000000000403","0x000000000000000000000000000000000000000000000000000000000000000c"],S=o=>{let e=_utils.normalizeSuiAddress.call(void 0, o);return be.includes(e)};var Q=class{async getObject(e){let[t,r]=await Promise.all([this.get("OwnedObject",e),this.get("SharedOrImmutableObject",e)]);return _nullishCoalesce(_nullishCoalesce(t, () => (r)), () => (null))}async getObjects(e){return Promise.all(e.map(t=>this.getObject(t)))}async addObject(e){return e.owner?await this.set("OwnedObject",e.objectId,e):await this.set("SharedOrImmutableObject",e.objectId,e),e}async addObjects(e){await Promise.all(e.map(async t=>this.addObject(t)))}async deleteObject(e){await Promise.all([this.delete("OwnedObject",e),this.delete("SharedOrImmutableObject",e)])}async deleteObjects(e){await Promise.all(e.map(t=>this.deleteObject(t)))}async getMoveFunctionDefinition(e){let t=`${_utils.normalizeSuiAddress.call(void 0, e.package)}::${e.module}::${e.function}`;return this.get("MoveFunction",t)}async addMoveFunctionDefinition(e){let t=_utils.normalizeSuiAddress.call(void 0, e.package),r=`${t}::${e.module}::${e.function}`,i={...e,package:t};return await this.set("MoveFunction",r,i),i}async deleteMoveFunctionDefinition(e){let t=`${_utils.normalizeSuiAddress.call(void 0, e.package)}::${e.module}::${e.function}`;await this.delete("MoveFunction",t)}async getCustom(e){return this.get("Custom",e)}async setCustom(e,t){return this.set("Custom",e,t)}async deleteCustom(e){return this.delete("Custom",e)}},C,q=class extends Q{constructor(){super(...arguments);_chunkE5KM5OVWjs.c.call(void 0, this,C,{OwnedObject:new Map,SharedOrImmutableObject:new Map,MoveFunction:new Map,Custom:new Map})}async get(t,r){return _nullishCoalesce(_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].get(r), () => (null))}async set(t,r,i){_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].set(r,i)}async delete(t,r){_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].delete(r)}async clear(t){if(t)_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].clear();else for(let r of Object.values(_chunkE5KM5OVWjs.b.call(void 0, this,C)))r.clear()}};C=new WeakMap;var E,l,A,M=class{constructor({cache:e=new q,onEffects:t,client:r}){_chunkE5KM5OVWjs.c.call(void 0, this,E);_chunkE5KM5OVWjs.c.call(void 0, this,l);_chunkE5KM5OVWjs.c.call(void 0, this,A);_chunkE5KM5OVWjs.d.call(void 0, this,E,r),_chunkE5KM5OVWjs.d.call(void 0, this,l,e),_chunkE5KM5OVWjs.d.call(void 0, this,A,t)}async applyCache(e,t){let r=(await _chunkE5KM5OVWjs.b.call(void 0, this,l).getObjects(t)).filter(n=>n!==null),i=new Map(r.map(n=>[n.objectId,n])),s=[];for(let n of e.inputs){if(!n.UnresolvedObject)continue;let a=i.get(n.UnresolvedObject.objectId);if(!a){s.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 s}async resolveObjects(e,t){let r=await this.applyCache(e,t);if(r.length===0)return[];let i=[...new Set(r)],s=await _chunkE5KM5OVWjs.b.call(void 0, this,E).core.getObjects({objectIds:i}),n=[];for(let a of s.objects){if(a instanceof Error)continue;let c=a.owner,p=c.$kind==="Shared"?c.Shared.initialSharedVersion:null,d=c.$kind==="AddressOwner"?c.AddressOwner:c.$kind==="ObjectOwner"?c.ObjectOwner:null,I={objectId:a.objectId,version:a.version,digest:a.digest,initialSharedVersion:p,owner:d};n.push(I)}return await _chunkE5KM5OVWjs.b.call(void 0, this,l).addObjects(n),await this.applyCache(e,r)}asPlugin(){return async(e,t,r)=>{let i=e.inputs.filter(s=>s.UnresolvedObject).map(s=>s.UnresolvedObject.objectId);await this.resolveObjects(e,i),await Promise.all(e.commands.map(async s=>{if(s.MoveCall){let n=await this.getMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function});n&&(s.MoveCall._argumentTypes=n.parameters)}})),await r(),await Promise.all(e.commands.map(async s=>{_optionalChain([s, 'access', _2 => _2.MoveCall, 'optionalAccess', _3 => _3._argumentTypes])&&await _chunkE5KM5OVWjs.b.call(void 0, this,l).addMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function,parameters:s.MoveCall._argumentTypes})}))}}async clear(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear()}async getMoveFunctionDefinition(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getMoveFunctionDefinition(e)}async getObjects(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getObjects(e)}async deleteObjects(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).deleteObjects(e)}async clearOwnedObjects(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear("OwnedObject")}async clearCustom(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear("Custom")}async getCustom(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getCustom(e)}async setCustom(e,t){return _chunkE5KM5OVWjs.b.call(void 0, this,l).setCustom(e,t)}async deleteCustom(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).deleteCustom(e)}async applyEffects(e){var n;if(!e.V2)throw new Error(`Unsupported transaction effects version ${e.$kind}`);let{lamportVersion:t,changedObjects:r}=e.V2,i=[],s=[];r.forEach(([a,c])=>{if(c.outputState.NotExist)i.push(a);else if(c.outputState.ObjectWrite){let[p,d]=c.outputState.ObjectWrite;s.push({objectId:a,digest:p,version:t,owner:_nullishCoalesce(_nullishCoalesce(d.AddressOwner, () => (d.ObjectOwner)), () => (null)),initialSharedVersion:_nullishCoalesce(_optionalChain([d, 'access', _4 => _4.Shared, 'optionalAccess', _5 => _5.initialSharedVersion]), () => (null))})}}),await Promise.all([_chunkE5KM5OVWjs.b.call(void 0, this,l).addObjects(s),_chunkE5KM5OVWjs.b.call(void 0, this,l).deleteObjects(i),(n=_chunkE5KM5OVWjs.b.call(void 0, this,A))==null?void 0:n.call(this,e)])}};E=new WeakMap,l=new WeakMap,A=new WeakMap;var T,_,x=class{constructor(e){this.client=e;_chunkE5KM5OVWjs.c.call(void 0, this,T);_chunkE5KM5OVWjs.c.call(void 0, this,_,new WeakSet);_chunkE5KM5OVWjs.a.call(void 0, this,"simulateTransaction",async e=>{e.transactionBlock.setSenderIfNotSet(e.sender),_chunkE5KM5OVWjs.b.call(void 0, this,_).has(e.transactionBlock)||(e.transactionBlock.addBuildPlugin(_chunkE5KM5OVWjs.b.call(void 0, this,T).asPlugin()),_chunkE5KM5OVWjs.b.call(void 0, this,_).add(e.transactionBlock));try{return await this.client.core.simulateTransaction({transaction:e.transactionBlock,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}})}catch(t){throw await _chunkE5KM5OVWjs.b.call(void 0, this,T).clear(),t}finally{await _chunkE5KM5OVWjs.b.call(void 0, this,T).clearOwnedObjects()}});_chunkE5KM5OVWjs.d.call(void 0, this,T,new M({client:this.client}))}};T=new WeakMap,_=new WeakMap;var _uuid = require('uuid');var b="0x2::sui::SUI",k="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie="https://web3.okx.com",re="/api/v6/dex/aggregator/swap",De="784",ne=_utils.normalizeStructTag.call(void 0, b),j=class{constructor(e,t,r){this.options=e;this.metaOptions=t;this.client=r;_chunkE5KM5OVWjs.a.call(void 0, this,"kind","okx")}async quote({amountIn:e,coinTypeIn:t,coinTypeOut:r,signer:i}){if(!i||S(i))return null;let s={chainIndex:De,amount:e,fromTokenAddress:t===ne?b:t,toTokenAddress:r===ne?b:r,slippagePercent:(this.metaOptions.slippageBps/100).toString(),userWalletAddress:i},n="?"+new URLSearchParams(s).toString(),a=`${_nullishCoalesce(this.options.api, () => (Ie))}${re}${n}`,p=await(await fetch(a,{headers:await ke(this.options,"GET",re,n)})).json();return _chunkE5KM5OVWjs.j.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:t,coinTypeOut:r,amountIn:e,amountOut:p.data[0].routerResult.toTokenAmount,rawAmountOut:p.data[0].routerResult.toTokenAmount,quote:p.data[0]}}async fastSwap(e){let{quote:t,signer:r,signTransaction:i}=e;_chunkE5KM5OVWjs.k.call(void 0, t,"okx");let{tx:s,coin:n}=ie({quote:t,signer:r});s.add(_chunkE5KM5OVWjs.n.call(void 0, t,n,this.metaOptions.slippageBps,this.metaOptions.tipBps,this.metaOptions.partner,this.metaOptions.partnerCommissionBps)),s.transferObjects([n],r);let a=await s.build({client:this.client}),{bytes:c,signature:p}=await i(_utils.toBase64.call(void 0, a)),d=await this.client.core.executeTransaction({transaction:_utils.fromBase64.call(void 0, c),signatures:[p]});if(!_optionalChain([d, 'access', _6 => _6.Transaction, 'optionalAccess', _7 => _7.digest]))throw new (0, _chunkE5KM5OVWjs.j)("OKX transaction failed or returned no digest",1008,{error:_nullishCoalesce(_optionalChain([d, 'access', _8 => _8.FailedTransaction, 'optionalAccess', _9 => _9.digest]), () => ("no digest"))});return d.Transaction.digest}};async function Me(o,e){let t=new TextEncoder,r=s=>{if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let n="";for(let a=0;a<s.byteLength;a++)n+=String.fromCharCode(s[a]);if(typeof btoa<"u")return btoa(n);throw new (0, _chunkE5KM5OVWjs.j)("Base64 encoder not available in this environment")};if(typeof globalThis<"u"&&_optionalChain([globalThis, 'access', _10 => _10.crypto, 'optionalAccess', _11 => _11.subtle])){let s=await globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await globalThis.crypto.subtle.sign("HMAC",s,t.encode(o));return r(new Uint8Array(n))}let{createHmac:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("crypto")));return i("sha256",e).update(o).digest("base64")}async function ke(o,e,t,r=""){let{apiKey:i,secretKey:s,apiPassphrase:n,projectId:a}=o;if(!i||!s||!n||!a)throw new (0, _chunkE5KM5OVWjs.j)("Missing required environment variables");let c=new Date().toISOString(),p=c+e+t+r;return{"Content-Type":"application/json","OK-ACCESS-KEY":i,"OK-ACCESS-SIGN":await Me(p,s),"OK-ACCESS-TIMESTAMP":c,"OK-ACCESS-PASSPHRASE":n,"OK-ACCESS-PROJECT":a}}var je=(o,e)=>{let t=_transactions.TransactionDataBuilder.restore(o.getData()),r=t.commands.findIndex(n=>n.$kind==="MoveCall"&&_utils.normalizeSuiAddress.call(void 0, n.MoveCall.package)===_utils.normalizeSuiAddress.call(void 0, e)&&n.MoveCall.module==="router"&&n.MoveCall.function==="finalize"),i=t.commands[r];return _chunkE5KM5OVWjs.j.assert(i.MoveCall,"OKX: Finalize command not found",1100,{packageId:e}),t.replaceCommand(r,_transactions.TransactionCommands.MoveCall({package:e,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(t.build()),coin:{NestedResult:[r,0]}}},ie=o=>{let{quote:e,signer:t}=o;_chunkE5KM5OVWjs.k.call(void 0, e,"okx");let r=_transactions.Transaction.from(e.quote.tx.data);r.setSenderIfNotSet(t);let{tx:i,coin:s}=je(r,e.quote.tx.to);return{tx:i,coin:s}},oe=async(o,e,t,r)=>{let{tx:i,coin:s}=ie({quote:o,signer:o.quote.tx.from});i.add(_chunkE5KM5OVWjs.n.call(void 0, o,s,1e4,r.tipBps,r.partner,r.partnerCommissionBps)),i.transferObjects([s],o.quote.tx.from);let n=await _chunkE5KM5OVWjs.l.call(void 0, i,e,t);return{id:o.id,provider:o.provider,...n}};var Ne=()=>new (0, _grpc.SuiGrpcClient)({baseUrl:_jsonRpc.getJsonRpcFullnodeUrl.call(void 0, "mainnet"),network:"mainnet"}),Qe="https://hermes.pyth.network",qe={bluefin7k:{},flowx:{},cetus:{}},R= exports.MetaAg =class{constructor(e){_chunkE5KM5OVWjs.a.call(void 0, this,"client");_chunkE5KM5OVWjs.a.call(void 0, this,"providers",{});_chunkE5KM5OVWjs.a.call(void 0, this,"inspector");_chunkE5KM5OVWjs.a.call(void 0, this,"options");this.client=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _12 => _12.client]), () => (Ne())),this.options={providers:{...qe,..._optionalChain([e, 'optionalAccess', _13 => _13.providers])},slippageBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _14 => _14.slippageBps]), () => (100)),client:this.client,hermesApi:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _15 => _15.hermesApi]), () => (Qe)),partner:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.partner]), () => (ee)),partnerCommissionBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _17 => _17.partnerCommissionBps]), () => (0)),tipBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _18 => _18.tipBps]), () => (0))},this.inspector=new x(this.client)}async _getProvider(e){let t=this.providers[e];if(t)return t;let r=this.options.providers[e];switch(_chunkE5KM5OVWjs.j.assert(!!r,`Provider not found: ${e}`,1002,{provider:e}),e){case"bluefin7k":let{Bluefin7kProvider:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("./bluefin7k-MP3A4MG4.js"))).catch(K("bluefin7k"));this.providers.bluefin7k=new i(r,this.options,this.client);break;case"flowx":let{FlowxProvider:s}=await Promise.resolve().then(() => _interopRequireWildcard(require("./flowx-SIZHC2DP.js"))).catch(K("flowx"));this.providers.flowx=new s(r,this.client);break;case"cetus":let{CetusProvider:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./cetus-MUHFO44Y.js"))).catch(K("cetus"));this.providers.cetus=new n(r,this.options,this.client);break;case"okx":this.providers.okx=new j(r,this.options,this.client);break;default:throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${e}`,1003,{provider:e})}return this.providers[e]}async _simulate(e,t,r){try{if(_chunkE5KM5OVWjs.f.call(void 0, e))return await _chunkE5KM5OVWjs.m.call(void 0, e,t,r,this.inspector,this.options);if(t.provider==="okx")return await oe(t,this.inspector,r,this.options);throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${e.kind}`,1003,{provider:e.kind})}catch(i){console.warn(i,{provider:e.kind,quote:t.id});return}}async _quote(e,t){return await _chunkE5KM5OVWjs.o.call(void 0, async()=>{let i=await e.quote(t);if(!i)return null;let{expectedAmount:s}=_chunkE5KM5OVWjs.i.call(void 0, i.rawAmountOut,0,this.options.partnerCommissionBps,this.options.tipBps);return i.amountOut=s,i},_nullishCoalesce(t.timeout, () => (2e3)),`quote for ${e.kind} provider from ${t.coinTypeIn} to ${t.coinTypeOut}`)}async _fastSwap({quote:e,signer:t,useGasCoin:r,signTransaction:i},s){let n=new _transactions.Transaction,a=await this.swap({quote:e,signer:t,tx:n,coinIn:_transactions.coinWithBalance.call(void 0, {type:e.coinTypeIn,balance:BigInt(e.amountIn),useGasCoin:r})});n.transferObjects([a],t),n.setSenderIfNotSet(t);let c=await n.build({client:this.client}),{signature:p,bytes:d}=await i(_utils.toBase64.call(void 0, c));return this.client.core.executeTransaction({transaction:_utils.fromBase64.call(void 0, d),signatures:[p],signal:_optionalChain([s, 'optionalAccess', _19 => _19.signal]),include:_optionalChain([s, 'optionalAccess', _20 => _20.include])})}async quote(e,t){let r={...e,coinTypeIn:_utils.normalizeStructTag.call(void 0, e.coinTypeIn),coinTypeOut:_utils.normalizeStructTag.call(void 0, e.coinTypeOut)},s=(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(t){let n=s.map(async a=>{let c=await this._getProvider(a.provider),p=await this._simulate(c,a,t);a.simulatedAmountOut=_optionalChain([p, 'optionalAccess', _21 => _21.simulatedAmountOut]),a.gasUsed=_optionalChain([p, 'optionalAccess', _22 => _22.gasUsed]),_optionalChain([t, 'optionalAccess', _23 => _23.onSimulated, 'optionalCall', _24 => _24({...a})])});t.onSimulated||await Promise.all(n)}return s}async swap(e,t){let r=await this._getProvider(e.quote.provider);_chunkE5KM5OVWjs.j.assert(!!r,`Provider not found: ${e.quote.provider}`,1002,{provider:e.quote.provider}),_chunkE5KM5OVWjs.j.assert(_chunkE5KM5OVWjs.f.call(void 0, r),`Provider does not support swap: ${r.kind}, use fastSwap instead`,1007,{provider:r.kind}),_chunkE5KM5OVWjs.j.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let i=await r.swap(e);return e.tx.add(_chunkE5KM5OVWjs.n.call(void 0, e.quote,i,_nullishCoalesce(_nullishCoalesce(t, () => (this.options.slippageBps)), () => (100)),this.options.tipBps,this.options.partner,this.options.partnerCommissionBps)),e.tx.setSenderIfNotSet(e.signer),i}async fastSwap(e,t){_chunkE5KM5OVWjs.j.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let r=await this._getProvider(e.quote.provider);if(_chunkE5KM5OVWjs.f.call(void 0, r))return this._fastSwap(e,t);if(_chunkE5KM5OVWjs.g.call(void 0, r))return this.client.core.waitForTransaction({digest:await r.fastSwap(e),signal:_optionalChain([t, 'optionalAccess', _25 => _25.signal]),include:_optionalChain([t, 'optionalAccess', _26 => _26.include])});throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${r.kind}`,1003,{provider:r.kind})}updateMetaAgOptions(e){if(Object.keys(e).length===0)return;this.options.slippageBps=_nullishCoalesce(e.slippageBps, () => (this.options.slippageBps)),this.options.partner=_nullishCoalesce(e.partner, () => (this.options.partner)),this.options.partnerCommissionBps=_nullishCoalesce(e.partnerCommissionBps, () => (this.options.partnerCommissionBps)),this.options.tipBps=_nullishCoalesce(e.tipBps, () => (this.options.tipBps));let t=!!(e.client&&e.client!==this.client),r=!!(e.hermesApi&&e.hermesApi!==this.options.hermesApi);t&&(this.client=e.client,this.options.client=this.client,this.inspector=new x(this.client)),r&&(this.options.hermesApi=e.hermesApi),(t||r)&&(this.providers={});for(let[i,s]of Object.entries(e.providers||{}))this.options.providers[i]={...s,...this.options.providers[i]},delete this.providers[i]}},K=o=>e=>{let t={cetus:"@cetusprotocol/aggregator-sdk",flowx:"@flowx-finance/sdk",bluefin7k:"@bluefin-exchange/bluefin7k-aggregator-sdk",okx:""};throw console.warn(`Please install ${t[o]} to use ${o} provider`),e};async function g(o,e){let t=new Headers(_optionalChain([e, 'optionalAccess', _27 => _27.headers])),r={...e,headers:t};return fetch(o,r)}var L={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(o){return o===b?k:o}var Ke=(o,e)=>{let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t},ce=500,Ve=100;function We(){return Math.floor(Date.now()/1e3).toString()}async function V(o){try{let e=B(o);return(await W([e]))[e]||0}catch (e2){return 0}}async function W(o){try{if(o.length===0)return{};let e=o.slice(0,ce).map(B),t=Ke(e,Ve),r=We(),s=(await Promise.all(t.map(async a=>{let c={timestamp:r,token_ids:a},p=await g(`${L.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 e.reduce((a,c)=>(a[c]=s[c]||0,a),{})}catch (e3){return o.slice(0,ce).reduce((t,r)=>(t[B(r)]=0,t),{})}}async function pe(){return await V(k)}var U="0xffc7f420b481ed7a012b42e125fd7e5716b5673759cf4629e5fcfebce970a72d",hr=BigInt("1000000000000"),yr=BigInt("10000"),X="0x0ef0f805710cf53c10f29c4f73e1144a662747e1839689a846e2520cae122adc",w=`${X}::limit_order`,$=`${X}::dca_order`,Cr=`${X}::config`,Tr=BigInt("18446744073709551615"),f=`${L.LO_DCA}/api`;async function ue({accountAddress:o,payCoinType:e,targetCoinType:t,payCoinAmount:r,rate:i,slippage:s,expireTs:n,devInspect:a}){let c=new _transactions.Transaction,p=c.add(_transactions.coinWithBalance.call(void 0, {type:e,balance:r,useGasCoin:!a}));return c.moveCall({target:`${w}::place_limit_order`,arguments:[c.object(U),p,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.object.clock()],typeArguments:[e,t]}),c.setSenderIfNotSet(o),c}async function le({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${w}::cancel_limit_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}async function me({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${w}::claim_expired_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}function O(o){let e="";return Object.entries(o).forEach(([t,r])=>{if(Array.isArray(r))for(let i of r)e+=e?`&${t}=${i}`:`${t}=${i}`;else r!==void 0&&(e+=e?`&${t}=${r}`:`${t}=${r}`)}),e}async function de({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open limit orders");return await n.json()}async function ge({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["CLOSED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch closed limit orders");return await n.json()}async function fe({payCoinType:o,targetCoinType:e,payCoinAmountEach:t,numOrders:r,interval:i,slippage:s,minRate:n,maxRate:a}){let c=new _transactions.Transaction,p=[];for(let I=0;I<r;I++){let Te=_transactions.coinWithBalance.call(void 0, {type:o,balance:t});p.push(Te)}let d=c.makeMoveVec({elements:p});return c.moveCall({target:`${$}::place_dca_order`,arguments:[c.object(U),d,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.pure.u64(a),c.object.clock()],typeArguments:[o,e]}),c}async function Oe({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${$}::cancel_dca_order`,arguments:[r.object(o),r.object.clock()],typeArguments:[e,t]}),r}async function he({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/dca-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open dca orders");return await n.json()}async function ye({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["SUCCESS"],offset:e,limit:t,orderType:"DCA",tokenPair:r}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch closed dca orders");return await n.json()}async function Ce({owner:o,orderId:e,offset:t=0,limit:r=10}){let s=O({owner:o,orderId:e,statuses:["SUCCESS"],offset:t,limit:r,orderType:"DCA"}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch dca order executions");return await n.json()}var Tn={getTokenPrice:V,getTokenPrices:W,getSuiPrice:pe,placeLimitOrder:ue,getOpenLimitOrders:de,cancelLimitOrder:le,claimExpiredLimitOrder:me,getClosedLimitOrders:ge,placeDcaOrder:fe,getOpenDcaOrders:he,cancelDcaOrder:Oe,getClosedDcaOrders:ye,getDcaOrderExecutions:Ce,MetaAg:R};exports.EProvider = _chunkE5KM5OVWjs.e; exports.MetaAg = R; exports.cancelDcaOrder = Oe; exports.cancelLimitOrder = le; exports.claimExpiredLimitOrder = me; exports.default = Tn; exports.getClosedDcaOrders = ye; exports.getClosedLimitOrders = ge; exports.getDcaOrderExecutions = Ce; exports.getOpenDcaOrders = he; exports.getOpenLimitOrders = de; exports.getSuiPrice = pe; exports.getTokenPrice = V; exports.getTokenPrices = W; exports.isAggregatorProvider = _chunkE5KM5OVWjs.f; exports.isSwapAPIProvider = _chunkE5KM5OVWjs.g; exports.placeDcaOrder = fe; exports.placeLimitOrder = ue;
|
|
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 _chunkE5KM5OVWjs = require('./chunk-E5KM5OVW.js');var _grpc = require('@mysten/sui/grpc');var _jsonRpc = require('@mysten/sui/jsonRpc');var _transactions = require('@mysten/sui/transactions');var _utils = require('@mysten/sui/utils');var ee="0x0000000000000000000000000000000000000000000000000000000000000000";var be=["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000003","0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000005","0x0000000000000000000000000000000000000000000000000000000000000006","0x0000000000000000000000000000000000000000000000000000000000000007","0x0000000000000000000000000000000000000000000000000000000000000008","0x0000000000000000000000000000000000000000000000000000000000000009","0x0000000000000000000000000000000000000000000000000000000000000403","0x000000000000000000000000000000000000000000000000000000000000000c"],S=o=>{let e=_utils.normalizeSuiAddress.call(void 0, o);return be.includes(e)};var Q=class{async getObject(e){let[t,r]=await Promise.all([this.get("OwnedObject",e),this.get("SharedOrImmutableObject",e)]);return _nullishCoalesce(_nullishCoalesce(t, () => (r)), () => (null))}async getObjects(e){return Promise.all(e.map(t=>this.getObject(t)))}async addObject(e){return e.owner?await this.set("OwnedObject",e.objectId,e):await this.set("SharedOrImmutableObject",e.objectId,e),e}async addObjects(e){await Promise.all(e.map(async t=>this.addObject(t)))}async deleteObject(e){await Promise.all([this.delete("OwnedObject",e),this.delete("SharedOrImmutableObject",e)])}async deleteObjects(e){await Promise.all(e.map(t=>this.deleteObject(t)))}async getMoveFunctionDefinition(e){let t=`${_utils.normalizeSuiAddress.call(void 0, e.package)}::${e.module}::${e.function}`;return this.get("MoveFunction",t)}async addMoveFunctionDefinition(e){let t=_utils.normalizeSuiAddress.call(void 0, e.package),r=`${t}::${e.module}::${e.function}`,i={...e,package:t};return await this.set("MoveFunction",r,i),i}async deleteMoveFunctionDefinition(e){let t=`${_utils.normalizeSuiAddress.call(void 0, e.package)}::${e.module}::${e.function}`;await this.delete("MoveFunction",t)}async getCustom(e){return this.get("Custom",e)}async setCustom(e,t){return this.set("Custom",e,t)}async deleteCustom(e){return this.delete("Custom",e)}},C,q=class extends Q{constructor(){super(...arguments);_chunkE5KM5OVWjs.c.call(void 0, this,C,{OwnedObject:new Map,SharedOrImmutableObject:new Map,MoveFunction:new Map,Custom:new Map})}async get(t,r){return _nullishCoalesce(_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].get(r), () => (null))}async set(t,r,i){_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].set(r,i)}async delete(t,r){_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].delete(r)}async clear(t){if(t)_chunkE5KM5OVWjs.b.call(void 0, this,C)[t].clear();else for(let r of Object.values(_chunkE5KM5OVWjs.b.call(void 0, this,C)))r.clear()}};C=new WeakMap;var E,l,A,M=class{constructor({cache:e=new q,onEffects:t,client:r}){_chunkE5KM5OVWjs.c.call(void 0, this,E);_chunkE5KM5OVWjs.c.call(void 0, this,l);_chunkE5KM5OVWjs.c.call(void 0, this,A);_chunkE5KM5OVWjs.d.call(void 0, this,E,r),_chunkE5KM5OVWjs.d.call(void 0, this,l,e),_chunkE5KM5OVWjs.d.call(void 0, this,A,t)}async applyCache(e,t){let r=(await _chunkE5KM5OVWjs.b.call(void 0, this,l).getObjects(t)).filter(n=>n!==null),i=new Map(r.map(n=>[n.objectId,n])),s=[];for(let n of e.inputs){if(!n.UnresolvedObject)continue;let a=i.get(n.UnresolvedObject.objectId);if(!a){s.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 s}async resolveObjects(e,t){let r=await this.applyCache(e,t);if(r.length===0)return[];let i=[...new Set(r)],s=await _chunkE5KM5OVWjs.b.call(void 0, this,E).core.getObjects({objectIds:i}),n=[];for(let a of s.objects){if(a instanceof Error)continue;let c=a.owner,p=c.$kind==="Shared"?c.Shared.initialSharedVersion:null,d=c.$kind==="AddressOwner"?c.AddressOwner:c.$kind==="ObjectOwner"?c.ObjectOwner:null,I={objectId:a.objectId,version:a.version,digest:a.digest,initialSharedVersion:p,owner:d};n.push(I)}return await _chunkE5KM5OVWjs.b.call(void 0, this,l).addObjects(n),await this.applyCache(e,r)}asPlugin(){return async(e,t,r)=>{let i=e.inputs.filter(s=>s.UnresolvedObject).map(s=>s.UnresolvedObject.objectId);await this.resolveObjects(e,i),await Promise.all(e.commands.map(async s=>{if(s.MoveCall){let n=await this.getMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function});n&&(s.MoveCall._argumentTypes=n.parameters)}})),await r(),await Promise.all(e.commands.map(async s=>{_optionalChain([s, 'access', _2 => _2.MoveCall, 'optionalAccess', _3 => _3._argumentTypes])&&await _chunkE5KM5OVWjs.b.call(void 0, this,l).addMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function,parameters:s.MoveCall._argumentTypes})}))}}async clear(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear()}async getMoveFunctionDefinition(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getMoveFunctionDefinition(e)}async getObjects(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getObjects(e)}async deleteObjects(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).deleteObjects(e)}async clearOwnedObjects(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear("OwnedObject")}async clearCustom(){await _chunkE5KM5OVWjs.b.call(void 0, this,l).clear("Custom")}async getCustom(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).getCustom(e)}async setCustom(e,t){return _chunkE5KM5OVWjs.b.call(void 0, this,l).setCustom(e,t)}async deleteCustom(e){return _chunkE5KM5OVWjs.b.call(void 0, this,l).deleteCustom(e)}async applyEffects(e){var n;if(!e.V2)throw new Error(`Unsupported transaction effects version ${e.$kind}`);let{lamportVersion:t,changedObjects:r}=e.V2,i=[],s=[];r.forEach(([a,c])=>{if(c.outputState.NotExist)i.push(a);else if(c.outputState.ObjectWrite){let[p,d]=c.outputState.ObjectWrite;s.push({objectId:a,digest:p,version:t,owner:_nullishCoalesce(_nullishCoalesce(d.AddressOwner, () => (d.ObjectOwner)), () => (null)),initialSharedVersion:_nullishCoalesce(_optionalChain([d, 'access', _4 => _4.Shared, 'optionalAccess', _5 => _5.initialSharedVersion]), () => (null))})}}),await Promise.all([_chunkE5KM5OVWjs.b.call(void 0, this,l).addObjects(s),_chunkE5KM5OVWjs.b.call(void 0, this,l).deleteObjects(i),(n=_chunkE5KM5OVWjs.b.call(void 0, this,A))==null?void 0:n.call(this,e)])}};E=new WeakMap,l=new WeakMap,A=new WeakMap;var T,_,x=class{constructor(e){this.client=e;_chunkE5KM5OVWjs.c.call(void 0, this,T);_chunkE5KM5OVWjs.c.call(void 0, this,_,new WeakSet);_chunkE5KM5OVWjs.a.call(void 0, this,"simulateTransaction",async e=>{e.transactionBlock.setSenderIfNotSet(e.sender),_chunkE5KM5OVWjs.b.call(void 0, this,_).has(e.transactionBlock)||(e.transactionBlock.addBuildPlugin(_chunkE5KM5OVWjs.b.call(void 0, this,T).asPlugin()),_chunkE5KM5OVWjs.b.call(void 0, this,_).add(e.transactionBlock));try{return await this.client.core.simulateTransaction({transaction:e.transactionBlock,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}})}catch(t){throw await _chunkE5KM5OVWjs.b.call(void 0, this,T).clear(),t}finally{await _chunkE5KM5OVWjs.b.call(void 0, this,T).clearOwnedObjects()}});_chunkE5KM5OVWjs.d.call(void 0, this,T,new M({client:this.client}))}};T=new WeakMap,_=new WeakMap;var _uuid = require('uuid');var b="0x2::sui::SUI",k="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie="https://web3.okx.com",re="/api/v6/dex/aggregator/swap",De="784",ne=_utils.normalizeStructTag.call(void 0, b),j=class{constructor(e,t,r){this.options=e;this.metaOptions=t;this.client=r;_chunkE5KM5OVWjs.a.call(void 0, this,"kind","okx")}async quote({amountIn:e,coinTypeIn:t,coinTypeOut:r,signer:i}){if(!i||S(i))return null;let s={chainIndex:De,amount:e,fromTokenAddress:t===ne?b:t,toTokenAddress:r===ne?b:r,slippagePercent:(this.metaOptions.slippageBps/100).toString(),userWalletAddress:i},n="?"+new URLSearchParams(s).toString(),a=`${_nullishCoalesce(this.options.api, () => (Ie))}${re}${n}`,p=await(await fetch(a,{headers:await ke(this.options,"GET",re,n)})).json();return _chunkE5KM5OVWjs.j.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:t,coinTypeOut:r,amountIn:e,amountOut:p.data[0].routerResult.toTokenAmount,rawAmountOut:p.data[0].routerResult.toTokenAmount,quote:p.data[0]}}async fastSwap(e){let{quote:t,signer:r,signTransaction:i}=e;_chunkE5KM5OVWjs.k.call(void 0, t,"okx");let{tx:s,coin:n}=ie({quote:t,signer:r});s.add(_chunkE5KM5OVWjs.n.call(void 0, t,n,this.metaOptions.slippageBps,this.metaOptions.tipBps,this.metaOptions.partner,this.metaOptions.partnerCommissionBps)),s.transferObjects([n],r);let a=await s.build({client:this.client}),{bytes:c,signature:p}=await i(_utils.toBase64.call(void 0, a)),d=await this.client.core.executeTransaction({transaction:_utils.fromBase64.call(void 0, c),signatures:[p]});if(!_optionalChain([d, 'access', _6 => _6.Transaction, 'optionalAccess', _7 => _7.digest]))throw new (0, _chunkE5KM5OVWjs.j)("OKX transaction failed or returned no digest",1008,{error:_nullishCoalesce(_optionalChain([d, 'access', _8 => _8.FailedTransaction, 'optionalAccess', _9 => _9.digest]), () => ("no digest"))});return d.Transaction.digest}};async function Me(o,e){let t=new TextEncoder,r=s=>{if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let n="";for(let a=0;a<s.byteLength;a++)n+=String.fromCharCode(s[a]);if(typeof btoa<"u")return btoa(n);throw new (0, _chunkE5KM5OVWjs.j)("Base64 encoder not available in this environment")};if(typeof globalThis<"u"&&_optionalChain([globalThis, 'access', _10 => _10.crypto, 'optionalAccess', _11 => _11.subtle])){let s=await globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await globalThis.crypto.subtle.sign("HMAC",s,t.encode(o));return r(new Uint8Array(n))}let{createHmac:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("crypto")));return i("sha256",e).update(o).digest("base64")}async function ke(o,e,t,r=""){let{apiKey:i,secretKey:s,apiPassphrase:n,projectId:a}=o;if(!i||!s||!n||!a)throw new (0, _chunkE5KM5OVWjs.j)("Missing required environment variables");let c=new Date().toISOString(),p=c+e+t+r;return{"Content-Type":"application/json","OK-ACCESS-KEY":i,"OK-ACCESS-SIGN":await Me(p,s),"OK-ACCESS-TIMESTAMP":c,"OK-ACCESS-PASSPHRASE":n,"OK-ACCESS-PROJECT":a}}var je=(o,e)=>{let t=_transactions.TransactionDataBuilder.restore(o.getData()),r=t.commands.findIndex(n=>n.$kind==="MoveCall"&&_utils.normalizeSuiAddress.call(void 0, n.MoveCall.package)===_utils.normalizeSuiAddress.call(void 0, e)&&n.MoveCall.module==="router"&&n.MoveCall.function==="finalize"),i=t.commands[r];return _chunkE5KM5OVWjs.j.assert(i.MoveCall,"OKX: Finalize command not found",1100,{packageId:e}),t.replaceCommand(r,_transactions.TransactionCommands.MoveCall({package:e,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(t.build()),coin:{NestedResult:[r,0]}}},ie=o=>{let{quote:e,signer:t}=o;_chunkE5KM5OVWjs.k.call(void 0, e,"okx");let r=_transactions.Transaction.from(e.quote.tx.data);r.setSenderIfNotSet(t);let{tx:i,coin:s}=je(r,e.quote.tx.to);return{tx:i,coin:s}},oe=async(o,e,t,r)=>{let{tx:i,coin:s}=ie({quote:o,signer:o.quote.tx.from});i.add(_chunkE5KM5OVWjs.n.call(void 0, o,s,1e4,r.tipBps,r.partner,r.partnerCommissionBps)),i.transferObjects([s],o.quote.tx.from);let n=await _chunkE5KM5OVWjs.l.call(void 0, i,e,t);return{id:o.id,provider:o.provider,...n}};var Ne=()=>new (0, _grpc.SuiGrpcClient)({baseUrl:_jsonRpc.getJsonRpcFullnodeUrl.call(void 0, "mainnet"),network:"mainnet"}),Qe="https://hermes.pyth.network",qe={bluefin7k:{},flowx:{},cetus:{}},R= exports.MetaAg =class{constructor(e){_chunkE5KM5OVWjs.a.call(void 0, this,"client");_chunkE5KM5OVWjs.a.call(void 0, this,"providers",{});_chunkE5KM5OVWjs.a.call(void 0, this,"inspector");_chunkE5KM5OVWjs.a.call(void 0, this,"options");this.client=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _12 => _12.client]), () => (Ne())),this.options={providers:{...qe,..._optionalChain([e, 'optionalAccess', _13 => _13.providers])},slippageBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _14 => _14.slippageBps]), () => (100)),client:this.client,hermesApi:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _15 => _15.hermesApi]), () => (Qe)),partner:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.partner]), () => (ee)),partnerCommissionBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _17 => _17.partnerCommissionBps]), () => (0)),tipBps:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _18 => _18.tipBps]), () => (0))},this.inspector=new x(this.client)}async _getProvider(e){let t=this.providers[e];if(t)return t;let r=this.options.providers[e];switch(_chunkE5KM5OVWjs.j.assert(!!r,`Provider not found: ${e}`,1002,{provider:e}),e){case"bluefin7k":let{Bluefin7kProvider:i}=await Promise.resolve().then(() => _interopRequireWildcard(require("./bluefin7k-MP3A4MG4.js"))).catch(K("bluefin7k"));this.providers.bluefin7k=new i(r,this.options,this.client);break;case"flowx":let{FlowxProvider:s}=await Promise.resolve().then(() => _interopRequireWildcard(require("./flowx-RRIX3SC4.js"))).catch(K("flowx"));this.providers.flowx=new s(r,this.client);break;case"cetus":let{CetusProvider:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./cetus-MUHFO44Y.js"))).catch(K("cetus"));this.providers.cetus=new n(r,this.options,this.client);break;case"okx":this.providers.okx=new j(r,this.options,this.client);break;default:throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${e}`,1003,{provider:e})}return this.providers[e]}async _simulate(e,t,r){try{if(_chunkE5KM5OVWjs.f.call(void 0, e))return await _chunkE5KM5OVWjs.m.call(void 0, e,t,r,this.inspector,this.options);if(t.provider==="okx")return await oe(t,this.inspector,r,this.options);throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${e.kind}`,1003,{provider:e.kind})}catch(i){console.warn(i,{provider:e.kind,quote:t.id});return}}async _quote(e,t){return await _chunkE5KM5OVWjs.o.call(void 0, async()=>{let i=await e.quote(t);if(!i)return null;let{expectedAmount:s}=_chunkE5KM5OVWjs.i.call(void 0, i.rawAmountOut,0,this.options.partnerCommissionBps,this.options.tipBps);return i.amountOut=s,i},_nullishCoalesce(t.timeout, () => (2e3)),`quote for ${e.kind} provider from ${t.coinTypeIn} to ${t.coinTypeOut}`)}async _fastSwap({quote:e,signer:t,useGasCoin:r,signTransaction:i},s){let n=new _transactions.Transaction,a=await this.swap({quote:e,signer:t,tx:n,coinIn:_transactions.coinWithBalance.call(void 0, {type:e.coinTypeIn,balance:BigInt(e.amountIn),useGasCoin:r})});n.transferObjects([a],t),n.setSenderIfNotSet(t);let c=await n.build({client:this.client}),{signature:p,bytes:d}=await i(_utils.toBase64.call(void 0, c));return this.client.core.executeTransaction({transaction:_utils.fromBase64.call(void 0, d),signatures:[p],signal:_optionalChain([s, 'optionalAccess', _19 => _19.signal]),include:_optionalChain([s, 'optionalAccess', _20 => _20.include])})}async quote(e,t){let r={...e,coinTypeIn:_utils.normalizeStructTag.call(void 0, e.coinTypeIn),coinTypeOut:_utils.normalizeStructTag.call(void 0, e.coinTypeOut)},s=(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(t){let n=s.map(async a=>{let c=await this._getProvider(a.provider),p=await this._simulate(c,a,t);a.simulatedAmountOut=_optionalChain([p, 'optionalAccess', _21 => _21.simulatedAmountOut]),a.gasUsed=_optionalChain([p, 'optionalAccess', _22 => _22.gasUsed]),_optionalChain([t, 'optionalAccess', _23 => _23.onSimulated, 'optionalCall', _24 => _24({...a})])});t.onSimulated||await Promise.all(n)}return s}async swap(e,t){let r=await this._getProvider(e.quote.provider);_chunkE5KM5OVWjs.j.assert(!!r,`Provider not found: ${e.quote.provider}`,1002,{provider:e.quote.provider}),_chunkE5KM5OVWjs.j.assert(_chunkE5KM5OVWjs.f.call(void 0, r),`Provider does not support swap: ${r.kind}, use fastSwap instead`,1007,{provider:r.kind}),_chunkE5KM5OVWjs.j.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let i=await r.swap(e);return e.tx.add(_chunkE5KM5OVWjs.n.call(void 0, e.quote,i,_nullishCoalesce(_nullishCoalesce(t, () => (this.options.slippageBps)), () => (100)),this.options.tipBps,this.options.partner,this.options.partnerCommissionBps)),e.tx.setSenderIfNotSet(e.signer),i}async fastSwap(e,t){_chunkE5KM5OVWjs.j.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let r=await this._getProvider(e.quote.provider);if(_chunkE5KM5OVWjs.f.call(void 0, r))return this._fastSwap(e,t);if(_chunkE5KM5OVWjs.g.call(void 0, r))return this.client.core.waitForTransaction({digest:await r.fastSwap(e),signal:_optionalChain([t, 'optionalAccess', _25 => _25.signal]),include:_optionalChain([t, 'optionalAccess', _26 => _26.include])});throw new (0, _chunkE5KM5OVWjs.j)(`Provider not supported: ${r.kind}`,1003,{provider:r.kind})}updateMetaAgOptions(e){if(Object.keys(e).length===0)return;this.options.slippageBps=_nullishCoalesce(e.slippageBps, () => (this.options.slippageBps)),this.options.partner=_nullishCoalesce(e.partner, () => (this.options.partner)),this.options.partnerCommissionBps=_nullishCoalesce(e.partnerCommissionBps, () => (this.options.partnerCommissionBps)),this.options.tipBps=_nullishCoalesce(e.tipBps, () => (this.options.tipBps));let t=!!(e.client&&e.client!==this.client),r=!!(e.hermesApi&&e.hermesApi!==this.options.hermesApi);t&&(this.client=e.client,this.options.client=this.client,this.inspector=new x(this.client)),r&&(this.options.hermesApi=e.hermesApi),(t||r)&&(this.providers={});for(let[i,s]of Object.entries(e.providers||{}))this.options.providers[i]={...s,...this.options.providers[i]},delete this.providers[i]}},K=o=>e=>{let t={cetus:"@cetusprotocol/aggregator-sdk",flowx:"@flowx-finance/sdk",bluefin7k:"@bluefin-exchange/bluefin7k-aggregator-sdk",okx:""};throw console.warn(`Please install ${t[o]} to use ${o} provider`),e};async function g(o,e){let t=new Headers(_optionalChain([e, 'optionalAccess', _27 => _27.headers])),r={...e,headers:t};return fetch(o,r)}var L={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(o){return o===b?k:o}var Ke=(o,e)=>{let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t},ce=500,Ve=100;function We(){return Math.floor(Date.now()/1e3).toString()}async function V(o){try{let e=B(o);return(await W([e]))[e]||0}catch (e2){return 0}}async function W(o){try{if(o.length===0)return{};let e=o.slice(0,ce).map(B),t=Ke(e,Ve),r=We(),s=(await Promise.all(t.map(async a=>{let c={timestamp:r,token_ids:a},p=await g(`${L.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 e.reduce((a,c)=>(a[c]=s[c]||0,a),{})}catch (e3){return o.slice(0,ce).reduce((t,r)=>(t[B(r)]=0,t),{})}}async function pe(){return await V(k)}var U="0xffc7f420b481ed7a012b42e125fd7e5716b5673759cf4629e5fcfebce970a72d",hr=BigInt("1000000000000"),yr=BigInt("10000"),X="0x0ef0f805710cf53c10f29c4f73e1144a662747e1839689a846e2520cae122adc",w=`${X}::limit_order`,$=`${X}::dca_order`,Cr=`${X}::config`,Tr=BigInt("18446744073709551615"),f=`${L.LO_DCA}/api`;async function ue({accountAddress:o,payCoinType:e,targetCoinType:t,payCoinAmount:r,rate:i,slippage:s,expireTs:n,devInspect:a}){let c=new _transactions.Transaction,p=c.add(_transactions.coinWithBalance.call(void 0, {type:e,balance:r,useGasCoin:!a}));return c.moveCall({target:`${w}::place_limit_order`,arguments:[c.object(U),p,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.object.clock()],typeArguments:[e,t]}),c.setSenderIfNotSet(o),c}async function le({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${w}::cancel_limit_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}async function me({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${w}::claim_expired_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}function O(o){let e="";return Object.entries(o).forEach(([t,r])=>{if(Array.isArray(r))for(let i of r)e+=e?`&${t}=${i}`:`${t}=${i}`;else r!==void 0&&(e+=e?`&${t}=${r}`:`${t}=${r}`)}),e}async function de({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open limit orders");return await n.json()}async function ge({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["CLOSED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch closed limit orders");return await n.json()}async function fe({payCoinType:o,targetCoinType:e,payCoinAmountEach:t,numOrders:r,interval:i,slippage:s,minRate:n,maxRate:a}){let c=new _transactions.Transaction,p=[];for(let I=0;I<r;I++){let Te=_transactions.coinWithBalance.call(void 0, {type:o,balance:t});p.push(Te)}let d=c.makeMoveVec({elements:p});return c.moveCall({target:`${$}::place_dca_order`,arguments:[c.object(U),d,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.pure.u64(a),c.object.clock()],typeArguments:[o,e]}),c}async function Oe({orderId:o,payCoinType:e,targetCoinType:t}){let r=new _transactions.Transaction;return r.moveCall({target:`${$}::cancel_dca_order`,arguments:[r.object(o),r.object.clock()],typeArguments:[e,t]}),r}async function he({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/dca-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open dca orders");return await n.json()}async function ye({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["SUCCESS"],offset:e,limit:t,orderType:"DCA",tokenPair:r}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch closed dca orders");return await n.json()}async function Ce({owner:o,orderId:e,offset:t=0,limit:r=10}){let s=O({owner:o,orderId:e,statuses:["SUCCESS"],offset:t,limit:r,orderType:"DCA"}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch dca order executions");return await n.json()}var Tn={getTokenPrice:V,getTokenPrices:W,getSuiPrice:pe,placeLimitOrder:ue,getOpenLimitOrders:de,cancelLimitOrder:le,claimExpiredLimitOrder:me,getClosedLimitOrders:ge,placeDcaOrder:fe,getOpenDcaOrders:he,cancelDcaOrder:Oe,getClosedDcaOrders:ye,getDcaOrderExecutions:Ce,MetaAg:R};exports.EProvider = _chunkE5KM5OVWjs.e; exports.MetaAg = R; exports.cancelDcaOrder = Oe; exports.cancelLimitOrder = le; exports.claimExpiredLimitOrder = me; exports.default = Tn; exports.getClosedDcaOrders = ye; exports.getClosedLimitOrders = ge; exports.getDcaOrderExecutions = Ce; exports.getOpenDcaOrders = he; exports.getOpenLimitOrders = de; exports.getSuiPrice = pe; exports.getTokenPrice = V; exports.getTokenPrices = W; exports.isAggregatorProvider = _chunkE5KM5OVWjs.f; exports.isSwapAPIProvider = _chunkE5KM5OVWjs.g; exports.placeDcaOrder = fe; exports.placeLimitOrder = ue;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as h,b as u,c as y,d as P,e as z,f as D,g as G,i as H,j as m,k as F,l as Y,m as Z,n as v,o as J}from"./chunk-CYI4MM5C.mjs";import{SuiGrpcClient as Re}from"@mysten/sui/grpc";import{getJsonRpcFullnodeUrl as Le}from"@mysten/sui/jsonRpc";import{coinWithBalance as Be,Transaction as Ue}from"@mysten/sui/transactions";import{fromBase64 as $e,normalizeStructTag as ae,toBase64 as Fe}from"@mysten/sui/utils";var ee="0x0000000000000000000000000000000000000000000000000000000000000000";import{normalizeSuiAddress as Pe,parseStructTag as it}from"@mysten/sui/utils";var be=["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000003","0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000005","0x0000000000000000000000000000000000000000000000000000000000000006","0x0000000000000000000000000000000000000000000000000000000000000007","0x0000000000000000000000000000000000000000000000000000000000000008","0x0000000000000000000000000000000000000000000000000000000000000009","0x0000000000000000000000000000000000000000000000000000000000000403","0x000000000000000000000000000000000000000000000000000000000000000c"],S=o=>{let e=Pe(o);return be.includes(e)};import{normalizeSuiAddress as N}from"@mysten/sui/utils";var Q=class{async getObject(e){let[t,r]=await Promise.all([this.get("OwnedObject",e),this.get("SharedOrImmutableObject",e)]);return t??r??null}async getObjects(e){return Promise.all(e.map(t=>this.getObject(t)))}async addObject(e){return e.owner?await this.set("OwnedObject",e.objectId,e):await this.set("SharedOrImmutableObject",e.objectId,e),e}async addObjects(e){await Promise.all(e.map(async t=>this.addObject(t)))}async deleteObject(e){await Promise.all([this.delete("OwnedObject",e),this.delete("SharedOrImmutableObject",e)])}async deleteObjects(e){await Promise.all(e.map(t=>this.deleteObject(t)))}async getMoveFunctionDefinition(e){let t=`${N(e.package)}::${e.module}::${e.function}`;return this.get("MoveFunction",t)}async addMoveFunctionDefinition(e){let t=N(e.package),r=`${t}::${e.module}::${e.function}`,i={...e,package:t};return await this.set("MoveFunction",r,i),i}async deleteMoveFunctionDefinition(e){let t=`${N(e.package)}::${e.module}::${e.function}`;await this.delete("MoveFunction",t)}async getCustom(e){return this.get("Custom",e)}async setCustom(e,t){return this.set("Custom",e,t)}async deleteCustom(e){return this.delete("Custom",e)}},C,q=class extends Q{constructor(){super(...arguments);y(this,C,{OwnedObject:new Map,SharedOrImmutableObject:new Map,MoveFunction:new Map,Custom:new Map})}async get(t,r){return u(this,C)[t].get(r)??null}async set(t,r,i){u(this,C)[t].set(r,i)}async delete(t,r){u(this,C)[t].delete(r)}async clear(t){if(t)u(this,C)[t].clear();else for(let r of Object.values(u(this,C)))r.clear()}};C=new WeakMap;var E,l,A,M=class{constructor({cache:e=new q,onEffects:t,client:r}){y(this,E);y(this,l);y(this,A);P(this,E,r),P(this,l,e),P(this,A,t)}async applyCache(e,t){let r=(await u(this,l).getObjects(t)).filter(n=>n!==null),i=new Map(r.map(n=>[n.objectId,n])),s=[];for(let n of e.inputs){if(!n.UnresolvedObject)continue;let a=i.get(n.UnresolvedObject.objectId);if(!a){s.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 s}async resolveObjects(e,t){let r=await this.applyCache(e,t);if(r.length===0)return[];let i=[...new Set(r)],s=await u(this,E).core.getObjects({objectIds:i}),n=[];for(let a of s.objects){if(a instanceof Error)continue;let c=a.owner,p=c.$kind==="Shared"?c.Shared.initialSharedVersion:null,d=c.$kind==="AddressOwner"?c.AddressOwner:c.$kind==="ObjectOwner"?c.ObjectOwner:null,I={objectId:a.objectId,version:a.version,digest:a.digest,initialSharedVersion:p,owner:d};n.push(I)}return await u(this,l).addObjects(n),await this.applyCache(e,r)}asPlugin(){return async(e,t,r)=>{let i=e.inputs.filter(s=>s.UnresolvedObject).map(s=>s.UnresolvedObject.objectId);await this.resolveObjects(e,i),await Promise.all(e.commands.map(async s=>{if(s.MoveCall){let n=await this.getMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function});n&&(s.MoveCall._argumentTypes=n.parameters)}})),await r(),await Promise.all(e.commands.map(async s=>{s.MoveCall?._argumentTypes&&await u(this,l).addMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function,parameters:s.MoveCall._argumentTypes})}))}}async clear(){await u(this,l).clear()}async getMoveFunctionDefinition(e){return u(this,l).getMoveFunctionDefinition(e)}async getObjects(e){return u(this,l).getObjects(e)}async deleteObjects(e){return u(this,l).deleteObjects(e)}async clearOwnedObjects(){await u(this,l).clear("OwnedObject")}async clearCustom(){await u(this,l).clear("Custom")}async getCustom(e){return u(this,l).getCustom(e)}async setCustom(e,t){return u(this,l).setCustom(e,t)}async deleteCustom(e){return u(this,l).deleteCustom(e)}async applyEffects(e){var n;if(!e.V2)throw new Error(`Unsupported transaction effects version ${e.$kind}`);let{lamportVersion:t,changedObjects:r}=e.V2,i=[],s=[];r.forEach(([a,c])=>{if(c.outputState.NotExist)i.push(a);else if(c.outputState.ObjectWrite){let[p,d]=c.outputState.ObjectWrite;s.push({objectId:a,digest:p,version:t,owner:d.AddressOwner??d.ObjectOwner??null,initialSharedVersion:d.Shared?.initialSharedVersion??null})}}),await Promise.all([u(this,l).addObjects(s),u(this,l).deleteObjects(i),(n=u(this,A))==null?void 0:n.call(this,e)])}};E=new WeakMap,l=new WeakMap,A=new WeakMap;var T,_,x=class{constructor(e){this.client=e;y(this,T);y(this,_,new WeakSet);h(this,"simulateTransaction",async e=>{e.transactionBlock.setSenderIfNotSet(e.sender),u(this,_).has(e.transactionBlock)||(e.transactionBlock.addBuildPlugin(u(this,T).asPlugin()),u(this,_).add(e.transactionBlock));try{return await this.client.core.simulateTransaction({transaction:e.transactionBlock,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}})}catch(t){throw await u(this,T).clear(),t}finally{await u(this,T).clearOwnedObjects()}});P(this,T,new M({client:this.client}))}};T=new WeakMap,_=new WeakMap;import{TransactionCommands as ve,Transaction as se,TransactionDataBuilder as Se}from"@mysten/sui/transactions";import{fromBase64 as Ee,normalizeStructTag as Ae,normalizeSuiAddress as te,toBase64 as xe}from"@mysten/sui/utils";import{v4 as _e}from"uuid";var b="0x2::sui::SUI",k="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie="https://web3.okx.com",re="/api/v6/dex/aggregator/swap",De="784",ne=Ae(b),j=class{constructor(e,t,r){this.options=e;this.metaOptions=t;this.client=r;h(this,"kind","okx")}async quote({amountIn:e,coinTypeIn:t,coinTypeOut:r,signer:i}){if(!i||S(i))return null;let s={chainIndex:De,amount:e,fromTokenAddress:t===ne?b:t,toTokenAddress:r===ne?b:r,slippagePercent:(this.metaOptions.slippageBps/100).toString(),userWalletAddress:i},n="?"+new URLSearchParams(s).toString(),a=`${this.options.api??Ie}${re}${n}`,p=await(await fetch(a,{headers:await ke(this.options,"GET",re,n)})).json();return m.assert(p.code==="0"&&p.data.length>0,"No quote found",1005,{provider:this.kind}),{id:_e(),provider:this.kind,coinTypeIn:t,coinTypeOut:r,amountIn:e,amountOut:p.data[0].routerResult.toTokenAmount,rawAmountOut:p.data[0].routerResult.toTokenAmount,quote:p.data[0]}}async fastSwap(e){let{quote:t,signer:r,signTransaction:i}=e;F(t,"okx");let{tx:s,coin:n}=ie({quote:t,signer:r});s.add(v(t,n,this.metaOptions.slippageBps,this.metaOptions.tipBps,this.metaOptions.partner,this.metaOptions.partnerCommissionBps)),s.transferObjects([n],r);let a=await s.build({client:this.client}),{bytes:c,signature:p}=await i(xe(a)),d=await this.client.core.executeTransaction({transaction:Ee(c),signatures:[p]});if(!d.Transaction?.digest)throw new m("OKX transaction failed or returned no digest",1008,{error:d.FailedTransaction?.digest??"no digest"});return d.Transaction.digest}};async function Me(o,e){let t=new TextEncoder,r=s=>{if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let n="";for(let a=0;a<s.byteLength;a++)n+=String.fromCharCode(s[a]);if(typeof btoa<"u")return btoa(n);throw new m("Base64 encoder not available in this environment")};if(typeof globalThis<"u"&&globalThis.crypto?.subtle){let s=await globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await globalThis.crypto.subtle.sign("HMAC",s,t.encode(o));return r(new Uint8Array(n))}let{createHmac:i}=await import("crypto");return i("sha256",e).update(o).digest("base64")}async function ke(o,e,t,r=""){let{apiKey:i,secretKey:s,apiPassphrase:n,projectId:a}=o;if(!i||!s||!n||!a)throw new m("Missing required environment variables");let c=new Date().toISOString(),p=c+e+t+r;return{"Content-Type":"application/json","OK-ACCESS-KEY":i,"OK-ACCESS-SIGN":await Me(p,s),"OK-ACCESS-TIMESTAMP":c,"OK-ACCESS-PASSPHRASE":n,"OK-ACCESS-PROJECT":a}}var je=(o,e)=>{let t=Se.restore(o.getData()),r=t.commands.findIndex(n=>n.$kind==="MoveCall"&&te(n.MoveCall.package)===te(e)&&n.MoveCall.module==="router"&&n.MoveCall.function==="finalize"),i=t.commands[r];return m.assert(i.MoveCall,"OKX: Finalize command not found",1100,{packageId:e}),t.replaceCommand(r,ve.MoveCall({package:e,module:"router",function:"finalize_without_transfer",typeArguments:i.MoveCall.typeArguments,arguments:[i.MoveCall.arguments[0],i.MoveCall.arguments[5],i.MoveCall.arguments[6]]})),{tx:se.from(t.build()),coin:{NestedResult:[r,0]}}},ie=o=>{let{quote:e,signer:t}=o;F(e,"okx");let r=se.from(e.quote.tx.data);r.setSenderIfNotSet(t);let{tx:i,coin:s}=je(r,e.quote.tx.to);return{tx:i,coin:s}},oe=async(o,e,t,r)=>{let{tx:i,coin:s}=ie({quote:o,signer:o.quote.tx.from});i.add(v(o,s,1e4,r.tipBps,r.partner,r.partnerCommissionBps)),i.transferObjects([s],o.quote.tx.from);let n=await Y(i,e,t);return{id:o.id,provider:o.provider,...n}};var Ne=()=>new Re({baseUrl:Le("mainnet"),network:"mainnet"}),Qe="https://hermes.pyth.network",qe={bluefin7k:{},flowx:{},cetus:{}},R=class{constructor(e){h(this,"client");h(this,"providers",{});h(this,"inspector");h(this,"options");this.client=e?.client??Ne(),this.options={providers:{...qe,...e?.providers},slippageBps:e?.slippageBps??100,client:this.client,hermesApi:e?.hermesApi??Qe,partner:e?.partner??ee,partnerCommissionBps:e?.partnerCommissionBps??0,tipBps:e?.tipBps??0},this.inspector=new x(this.client)}async _getProvider(e){let t=this.providers[e];if(t)return t;let r=this.options.providers[e];switch(m.assert(!!r,`Provider not found: ${e}`,1002,{provider:e}),e){case"bluefin7k":let{Bluefin7kProvider:i}=await import("./bluefin7k-63A5CV3A.mjs").catch(K("bluefin7k"));this.providers.bluefin7k=new i(r,this.options,this.client);break;case"flowx":let{FlowxProvider:s}=await import("./flowx-533PLKYB.mjs").catch(K("flowx"));this.providers.flowx=new s(r,this.client);break;case"cetus":let{CetusProvider:n}=await import("./cetus-HOKHMQSS.mjs").catch(K("cetus"));this.providers.cetus=new n(r,this.options,this.client);break;case"okx":this.providers.okx=new j(r,this.options,this.client);break;default:throw new m(`Provider not supported: ${e}`,1003,{provider:e})}return this.providers[e]}async _simulate(e,t,r){try{if(D(e))return await Z(e,t,r,this.inspector,this.options);if(t.provider==="okx")return await oe(t,this.inspector,r,this.options);throw new m(`Provider not supported: ${e.kind}`,1003,{provider:e.kind})}catch(i){console.warn(i,{provider:e.kind,quote:t.id});return}}async _quote(e,t){return await J(async()=>{let i=await e.quote(t);if(!i)return null;let{expectedAmount:s}=H(i.rawAmountOut,0,this.options.partnerCommissionBps,this.options.tipBps);return i.amountOut=s,i},t.timeout??2e3,`quote for ${e.kind} provider from ${t.coinTypeIn} to ${t.coinTypeOut}`)}async _fastSwap({quote:e,signer:t,useGasCoin:r,signTransaction:i},s){let n=new Ue,a=await this.swap({quote:e,signer:t,tx:n,coinIn:Be({type:e.coinTypeIn,balance:BigInt(e.amountIn),useGasCoin:r})});n.transferObjects([a],t),n.setSenderIfNotSet(t);let c=await n.build({client:this.client}),{signature:p,bytes:d}=await i(Fe(c));return this.client.core.executeTransaction({transaction:$e(d),signatures:[p],signal:s?.signal,include:s?.include})}async quote(e,t){let r={...e,coinTypeIn:ae(e.coinTypeIn),coinTypeOut:ae(e.coinTypeOut)},s=(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(t){let n=s.map(async a=>{let c=await this._getProvider(a.provider),p=await this._simulate(c,a,t);a.simulatedAmountOut=p?.simulatedAmountOut,a.gasUsed=p?.gasUsed,t?.onSimulated?.({...a})});t.onSimulated||await Promise.all(n)}return s}async swap(e,t){let r=await this._getProvider(e.quote.provider);m.assert(!!r,`Provider not found: ${e.quote.provider}`,1002,{provider:e.quote.provider}),m.assert(D(r),`Provider does not support swap: ${r.kind}, use fastSwap instead`,1007,{provider:r.kind}),m.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let i=await r.swap(e);return e.tx.add(v(e.quote,i,t??this.options.slippageBps??100,this.options.tipBps,this.options.partner,this.options.partnerCommissionBps)),e.tx.setSenderIfNotSet(e.signer),i}async fastSwap(e,t){m.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let r=await this._getProvider(e.quote.provider);if(D(r))return this._fastSwap(e,t);if(G(r))return this.client.core.waitForTransaction({digest:await r.fastSwap(e),signal:t?.signal,include:t?.include});throw new m(`Provider not supported: ${r.kind}`,1003,{provider:r.kind})}updateMetaAgOptions(e){if(Object.keys(e).length===0)return;this.options.slippageBps=e.slippageBps??this.options.slippageBps,this.options.partner=e.partner??this.options.partner,this.options.partnerCommissionBps=e.partnerCommissionBps??this.options.partnerCommissionBps,this.options.tipBps=e.tipBps??this.options.tipBps;let t=!!(e.client&&e.client!==this.client),r=!!(e.hermesApi&&e.hermesApi!==this.options.hermesApi);t&&(this.client=e.client,this.options.client=this.client,this.inspector=new x(this.client)),r&&(this.options.hermesApi=e.hermesApi),(t||r)&&(this.providers={});for(let[i,s]of Object.entries(e.providers||{}))this.options.providers[i]={...s,...this.options.providers[i]},delete this.providers[i]}},K=o=>e=>{let t={cetus:"@cetusprotocol/aggregator-sdk",flowx:"@flowx-finance/sdk",bluefin7k:"@bluefin-exchange/bluefin7k-aggregator-sdk",okx:""};throw console.warn(`Please install ${t[o]} to use ${o} provider`),e};async function g(o,e){let t=new Headers(e?.headers),r={...e,headers:t};return fetch(o,r)}var L={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(o){return o===b?k:o}var Ke=(o,e)=>{let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t},ce=500,Ve=100;function We(){return Math.floor(Date.now()/1e3).toString()}async function V(o){try{let e=B(o);return(await W([e]))[e]||0}catch{return 0}}async function W(o){try{if(o.length===0)return{};let e=o.slice(0,ce).map(B),t=Ke(e,Ve),r=We(),s=(await Promise.all(t.map(async a=>{let c={timestamp:r,token_ids:a},p=await g(`${L.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 e.reduce((a,c)=>(a[c]=s[c]||0,a),{})}catch{return o.slice(0,ce).reduce((t,r)=>(t[B(r)]=0,t),{})}}async function pe(){return await V(k)}import{coinWithBalance as Xe,Transaction as ze}from"@mysten/sui/transactions";var U="0xffc7f420b481ed7a012b42e125fd7e5716b5673759cf4629e5fcfebce970a72d",hr=BigInt("1000000000000"),yr=BigInt("10000"),X="0x0ef0f805710cf53c10f29c4f73e1144a662747e1839689a846e2520cae122adc",w=`${X}::limit_order`,$=`${X}::dca_order`,Cr=`${X}::config`,Tr=BigInt("18446744073709551615"),f=`${L.LO_DCA}/api`;async function ue({accountAddress:o,payCoinType:e,targetCoinType:t,payCoinAmount:r,rate:i,slippage:s,expireTs:n,devInspect:a}){let c=new ze,p=c.add(Xe({type:e,balance:r,useGasCoin:!a}));return c.moveCall({target:`${w}::place_limit_order`,arguments:[c.object(U),p,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.object.clock()],typeArguments:[e,t]}),c.setSenderIfNotSet(o),c}import{Transaction as Ge}from"@mysten/sui/transactions";async function le({orderId:o,payCoinType:e,targetCoinType:t}){let r=new Ge;return r.moveCall({target:`${w}::cancel_limit_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}import{Transaction as He}from"@mysten/sui/transactions";async function me({orderId:o,payCoinType:e,targetCoinType:t}){let r=new He;return r.moveCall({target:`${w}::claim_expired_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}function O(o){let e="";return Object.entries(o).forEach(([t,r])=>{if(Array.isArray(r))for(let i of r)e+=e?`&${t}=${i}`:`${t}=${i}`;else r!==void 0&&(e+=e?`&${t}=${r}`:`${t}=${r}`)}),e}async function de({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open limit orders");return await n.json()}async function ge({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["CLOSED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch closed limit orders");return await n.json()}import{coinWithBalance as Ye,Transaction as Ze}from"@mysten/sui/transactions";async function fe({payCoinType:o,targetCoinType:e,payCoinAmountEach:t,numOrders:r,interval:i,slippage:s,minRate:n,maxRate:a}){let c=new Ze,p=[];for(let I=0;I<r;I++){let Te=Ye({type:o,balance:t});p.push(Te)}let d=c.makeMoveVec({elements:p});return c.moveCall({target:`${$}::place_dca_order`,arguments:[c.object(U),d,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.pure.u64(a),c.object.clock()],typeArguments:[o,e]}),c}import{Transaction as Je}from"@mysten/sui/transactions";async function Oe({orderId:o,payCoinType:e,targetCoinType:t}){let r=new Je;return r.moveCall({target:`${$}::cancel_dca_order`,arguments:[r.object(o),r.object.clock()],typeArguments:[e,t]}),r}async function he({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/dca-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open dca orders");return await n.json()}async function ye({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["SUCCESS"],offset:e,limit:t,orderType:"DCA",tokenPair:r}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch closed dca orders");return await n.json()}async function Ce({owner:o,orderId:e,offset:t=0,limit:r=10}){let s=O({owner:o,orderId:e,statuses:["SUCCESS"],offset:t,limit:r,orderType:"DCA"}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch dca order executions");return await n.json()}var Tn={getTokenPrice:V,getTokenPrices:W,getSuiPrice:pe,placeLimitOrder:ue,getOpenLimitOrders:de,cancelLimitOrder:le,claimExpiredLimitOrder:me,getClosedLimitOrders:ge,placeDcaOrder:fe,getOpenDcaOrders:he,cancelDcaOrder:Oe,getClosedDcaOrders:ye,getDcaOrderExecutions:Ce,MetaAg:R};export{z as EProvider,R as MetaAg,Oe as cancelDcaOrder,le as cancelLimitOrder,me as claimExpiredLimitOrder,Tn as default,ye as getClosedDcaOrders,ge as getClosedLimitOrders,Ce as getDcaOrderExecutions,he as getOpenDcaOrders,de as getOpenLimitOrders,pe as getSuiPrice,V as getTokenPrice,W as getTokenPrices,D as isAggregatorProvider,G as isSwapAPIProvider,fe as placeDcaOrder,ue as placeLimitOrder};
|
|
1
|
+
import{a as h,b as u,c as y,d as P,e as z,f as D,g as G,i as H,j as m,k as F,l as Y,m as Z,n as v,o as J}from"./chunk-CYI4MM5C.mjs";import{SuiGrpcClient as Re}from"@mysten/sui/grpc";import{getJsonRpcFullnodeUrl as Le}from"@mysten/sui/jsonRpc";import{coinWithBalance as Be,Transaction as Ue}from"@mysten/sui/transactions";import{fromBase64 as $e,normalizeStructTag as ae,toBase64 as Fe}from"@mysten/sui/utils";var ee="0x0000000000000000000000000000000000000000000000000000000000000000";import{normalizeSuiAddress as Pe,parseStructTag as it}from"@mysten/sui/utils";var be=["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000003","0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000005","0x0000000000000000000000000000000000000000000000000000000000000006","0x0000000000000000000000000000000000000000000000000000000000000007","0x0000000000000000000000000000000000000000000000000000000000000008","0x0000000000000000000000000000000000000000000000000000000000000009","0x0000000000000000000000000000000000000000000000000000000000000403","0x000000000000000000000000000000000000000000000000000000000000000c"],S=o=>{let e=Pe(o);return be.includes(e)};import{normalizeSuiAddress as N}from"@mysten/sui/utils";var Q=class{async getObject(e){let[t,r]=await Promise.all([this.get("OwnedObject",e),this.get("SharedOrImmutableObject",e)]);return t??r??null}async getObjects(e){return Promise.all(e.map(t=>this.getObject(t)))}async addObject(e){return e.owner?await this.set("OwnedObject",e.objectId,e):await this.set("SharedOrImmutableObject",e.objectId,e),e}async addObjects(e){await Promise.all(e.map(async t=>this.addObject(t)))}async deleteObject(e){await Promise.all([this.delete("OwnedObject",e),this.delete("SharedOrImmutableObject",e)])}async deleteObjects(e){await Promise.all(e.map(t=>this.deleteObject(t)))}async getMoveFunctionDefinition(e){let t=`${N(e.package)}::${e.module}::${e.function}`;return this.get("MoveFunction",t)}async addMoveFunctionDefinition(e){let t=N(e.package),r=`${t}::${e.module}::${e.function}`,i={...e,package:t};return await this.set("MoveFunction",r,i),i}async deleteMoveFunctionDefinition(e){let t=`${N(e.package)}::${e.module}::${e.function}`;await this.delete("MoveFunction",t)}async getCustom(e){return this.get("Custom",e)}async setCustom(e,t){return this.set("Custom",e,t)}async deleteCustom(e){return this.delete("Custom",e)}},C,q=class extends Q{constructor(){super(...arguments);y(this,C,{OwnedObject:new Map,SharedOrImmutableObject:new Map,MoveFunction:new Map,Custom:new Map})}async get(t,r){return u(this,C)[t].get(r)??null}async set(t,r,i){u(this,C)[t].set(r,i)}async delete(t,r){u(this,C)[t].delete(r)}async clear(t){if(t)u(this,C)[t].clear();else for(let r of Object.values(u(this,C)))r.clear()}};C=new WeakMap;var E,l,A,M=class{constructor({cache:e=new q,onEffects:t,client:r}){y(this,E);y(this,l);y(this,A);P(this,E,r),P(this,l,e),P(this,A,t)}async applyCache(e,t){let r=(await u(this,l).getObjects(t)).filter(n=>n!==null),i=new Map(r.map(n=>[n.objectId,n])),s=[];for(let n of e.inputs){if(!n.UnresolvedObject)continue;let a=i.get(n.UnresolvedObject.objectId);if(!a){s.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 s}async resolveObjects(e,t){let r=await this.applyCache(e,t);if(r.length===0)return[];let i=[...new Set(r)],s=await u(this,E).core.getObjects({objectIds:i}),n=[];for(let a of s.objects){if(a instanceof Error)continue;let c=a.owner,p=c.$kind==="Shared"?c.Shared.initialSharedVersion:null,d=c.$kind==="AddressOwner"?c.AddressOwner:c.$kind==="ObjectOwner"?c.ObjectOwner:null,I={objectId:a.objectId,version:a.version,digest:a.digest,initialSharedVersion:p,owner:d};n.push(I)}return await u(this,l).addObjects(n),await this.applyCache(e,r)}asPlugin(){return async(e,t,r)=>{let i=e.inputs.filter(s=>s.UnresolvedObject).map(s=>s.UnresolvedObject.objectId);await this.resolveObjects(e,i),await Promise.all(e.commands.map(async s=>{if(s.MoveCall){let n=await this.getMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function});n&&(s.MoveCall._argumentTypes=n.parameters)}})),await r(),await Promise.all(e.commands.map(async s=>{s.MoveCall?._argumentTypes&&await u(this,l).addMoveFunctionDefinition({package:s.MoveCall.package,module:s.MoveCall.module,function:s.MoveCall.function,parameters:s.MoveCall._argumentTypes})}))}}async clear(){await u(this,l).clear()}async getMoveFunctionDefinition(e){return u(this,l).getMoveFunctionDefinition(e)}async getObjects(e){return u(this,l).getObjects(e)}async deleteObjects(e){return u(this,l).deleteObjects(e)}async clearOwnedObjects(){await u(this,l).clear("OwnedObject")}async clearCustom(){await u(this,l).clear("Custom")}async getCustom(e){return u(this,l).getCustom(e)}async setCustom(e,t){return u(this,l).setCustom(e,t)}async deleteCustom(e){return u(this,l).deleteCustom(e)}async applyEffects(e){var n;if(!e.V2)throw new Error(`Unsupported transaction effects version ${e.$kind}`);let{lamportVersion:t,changedObjects:r}=e.V2,i=[],s=[];r.forEach(([a,c])=>{if(c.outputState.NotExist)i.push(a);else if(c.outputState.ObjectWrite){let[p,d]=c.outputState.ObjectWrite;s.push({objectId:a,digest:p,version:t,owner:d.AddressOwner??d.ObjectOwner??null,initialSharedVersion:d.Shared?.initialSharedVersion??null})}}),await Promise.all([u(this,l).addObjects(s),u(this,l).deleteObjects(i),(n=u(this,A))==null?void 0:n.call(this,e)])}};E=new WeakMap,l=new WeakMap,A=new WeakMap;var T,_,x=class{constructor(e){this.client=e;y(this,T);y(this,_,new WeakSet);h(this,"simulateTransaction",async e=>{e.transactionBlock.setSenderIfNotSet(e.sender),u(this,_).has(e.transactionBlock)||(e.transactionBlock.addBuildPlugin(u(this,T).asPlugin()),u(this,_).add(e.transactionBlock));try{return await this.client.core.simulateTransaction({transaction:e.transactionBlock,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}})}catch(t){throw await u(this,T).clear(),t}finally{await u(this,T).clearOwnedObjects()}});P(this,T,new M({client:this.client}))}};T=new WeakMap,_=new WeakMap;import{TransactionCommands as ve,Transaction as se,TransactionDataBuilder as Se}from"@mysten/sui/transactions";import{fromBase64 as Ee,normalizeStructTag as Ae,normalizeSuiAddress as te,toBase64 as xe}from"@mysten/sui/utils";import{v4 as _e}from"uuid";var b="0x2::sui::SUI",k="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie="https://web3.okx.com",re="/api/v6/dex/aggregator/swap",De="784",ne=Ae(b),j=class{constructor(e,t,r){this.options=e;this.metaOptions=t;this.client=r;h(this,"kind","okx")}async quote({amountIn:e,coinTypeIn:t,coinTypeOut:r,signer:i}){if(!i||S(i))return null;let s={chainIndex:De,amount:e,fromTokenAddress:t===ne?b:t,toTokenAddress:r===ne?b:r,slippagePercent:(this.metaOptions.slippageBps/100).toString(),userWalletAddress:i},n="?"+new URLSearchParams(s).toString(),a=`${this.options.api??Ie}${re}${n}`,p=await(await fetch(a,{headers:await ke(this.options,"GET",re,n)})).json();return m.assert(p.code==="0"&&p.data.length>0,"No quote found",1005,{provider:this.kind}),{id:_e(),provider:this.kind,coinTypeIn:t,coinTypeOut:r,amountIn:e,amountOut:p.data[0].routerResult.toTokenAmount,rawAmountOut:p.data[0].routerResult.toTokenAmount,quote:p.data[0]}}async fastSwap(e){let{quote:t,signer:r,signTransaction:i}=e;F(t,"okx");let{tx:s,coin:n}=ie({quote:t,signer:r});s.add(v(t,n,this.metaOptions.slippageBps,this.metaOptions.tipBps,this.metaOptions.partner,this.metaOptions.partnerCommissionBps)),s.transferObjects([n],r);let a=await s.build({client:this.client}),{bytes:c,signature:p}=await i(xe(a)),d=await this.client.core.executeTransaction({transaction:Ee(c),signatures:[p]});if(!d.Transaction?.digest)throw new m("OKX transaction failed or returned no digest",1008,{error:d.FailedTransaction?.digest??"no digest"});return d.Transaction.digest}};async function Me(o,e){let t=new TextEncoder,r=s=>{if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let n="";for(let a=0;a<s.byteLength;a++)n+=String.fromCharCode(s[a]);if(typeof btoa<"u")return btoa(n);throw new m("Base64 encoder not available in this environment")};if(typeof globalThis<"u"&&globalThis.crypto?.subtle){let s=await globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await globalThis.crypto.subtle.sign("HMAC",s,t.encode(o));return r(new Uint8Array(n))}let{createHmac:i}=await import("crypto");return i("sha256",e).update(o).digest("base64")}async function ke(o,e,t,r=""){let{apiKey:i,secretKey:s,apiPassphrase:n,projectId:a}=o;if(!i||!s||!n||!a)throw new m("Missing required environment variables");let c=new Date().toISOString(),p=c+e+t+r;return{"Content-Type":"application/json","OK-ACCESS-KEY":i,"OK-ACCESS-SIGN":await Me(p,s),"OK-ACCESS-TIMESTAMP":c,"OK-ACCESS-PASSPHRASE":n,"OK-ACCESS-PROJECT":a}}var je=(o,e)=>{let t=Se.restore(o.getData()),r=t.commands.findIndex(n=>n.$kind==="MoveCall"&&te(n.MoveCall.package)===te(e)&&n.MoveCall.module==="router"&&n.MoveCall.function==="finalize"),i=t.commands[r];return m.assert(i.MoveCall,"OKX: Finalize command not found",1100,{packageId:e}),t.replaceCommand(r,ve.MoveCall({package:e,module:"router",function:"finalize_without_transfer",typeArguments:i.MoveCall.typeArguments,arguments:[i.MoveCall.arguments[0],i.MoveCall.arguments[5],i.MoveCall.arguments[6]]})),{tx:se.from(t.build()),coin:{NestedResult:[r,0]}}},ie=o=>{let{quote:e,signer:t}=o;F(e,"okx");let r=se.from(e.quote.tx.data);r.setSenderIfNotSet(t);let{tx:i,coin:s}=je(r,e.quote.tx.to);return{tx:i,coin:s}},oe=async(o,e,t,r)=>{let{tx:i,coin:s}=ie({quote:o,signer:o.quote.tx.from});i.add(v(o,s,1e4,r.tipBps,r.partner,r.partnerCommissionBps)),i.transferObjects([s],o.quote.tx.from);let n=await Y(i,e,t);return{id:o.id,provider:o.provider,...n}};var Ne=()=>new Re({baseUrl:Le("mainnet"),network:"mainnet"}),Qe="https://hermes.pyth.network",qe={bluefin7k:{},flowx:{},cetus:{}},R=class{constructor(e){h(this,"client");h(this,"providers",{});h(this,"inspector");h(this,"options");this.client=e?.client??Ne(),this.options={providers:{...qe,...e?.providers},slippageBps:e?.slippageBps??100,client:this.client,hermesApi:e?.hermesApi??Qe,partner:e?.partner??ee,partnerCommissionBps:e?.partnerCommissionBps??0,tipBps:e?.tipBps??0},this.inspector=new x(this.client)}async _getProvider(e){let t=this.providers[e];if(t)return t;let r=this.options.providers[e];switch(m.assert(!!r,`Provider not found: ${e}`,1002,{provider:e}),e){case"bluefin7k":let{Bluefin7kProvider:i}=await import("./bluefin7k-63A5CV3A.mjs").catch(K("bluefin7k"));this.providers.bluefin7k=new i(r,this.options,this.client);break;case"flowx":let{FlowxProvider:s}=await import("./flowx-FTPJ3RYF.mjs").catch(K("flowx"));this.providers.flowx=new s(r,this.client);break;case"cetus":let{CetusProvider:n}=await import("./cetus-HOKHMQSS.mjs").catch(K("cetus"));this.providers.cetus=new n(r,this.options,this.client);break;case"okx":this.providers.okx=new j(r,this.options,this.client);break;default:throw new m(`Provider not supported: ${e}`,1003,{provider:e})}return this.providers[e]}async _simulate(e,t,r){try{if(D(e))return await Z(e,t,r,this.inspector,this.options);if(t.provider==="okx")return await oe(t,this.inspector,r,this.options);throw new m(`Provider not supported: ${e.kind}`,1003,{provider:e.kind})}catch(i){console.warn(i,{provider:e.kind,quote:t.id});return}}async _quote(e,t){return await J(async()=>{let i=await e.quote(t);if(!i)return null;let{expectedAmount:s}=H(i.rawAmountOut,0,this.options.partnerCommissionBps,this.options.tipBps);return i.amountOut=s,i},t.timeout??2e3,`quote for ${e.kind} provider from ${t.coinTypeIn} to ${t.coinTypeOut}`)}async _fastSwap({quote:e,signer:t,useGasCoin:r,signTransaction:i},s){let n=new Ue,a=await this.swap({quote:e,signer:t,tx:n,coinIn:Be({type:e.coinTypeIn,balance:BigInt(e.amountIn),useGasCoin:r})});n.transferObjects([a],t),n.setSenderIfNotSet(t);let c=await n.build({client:this.client}),{signature:p,bytes:d}=await i(Fe(c));return this.client.core.executeTransaction({transaction:$e(d),signatures:[p],signal:s?.signal,include:s?.include})}async quote(e,t){let r={...e,coinTypeIn:ae(e.coinTypeIn),coinTypeOut:ae(e.coinTypeOut)},s=(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(t){let n=s.map(async a=>{let c=await this._getProvider(a.provider),p=await this._simulate(c,a,t);a.simulatedAmountOut=p?.simulatedAmountOut,a.gasUsed=p?.gasUsed,t?.onSimulated?.({...a})});t.onSimulated||await Promise.all(n)}return s}async swap(e,t){let r=await this._getProvider(e.quote.provider);m.assert(!!r,`Provider not found: ${e.quote.provider}`,1002,{provider:e.quote.provider}),m.assert(D(r),`Provider does not support swap: ${r.kind}, use fastSwap instead`,1007,{provider:r.kind}),m.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let i=await r.swap(e);return e.tx.add(v(e.quote,i,t??this.options.slippageBps??100,this.options.tipBps,this.options.partner,this.options.partnerCommissionBps)),e.tx.setSenderIfNotSet(e.signer),i}async fastSwap(e,t){m.assert(e.signer&&!S(e.signer),"Invalid signer address",1006,{signer:e.signer});let r=await this._getProvider(e.quote.provider);if(D(r))return this._fastSwap(e,t);if(G(r))return this.client.core.waitForTransaction({digest:await r.fastSwap(e),signal:t?.signal,include:t?.include});throw new m(`Provider not supported: ${r.kind}`,1003,{provider:r.kind})}updateMetaAgOptions(e){if(Object.keys(e).length===0)return;this.options.slippageBps=e.slippageBps??this.options.slippageBps,this.options.partner=e.partner??this.options.partner,this.options.partnerCommissionBps=e.partnerCommissionBps??this.options.partnerCommissionBps,this.options.tipBps=e.tipBps??this.options.tipBps;let t=!!(e.client&&e.client!==this.client),r=!!(e.hermesApi&&e.hermesApi!==this.options.hermesApi);t&&(this.client=e.client,this.options.client=this.client,this.inspector=new x(this.client)),r&&(this.options.hermesApi=e.hermesApi),(t||r)&&(this.providers={});for(let[i,s]of Object.entries(e.providers||{}))this.options.providers[i]={...s,...this.options.providers[i]},delete this.providers[i]}},K=o=>e=>{let t={cetus:"@cetusprotocol/aggregator-sdk",flowx:"@flowx-finance/sdk",bluefin7k:"@bluefin-exchange/bluefin7k-aggregator-sdk",okx:""};throw console.warn(`Please install ${t[o]} to use ${o} provider`),e};async function g(o,e){let t=new Headers(e?.headers),r={...e,headers:t};return fetch(o,r)}var L={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(o){return o===b?k:o}var Ke=(o,e)=>{let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t},ce=500,Ve=100;function We(){return Math.floor(Date.now()/1e3).toString()}async function V(o){try{let e=B(o);return(await W([e]))[e]||0}catch{return 0}}async function W(o){try{if(o.length===0)return{};let e=o.slice(0,ce).map(B),t=Ke(e,Ve),r=We(),s=(await Promise.all(t.map(async a=>{let c={timestamp:r,token_ids:a},p=await g(`${L.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 e.reduce((a,c)=>(a[c]=s[c]||0,a),{})}catch{return o.slice(0,ce).reduce((t,r)=>(t[B(r)]=0,t),{})}}async function pe(){return await V(k)}import{coinWithBalance as Xe,Transaction as ze}from"@mysten/sui/transactions";var U="0xffc7f420b481ed7a012b42e125fd7e5716b5673759cf4629e5fcfebce970a72d",hr=BigInt("1000000000000"),yr=BigInt("10000"),X="0x0ef0f805710cf53c10f29c4f73e1144a662747e1839689a846e2520cae122adc",w=`${X}::limit_order`,$=`${X}::dca_order`,Cr=`${X}::config`,Tr=BigInt("18446744073709551615"),f=`${L.LO_DCA}/api`;async function ue({accountAddress:o,payCoinType:e,targetCoinType:t,payCoinAmount:r,rate:i,slippage:s,expireTs:n,devInspect:a}){let c=new ze,p=c.add(Xe({type:e,balance:r,useGasCoin:!a}));return c.moveCall({target:`${w}::place_limit_order`,arguments:[c.object(U),p,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.object.clock()],typeArguments:[e,t]}),c.setSenderIfNotSet(o),c}import{Transaction as Ge}from"@mysten/sui/transactions";async function le({orderId:o,payCoinType:e,targetCoinType:t}){let r=new Ge;return r.moveCall({target:`${w}::cancel_limit_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}import{Transaction as He}from"@mysten/sui/transactions";async function me({orderId:o,payCoinType:e,targetCoinType:t}){let r=new He;return r.moveCall({target:`${w}::claim_expired_order`,typeArguments:[e,t],arguments:[r.object(o),r.object.clock()]}),r}function O(o){let e="";return Object.entries(o).forEach(([t,r])=>{if(Array.isArray(r))for(let i of r)e+=e?`&${t}=${i}`:`${t}=${i}`;else r!==void 0&&(e+=e?`&${t}=${r}`:`${t}=${r}`)}),e}async function de({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open limit orders");return await n.json()}async function ge({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["CLOSED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/limit-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch closed limit orders");return await n.json()}import{coinWithBalance as Ye,Transaction as Ze}from"@mysten/sui/transactions";async function fe({payCoinType:o,targetCoinType:e,payCoinAmountEach:t,numOrders:r,interval:i,slippage:s,minRate:n,maxRate:a}){let c=new Ze,p=[];for(let I=0;I<r;I++){let Te=Ye({type:o,balance:t});p.push(Te)}let d=c.makeMoveVec({elements:p});return c.moveCall({target:`${$}::place_dca_order`,arguments:[c.object(U),d,c.pure.u64(i),c.pure.u64(s),c.pure.u64(n),c.pure.u64(a),c.object.clock()],typeArguments:[o,e]}),c}import{Transaction as Je}from"@mysten/sui/transactions";async function Oe({orderId:o,payCoinType:e,targetCoinType:t}){let r=new Je;return r.moveCall({target:`${$}::cancel_dca_order`,arguments:[r.object(o),r.object.clock()],typeArguments:[e,t]}),r}async function he({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["ACTIVE","EXPIRED"],offset:e,limit:t,tokenPair:r}),n=await g(`${f}/dca-orders?${s}`);if(!n.ok)throw new Error("Failed to fetch open dca orders");return await n.json()}async function ye({owner:o,offset:e=0,limit:t=10,tokenPair:r}){let s=O({owner:o,statuses:["SUCCESS"],offset:e,limit:t,orderType:"DCA",tokenPair:r}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch closed dca orders");return await n.json()}async function Ce({owner:o,orderId:e,offset:t=0,limit:r=10}){let s=O({owner:o,orderId:e,statuses:["SUCCESS"],offset:t,limit:r,orderType:"DCA"}),n=await g(`${f}/order-executions?${s}`);if(!n.ok)throw new Error("Failed to fetch dca order executions");return await n.json()}var Tn={getTokenPrice:V,getTokenPrices:W,getSuiPrice:pe,placeLimitOrder:ue,getOpenLimitOrders:de,cancelLimitOrder:le,claimExpiredLimitOrder:me,getClosedLimitOrders:ge,placeDcaOrder:fe,getOpenDcaOrders:he,cancelDcaOrder:Oe,getClosedDcaOrders:ye,getDcaOrderExecutions:Ce,MetaAg:R};export{z as EProvider,R as MetaAg,Oe as cancelDcaOrder,le as cancelLimitOrder,me as claimExpiredLimitOrder,Tn as default,ye as getClosedDcaOrders,ge as getClosedLimitOrders,Ce as getDcaOrderExecutions,he as getOpenDcaOrders,de as getOpenLimitOrders,pe as getSuiPrice,V as getTokenPrice,W as getTokenPrices,D as isAggregatorProvider,G as isSwapAPIProvider,fe as placeDcaOrder,ue as placeLimitOrder};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
package/dist/flowx-533PLKYB.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as o,h as i,j as n,k as s}from"./chunk-CYI4MM5C.mjs";import{AggregatorQuoter as p,Commission as m,CommissionType as c,TradeBuilder as l}from"@flowx-finance/sdk";import{v4 as d}from"uuid";var u=class{constructor(t,e){this.options=t;this.client=e;o(this,"kind","flowx");o(this,"quoter");this.quoter=new p("mainnet",t.apiKey)}async quote(t){let e=await this.quoter.getRoutes({amountIn:t.amountIn,tokenIn:t.coinTypeIn,tokenOut:t.coinTypeOut,includeSources:this.options.sources,excludePools:this.options.excludePools,excludeSources:this.options.excludeSources,maxHops:this.options.maxHops,splitDistributionPercent:this.options.splitDistributionPercent});return{id:d(),provider:"flowx",quote:e,amountIn:e.amountIn?.toString()??"0",rawAmountOut:e.amountOut?.toString()??"0",amountOut:e.amountOut?.toString()??"0",coinTypeIn:t.coinTypeIn,coinTypeOut:t.coinTypeOut}}async swap(t){s(t.quote,"flowx");let e=new l("mainnet",t.quote.quote.routes);e.sender(t.signer),e.slippage(1e4*100),e.commission(new m(i,t.quote.quote.coinOut,c.PERCENTAGE,0,!0));let a=e.build().swap,r=await a({tx:t.tx,client:this.client,coinIn:t.coinIn});return n.assert(!!r,"FlowX swap returned no coin out",1004,{quote:t.quote,expectedProvider:"flowx"}),r}};export{u as FlowxProvider};
|
|
2
|
-
//# sourceMappingURL=flowx-533PLKYB.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/features/metaAg/providers/flowx.ts"],"sourcesContent":["import {\n AggregatorQuoter,\n Commission,\n CommissionType,\n TradeBuilder,\n} from \"@flowx-finance/sdk\";\nimport { ClientWithCoreApi } from \"@mysten/sui/client\";\nimport { TransactionObjectArgument } from \"@mysten/sui/transactions\";\nimport { v4 } from \"uuid\";\nimport { _7K_PARTNER_ADDRESS } from \"../../../constants/_7k\";\nimport {\n AggregatorProvider,\n EProvider,\n FlowxProviderOptions,\n MetaQuote,\n MetaQuoteOptions,\n MetaSwapOptions,\n QuoteProvider,\n} from \"../../../types/metaAg\";\nimport { assertQuoteProvider } from \"../common\";\nimport { MetaAgError, MetaAgErrorCode } from \"../error\";\n\nexport class FlowxProvider implements QuoteProvider, AggregatorProvider {\n readonly kind = EProvider.FLOWX;\n private quoter: AggregatorQuoter;\n constructor(\n private readonly options: FlowxProviderOptions,\n private readonly client: ClientWithCoreApi,\n ) {\n this.quoter = new AggregatorQuoter(\"mainnet\", options.apiKey);\n }\n\n async quote(quoteOptions: MetaQuoteOptions): Promise<MetaQuote> {\n const quote = await this.quoter.getRoutes({\n amountIn: quoteOptions.amountIn,\n tokenIn: quoteOptions.coinTypeIn,\n tokenOut: quoteOptions.coinTypeOut,\n includeSources: this.options.sources,\n excludePools: this.options.excludePools,\n excludeSources: this.options.excludeSources,\n maxHops: this.options.maxHops,\n splitDistributionPercent: this.options.splitDistributionPercent,\n });\n return {\n id: v4(),\n provider: EProvider.FLOWX,\n quote: quote,\n amountIn: quote.amountIn?.toString() ?? \"0\",\n rawAmountOut: quote.amountOut?.toString() ?? \"0\",\n amountOut: quote.amountOut?.toString() ?? \"0\",\n coinTypeIn: quoteOptions.coinTypeIn,\n coinTypeOut: quoteOptions.coinTypeOut,\n };\n }\n\n async swap(options: MetaSwapOptions): Promise<TransactionObjectArgument> {\n assertQuoteProvider(options.quote, EProvider.FLOWX);\n const builder = new TradeBuilder(\"mainnet\", options.quote.quote.routes);\n builder.sender(options.signer);\n builder.slippage(10000 * 100);\n builder.commission(\n new Commission(\n _7K_PARTNER_ADDRESS,\n options.quote.quote.coinOut,\n CommissionType.PERCENTAGE,\n 0,\n true,\n ),\n );\n const swap = builder.build().swap;\n type SwapClient = Parameters<typeof swap>[0][\"client\"];\n const res = await swap({\n tx: options.tx,\n // FlowX 2.0.3 types `client` as `SuiGrpcClient`, but at runtime it only\n // calls through `core.*`. Cast at this single boundary so the SDK\n // public API stays transport-agnostic (`ClientWithCoreApi`).\n client: this.client as unknown as SwapClient,\n coinIn: options.coinIn,\n });\n MetaAgError.assert(\n !!res,\n \"FlowX swap returned no coin out\",\n MetaAgErrorCode.INVALID_QUOTE,\n { quote: options.quote, expectedProvider: EProvider.FLOWX },\n );\n return res;\n }\n}\n"],"mappings":"8DAAA,OACE,oBAAAA,EACA,cAAAC,EACA,kBAAAC,EACA,gBAAAC,MACK,qBAGP,OAAS,MAAAC,MAAU,OAcZ,IAAMC,EAAN,KAAiE,CAGtE,YACmBC,EACAC,EACjB,CAFiB,aAAAD,EACA,YAAAC,EAJnBC,EAAA,KAAS,gBACTA,EAAA,KAAQ,UAKN,KAAK,OAAS,IAAIC,EAAiB,UAAWH,EAAQ,MAAM,CAC9D,CAEA,MAAM,MAAMI,EAAoD,CAC9D,IAAMC,EAAQ,MAAM,KAAK,OAAO,UAAU,CACxC,SAAUD,EAAa,SACvB,QAASA,EAAa,WACtB,SAAUA,EAAa,YACvB,eAAgB,KAAK,QAAQ,QAC7B,aAAc,KAAK,QAAQ,aAC3B,eAAgB,KAAK,QAAQ,eAC7B,QAAS,KAAK,QAAQ,QACtB,yBAA0B,KAAK,QAAQ,wBACzC,CAAC,EACD,MAAO,CACL,GAAIE,EAAG,EACP,iBACA,MAAOD,EACP,SAAUA,EAAM,UAAU,SAAS,GAAK,IACxC,aAAcA,EAAM,WAAW,SAAS,GAAK,IAC7C,UAAWA,EAAM,WAAW,SAAS,GAAK,IAC1C,WAAYD,EAAa,WACzB,YAAaA,EAAa,WAC5B,CACF,CAEA,MAAM,KAAKJ,EAA8D,CACvEO,EAAoBP,EAAQ,aAAsB,EAClD,IAAMQ,EAAU,IAAIC,EAAa,UAAWT,EAAQ,MAAM,MAAM,MAAM,EACtEQ,EAAQ,OAAOR,EAAQ,MAAM,EAC7BQ,EAAQ,SAAS,IAAQ,GAAG,EAC5BA,EAAQ,WACN,IAAIE,EACFC,EACAX,EAAQ,MAAM,MAAM,QACpBY,EAAe,WACf,EACA,EACF,CACF,EACA,IAAMC,EAAOL,EAAQ,MAAM,EAAE,KAEvBM,EAAM,MAAMD,EAAK,CACrB,GAAIb,EAAQ,GAIZ,OAAQ,KAAK,OACb,OAAQA,EAAQ,MAClB,CAAC,EACD,OAAAe,EAAY,OACV,CAAC,CAACD,EACF,uCAEA,CAAE,MAAOd,EAAQ,MAAO,wBAAkC,CAC5D,EACOc,CACT,CACF","names":["AggregatorQuoter","Commission","CommissionType","TradeBuilder","v4","FlowxProvider","options","client","__publicField","AggregatorQuoter","quoteOptions","quote","v4","assertQuoteProvider","builder","TradeBuilder","Commission","_7K_PARTNER_ADDRESS","CommissionType","swap","res","MetaAgError"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/otis/Documents/7k-ts-sdk/dist/flowx-SIZHC2DP.js","../src/features/metaAg/providers/flowx.ts"],"names":["FlowxProvider","options","client","__publicField","AggregatorQuoter","quoteOptions","quote","v4","assertQuoteProvider","builder","TradeBuilder","Commission","_7K_PARTNER_ADDRESS","CommissionType","swap","res","MetaAgError"],"mappings":"AAAA,uuBAA4D,yCCKrD,4BAGY,IAcNA,CAAAA,CAAN,KAAiE,CAGtE,WAAA,CACmBC,CAAAA,CACAC,CAAAA,CACjB,CAFiB,IAAA,CAAA,OAAA,CAAAD,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAC,CAAAA,CAJnBC,gCAAAA,IAAA,CAAS,MAAA,CAAA,OAAA,CAAA,CACTA,gCAAAA,IAAA,CAAQ,QAAA,CAAA,CAKN,IAAA,CAAK,MAAA,CAAS,IAAIC,0BAAAA,CAAiB,SAAA,CAAWH,CAAAA,CAAQ,MAAM,CAC9D,CAEA,MAAM,KAAA,CAAMI,CAAAA,CAAoD,CAC9D,IAAMC,CAAAA,CAAQ,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,CAAU,CACxC,QAAA,CAAUD,CAAAA,CAAa,QAAA,CACvB,OAAA,CAASA,CAAAA,CAAa,UAAA,CACtB,QAAA,CAAUA,CAAAA,CAAa,WAAA,CACvB,cAAA,CAAgB,IAAA,CAAK,OAAA,CAAQ,OAAA,CAC7B,YAAA,CAAc,IAAA,CAAK,OAAA,CAAQ,YAAA,CAC3B,cAAA,CAAgB,IAAA,CAAK,OAAA,CAAQ,cAAA,CAC7B,OAAA,CAAS,IAAA,CAAK,OAAA,CAAQ,OAAA,CACtB,wBAAA,CAA0B,IAAA,CAAK,OAAA,CAAQ,wBACzC,CAAC,CAAA,CACD,MAAO,CACL,EAAA,CAAIE,sBAAAA,CAAG,CACP,QAAA,CAAA,OAAA,CACA,KAAA,CAAOD,CAAAA,CACP,QAAA,kCAAUA,CAAAA,mBAAM,QAAA,6BAAU,QAAA,mBAAS,GAAA,SAAK,KAAA,CACxC,YAAA,kCAAcA,CAAAA,qBAAM,SAAA,6BAAW,QAAA,mBAAS,GAAA,SAAK,KAAA,CAC7C,SAAA,kCAAWA,CAAAA,qBAAM,SAAA,6BAAW,QAAA,mBAAS,GAAA,SAAK,KAAA,CAC1C,UAAA,CAAYD,CAAAA,CAAa,UAAA,CACzB,WAAA,CAAaA,CAAAA,CAAa,WAC5B,CACF,CAEA,MAAM,IAAA,CAAKJ,CAAAA,CAA8D,CACvEO,gCAAAA,CAAoBP,CAAQ,KAAA,CAAA,OAAsB,CAAA,CAClD,IAAMQ,CAAAA,CAAU,IAAIC,sBAAAA,CAAa,SAAA,CAAWT,CAAAA,CAAQ,KAAA,CAAM,KAAA,CAAM,MAAM,CAAA,CACtEQ,CAAAA,CAAQ,MAAA,CAAOR,CAAAA,CAAQ,MAAM,CAAA,CAC7BQ,CAAAA,CAAQ,QAAA,CAAS,GAAA,CAAQ,GAAG,CAAA,CAC5BA,CAAAA,CAAQ,UAAA,CACN,IAAIE,oBAAAA,CACFC,kBAAAA,CACAX,CAAAA,CAAQ,KAAA,CAAM,KAAA,CAAM,OAAA,CACpBY,mBAAAA,CAAe,UAAA,CACf,CAAA,CACA,CAAA,CACF,CACF,CAAA,CACA,IAAMC,CAAAA,CAAOL,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAE,IAAA,CAEvBM,CAAAA,CAAM,MAAMD,CAAAA,CAAK,CACrB,EAAA,CAAIb,CAAAA,CAAQ,EAAA,CAIZ,MAAA,CAAQ,IAAA,CAAK,MAAA,CACb,MAAA,CAAQA,CAAAA,CAAQ,MAClB,CAAC,CAAA,CACD,OAAAe,kBAAAA,CAAY,MAAA,CACV,CAAC,CAACD,CAAAA,CACF,iCAAA,CAAA,IAAA,CAEA,CAAE,KAAA,CAAOd,CAAAA,CAAQ,KAAA,CAAO,gBAAA,CAAA,OAAkC,CAC5D,CAAA,CACOc,CACT,CACF,CAAA,CAAA,0BAAA","file":"/Users/otis/Documents/7k-ts-sdk/dist/flowx-SIZHC2DP.js","sourcesContent":[null,"import {\n AggregatorQuoter,\n Commission,\n CommissionType,\n TradeBuilder,\n} from \"@flowx-finance/sdk\";\nimport { ClientWithCoreApi } from \"@mysten/sui/client\";\nimport { TransactionObjectArgument } from \"@mysten/sui/transactions\";\nimport { v4 } from \"uuid\";\nimport { _7K_PARTNER_ADDRESS } from \"../../../constants/_7k\";\nimport {\n AggregatorProvider,\n EProvider,\n FlowxProviderOptions,\n MetaQuote,\n MetaQuoteOptions,\n MetaSwapOptions,\n QuoteProvider,\n} from \"../../../types/metaAg\";\nimport { assertQuoteProvider } from \"../common\";\nimport { MetaAgError, MetaAgErrorCode } from \"../error\";\n\nexport class FlowxProvider implements QuoteProvider, AggregatorProvider {\n readonly kind = EProvider.FLOWX;\n private quoter: AggregatorQuoter;\n constructor(\n private readonly options: FlowxProviderOptions,\n private readonly client: ClientWithCoreApi,\n ) {\n this.quoter = new AggregatorQuoter(\"mainnet\", options.apiKey);\n }\n\n async quote(quoteOptions: MetaQuoteOptions): Promise<MetaQuote> {\n const quote = await this.quoter.getRoutes({\n amountIn: quoteOptions.amountIn,\n tokenIn: quoteOptions.coinTypeIn,\n tokenOut: quoteOptions.coinTypeOut,\n includeSources: this.options.sources,\n excludePools: this.options.excludePools,\n excludeSources: this.options.excludeSources,\n maxHops: this.options.maxHops,\n splitDistributionPercent: this.options.splitDistributionPercent,\n });\n return {\n id: v4(),\n provider: EProvider.FLOWX,\n quote: quote,\n amountIn: quote.amountIn?.toString() ?? \"0\",\n rawAmountOut: quote.amountOut?.toString() ?? \"0\",\n amountOut: quote.amountOut?.toString() ?? \"0\",\n coinTypeIn: quoteOptions.coinTypeIn,\n coinTypeOut: quoteOptions.coinTypeOut,\n };\n }\n\n async swap(options: MetaSwapOptions): Promise<TransactionObjectArgument> {\n assertQuoteProvider(options.quote, EProvider.FLOWX);\n const builder = new TradeBuilder(\"mainnet\", options.quote.quote.routes);\n builder.sender(options.signer);\n builder.slippage(10000 * 100);\n builder.commission(\n new Commission(\n _7K_PARTNER_ADDRESS,\n options.quote.quote.coinOut,\n CommissionType.PERCENTAGE,\n 0,\n true,\n ),\n );\n const swap = builder.build().swap;\n type SwapClient = Parameters<typeof swap>[0][\"client\"];\n const res = await swap({\n tx: options.tx,\n // FlowX 2.0.3 types `client` as `SuiGrpcClient`, but at runtime it only\n // calls through `core.*`. Cast at this single boundary so the SDK\n // public API stays transport-agnostic (`ClientWithCoreApi`).\n client: this.client as unknown as SwapClient,\n coinIn: options.coinIn,\n });\n MetaAgError.assert(\n !!res,\n \"FlowX swap returned no coin out\",\n MetaAgErrorCode.INVALID_QUOTE,\n { quote: options.quote, expectedProvider: EProvider.FLOWX },\n );\n return res;\n }\n}\n"]}
|