@ickb/sdk 1000.0.43 → 1000.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,235 +1,20 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IckbController = void 0;
4
- const core_1 = require("@ckb-ccc/core");
5
- const utils_1 = require("@ickb/utils");
6
- const core_2 = require("@ickb/core");
7
- const dao_1 = require("@ickb/dao");
8
- const order_1 = require("@ickb/order");
9
- class IckbController {
10
- constructor(ickbUdtManager, logicManager, ownedOwnerManager, orderManager, daoManager) {
11
- this.ickbUdtManager = ickbUdtManager;
12
- this.logicManager = logicManager;
13
- this.ownedOwnerManager = ownedOwnerManager;
14
- this.orderManager = orderManager;
15
- this.daoManager = daoManager;
16
- }
17
- static fromDeps({ xudt, dao, ickbLogic, ownedOwner, order, }) {
18
- const daoManager = dao_1.DaoManager.fromDeps(dao);
19
- const { script: { codeHash, hashType }, cellDeps, } = xudt;
20
- const ickbXudt = {
21
- script: new core_1.ccc.Script(codeHash, hashType, [ickbLogic.script.hash(), "00000080"].join("")),
22
- cellDeps,
23
- };
24
- const ickbUdtManager = core_2.IckbUdtManager.fromDeps(ickbXudt, daoManager);
25
- return new IckbController(ickbUdtManager, core_2.LogicManager.fromDeps(ickbLogic, daoManager, ickbUdtManager), core_2.OwnedOwnerManager.fromDeps(ownedOwner, daoManager, ickbUdtManager), order_1.OrderManager.fromDeps(order, ickbUdtManager), daoManager);
26
- }
27
- // fee examples:
28
- // 100000n => 0.001%
29
- // 10000n => 0.01%
30
- // 1000n => 0.1%
31
- // 100n => 1%
32
- // 10n => 10%
33
- // 1n => 100%
34
- // less than 1n => 0%
35
- static previewConversion(conversion) {
36
- const { isCkb2Udt, amount, fee } = conversion;
37
- let rate = conversion.rate;
38
- rate = "dao" in rate ? (0, core_2.ickbExchangeRatio)(rate) : rate;
39
- if (fee > core_1.ccc.Zero) {
40
- const { ckbScale, udtScale } = rate;
41
- rate = {
42
- ckbScale,
43
- // Worst case scenario where fee applies to the full amount
44
- udtScale: udtScale + (isCkb2Udt ? 1n : -1n) * (udtScale / fee),
45
- };
46
- }
47
- const convertedAmount = amount > core_1.ccc.Zero ? (0, core_2.convert)(isCkb2Udt, amount, rate) : core_1.ccc.Zero;
48
- return { rate, convertedAmount };
49
- }
50
- async convert(options) {
51
- // Get user lock
52
- const { system, signer } = options;
53
- const lock = (await signer.getRecommendedAddressObj()).script;
54
- // Normalize rate
55
- const { rate } = IckbController.previewConversion({
56
- ...options.conversion,
57
- amount: core_1.ccc.Zero,
58
- });
59
- const { isCkb2Udt, amount, ckbMinMatchLog } = options.conversion;
60
- const info = order_1.Info.create(isCkb2Udt, rate, ckbMinMatchLog);
61
- // feeRate is a good approximation of the bot tx size matching the order
62
- const ckbMinFee = options.conversion.ckbMinFee ?? 10n * system.feeRate;
63
- const conversion = {
64
- isCkb2Udt,
65
- amount,
66
- rate,
67
- info,
68
- ckbMinFee,
69
- lock,
70
- };
71
- const N = isCkb2Udt
72
- ? Number(amount / system.ckbDepositCap)
73
- : system.depositPool.slice(0, 30).length;
74
- const cache = Array(N);
75
- const cachedAttempt = (n) => {
76
- n = N - n;
77
- return (cache[n] = cache[n] ?? this.attempt(n, conversion, options));
78
- };
79
- return cachedAttempt(await (0, utils_1.asyncBinarySearch)(N, async (n) => (await cachedAttempt(n)) !== undefined));
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
80
7
  }
81
- async attempt(n, conversion, options) {
82
- try {
83
- const { isCkb2Udt, rate, info, ckbMinFee, lock } = conversion;
84
- const { signer, userCells, system, filters } = options;
85
- const { feeRate, depositPool, ckbDepositCap, exchangeRatio } = system;
86
- const tx = utils_1.SmartTransaction.default();
87
- const maturities = [];
88
- let ckbFee = core_1.ccc.Zero;
89
- let amount = conversion.amount;
90
- // Core protocol
91
- if (n > 0) {
92
- if (isCkb2Udt) {
93
- amount -= ckbDepositCap * BigInt(n);
94
- if (amount < core_1.ccc.Zero) {
95
- // Too many Deposits respectfully to the amount
96
- return undefined;
97
- }
98
- this.logicManager.deposit(tx, n, ckbDepositCap, lock);
99
- }
100
- else {
101
- const myDeposits = depositPool.slice(0, n);
102
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
103
- amount -= myDeposits.slice(-1)[0].udtCumulative;
104
- if (amount < core_1.ccc.Zero) {
105
- // Too many Withdrawal Requests respectfully to the amount
106
- return undefined;
107
- }
108
- this.ownedOwnerManager.requestWithdrawal(tx, myDeposits, lock);
109
- maturities.push(...myDeposits.map((d) => d.maturity));
110
- }
111
- }
112
- // Order protocol
113
- if (amount > core_1.ccc.Zero) {
114
- this.orderManager.mint(tx, lock, info, {
115
- ckbValue: isCkb2Udt ? amount : core_1.ccc.Zero,
116
- udtValue: isCkb2Udt ? core_1.ccc.Zero : amount,
117
- });
118
- const convertedAmount = (0, core_2.convert)(isCkb2Udt, amount, rate);
119
- ckbFee = isCkb2Udt
120
- ? amount - (0, core_2.convert)(false, convertedAmount, exchangeRatio)
121
- : (0, core_2.convert)(true, amount, exchangeRatio) - convertedAmount;
122
- maturities.push(
123
- // TODO: use real world data from deposits, open orders and bot balances
124
- orderMaturityEstimate(isCkb2Udt, amount, system.tip));
125
- }
126
- // Check that order provides enough fee to the bot for being matched
127
- if (ckbFee < ckbMinFee) {
128
- return undefined;
129
- }
130
- const { receipts, withdrawalGroups, orders, udts, capacities } = userCells;
131
- this.logicManager.completeDeposit(tx, receipts);
132
- this.ownedOwnerManager.withdraw(tx, withdrawalGroups, filters);
133
- this.orderManager.melt(tx, orders, filters);
134
- this.ickbUdtManager.addUdts(tx, udts);
135
- utils_1.CapacityManager.addCapacities(tx, capacities);
136
- // Throw an error if inputs do not cover for outputs
137
- await new utils_1.RestrictedTransaction(tx).completeFeeBy(signer, feeRate);
138
- // Find the maturity most distant in the future
139
- const maturity = maturities.reduce((a, b) => (0, utils_1.epochCompare)(a, b) === -1 ? b : a);
140
- return {
141
- tx,
142
- ckbFee,
143
- maturity,
144
- };
145
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
146
- }
147
- catch (_) {
148
- return undefined;
149
- }
150
- }
151
- async getL1State(client, filter, locks, options) {
152
- const tip = await client.getTipHeader();
153
- const onChain = true;
154
- const opts = { ...options, tip, onChain };
155
- const [feeRate, depositPool, capacities, udts, receipts, withdrawalGroups, orders, deposits, withdrawalRequests,] = await Promise.all([
156
- client.getFeeRate(),
157
- filter.has("depositPool")
158
- ? (0, utils_1.collect)(this.logicManager.findDeposits(client, opts))
159
- : [],
160
- filter.has("capacities")
161
- ? (0, utils_1.collect)(utils_1.CapacityManager.findCapacities(client, locks, opts))
162
- : [],
163
- filter.has("udts")
164
- ? (0, utils_1.collect)(this.ickbUdtManager.findUdts(client, locks, opts))
165
- : [],
166
- filter.has("receipts")
167
- ? (0, utils_1.collect)(this.logicManager.findReceipts(client, locks, opts))
168
- : [],
169
- filter.has("withdrawalGroups")
170
- ? (0, utils_1.collect)(this.ownedOwnerManager.findWithdrawalGroups(client, locks, opts))
171
- : [],
172
- filter.has("orders") ? (0, utils_1.collect)(this.orderManager.findOrders(client)) : [],
173
- filter.has("deposits")
174
- ? (0, utils_1.collect)(this.daoManager.findDeposits(client, locks, opts))
175
- : [],
176
- filter.has("withdrawalRequests")
177
- ? (0, utils_1.collect)(this.daoManager.findWithdrawalRequests(client, locks, opts))
178
- : [],
179
- // TODO: fetch bot cells for estimating timings
180
- ]);
181
- // Sort depositPool by maturity
182
- depositPool.sort((a, b) => (0, utils_1.epochCompare)(a.maturity, b.maturity));
183
- // Calculate cumulative value of deposits in the pool
184
- let udtCumulative = 0n;
185
- const cumulativeDepositPool = [];
186
- for (const deposit of depositPool) {
187
- udtCumulative += deposit.udtValue;
188
- cumulativeDepositPool.push({ ...deposit, udtCumulative });
189
- }
190
- const userOrders = [];
191
- const nonUserOrders = [];
192
- for (const group of orders) {
193
- if (group.isOwner(...locks)) {
194
- userOrders.push(group);
195
- }
196
- else {
197
- nonUserOrders.push(group.order);
198
- }
199
- }
200
- const exchangeRatio = (0, core_2.ickbExchangeRatio)(tip);
201
- const ckbDepositCap = (0, core_2.convert)(false, core_2.ICKB_DEPOSIT_CAP, exchangeRatio);
202
- return {
203
- system: {
204
- feeRate,
205
- tip,
206
- exchangeRatio,
207
- ckbDepositCap,
208
- udtDepositCap: core_2.ICKB_DEPOSIT_CAP,
209
- depositPool: cumulativeDepositPool,
210
- orderPool: nonUserOrders,
211
- },
212
- user: {
213
- capacities,
214
- udts,
215
- receipts,
216
- withdrawalGroups,
217
- orders: userOrders,
218
- deposits,
219
- withdrawalRequests,
220
- },
221
- };
222
- }
223
- }
224
- exports.IckbController = IckbController;
225
- // Estimate bot ability to fulfill orders:
226
- // - CKB to iCKB orders at 100k CKB every minute
227
- // - iCKB to CKB orders at 200 CKB every minute
228
- function orderMaturityEstimate(isCkb2Udt, amount, tip) {
229
- return (0, utils_1.epochAdd)(tip.epoch, [
230
- 0n,
231
- 1n + amount / core_1.ccc.fixedPointFrom(isCkb2Udt ? 100000 : 200),
232
- 4n * 60n,
233
- ]);
234
- }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./sdk.js"), exports);
18
+ __exportStar(require("./codec.js"), exports);
19
+ __exportStar(require("./constants.js"), exports);
235
20
  //# sourceMappingURL=index.js.map
@@ -1 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a,EAAE,uBAAgB;gBAC/B,WAAW,EAAE,qBAAqB;gBAClC,SAAS,EAAE,aAAa;aACzB;YACD,IAAI,EAAE;gBACJ,UAAU;gBACV,IAAI;gBACJ,QAAQ;gBACR,gBAAgB;gBAChB,MAAM,EAAE,UAAU;gBAClB,QAAQ;gBACR,kBAAkB;aACnB;SACF,CAAC;IACJ,CAAC;CACF;AAzUD,wCAyUC;AA+BD,0CAA0C;AAC1C,gDAAgD;AAChD,+CAA+C;AAC/C,SAAS,qBAAqB,CAC5B,SAAkB,EAClB,MAAc,EACd,GAA0B;IAE1B,OAAO,IAAA,gBAAQ,EAAC,GAAG,CAAC,KAAK,EAAE;QACzB,EAAE;QACF,EAAE,GAAG,MAAM,GAAG,UAAG,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC;QAC1D,EAAE,GAAG,GAAG;KACT,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,6CAA2B;AAC3B,iDAA+B"}
@@ -0,0 +1,178 @@
1
+ import { ccc } from "@ckb-ccc/core";
2
+ import { CapacityManager, SmartTransaction, type ValueComponents } from "@ickb/utils";
3
+ import { type LogicManager, type OwnedOwnerManager } from "@ickb/core";
4
+ import { Info, OrderManager, Ratio, type OrderCell, type OrderGroup } from "@ickb/order";
5
+ import { getConfig } from "./constants.js";
6
+ /**
7
+ * SDK for managing iCKB operations.
8
+ */
9
+ export declare class IckbSdk {
10
+ private readonly ownedOwner;
11
+ private readonly ickbLogic;
12
+ private readonly order;
13
+ private readonly capacity;
14
+ private readonly bots;
15
+ /**
16
+ * Creates an instance of IckbSdk.
17
+ *
18
+ * @param ownedOwner - The manager for owned owner operations.
19
+ * @param ickbLogic - The manager for iCKB logic operations.
20
+ * @param order - The manager for order operations.
21
+ * @param capacity - The capacity manager instance.
22
+ * @param bots - An array of bot lock scripts.
23
+ */
24
+ constructor(ownedOwner: OwnedOwnerManager, ickbLogic: LogicManager, order: OrderManager, capacity: CapacityManager, bots: ccc.Script[]);
25
+ /**
26
+ * Creates an instance of IckbSdk from script dependencies.
27
+ *
28
+ * @param args - Parameters matching those of getConfig.
29
+ * @returns A new instance of IckbSdk.
30
+ */
31
+ static from(...args: Parameters<typeof getConfig>): IckbSdk;
32
+ /**
33
+ * Previews the conversion between CKB and UDT.
34
+ *
35
+ * This method calculates a conversion preview using an exchange ratio midpoint.
36
+ * Optionally, a fee may be applied that influences the effective conversion rate,
37
+ * scaling the converted amount by (feeBase - fee) / feeBase.
38
+ *
39
+ * @param isCkb2Udt - Indicates the conversion direction:
40
+ * - true: Convert CKB to UDT.
41
+ * - false: Convert UDT to CKB.
42
+ * @param amounts - An object containing value components (amounts for CKB and UDT).
43
+ * @param system - The current system state containing exchange ratio, fee rate, tip, and order-related information.
44
+ * @param options - Optional parameters for fee and matching:
45
+ * - fee: The fee to apply in integer terms (defaults to 1n for 0.001% fee).
46
+ * - feeBase: The base used for fee scaling (defaults to 100000n).
47
+ *
48
+ * @returns An object with:
49
+ * - convertedAmount: The estimated converted amount as a FixedPoint.
50
+ * - ckbFee: The fee (or gain) in CKB, as a FixedPoint.
51
+ * - info: Additional conversion metadata.
52
+ * - maturity: Optional maturity information (as ccc.Num) if meets criteria.
53
+ */
54
+ static estimate(isCkb2Udt: boolean, amounts: ValueComponents, system: SystemState, options?: {
55
+ fee?: ccc.Num;
56
+ feeBase?: ccc.Num;
57
+ }): {
58
+ convertedAmount: ccc.FixedPoint;
59
+ ckbFee: ccc.FixedPoint;
60
+ info: Info;
61
+ maturity: ccc.Num | undefined;
62
+ };
63
+ /**
64
+ * Estimates the maturity for an order formatted as a Unix timestamp.
65
+ *
66
+ * Depending on the order type and amount remaining, the method calculates an estimated timestamp
67
+ * when the order (or part thereof) might be fulfilled.
68
+ *
69
+ * @param o - Either an OrderCell or an object containing order Info and value components.
70
+ * @param system - The current system state.
71
+ * @returns The Unix timestamp of estimated maturity as a bigint (in milliseconds) or undefined if not applicable.
72
+ */
73
+ static maturity(o: OrderCell | {
74
+ info: Info;
75
+ amounts: ValueComponents;
76
+ }, system: SystemState): bigint | undefined;
77
+ /**
78
+ * Mints a new order cell and appends it to the transaction.
79
+ *
80
+ * The method performs the following operations:
81
+ * - Creates order cell data using provided amounts and order information.
82
+ * - Adds required cell dependencies and UDT handlers to the transaction.
83
+ * - Appends the order cell to the transaction outputs.
84
+ *
85
+ * @param tx - The smart transaction to which the order cell is added.
86
+ * @param user - The user, represented either as a Signer or a Script.
87
+ * @param info - The order information meta data (usually computed via OrderManager.convert).
88
+ * @param amounts - The value components for the order, including:
89
+ * - ckbValue: The CKB amount (may include an internal surplus).
90
+ * - udtValue: The UDT amount.
91
+ *
92
+ * @returns A Promise resolving to void.
93
+ */
94
+ request(tx: SmartTransaction, user: ccc.Signer | ccc.Script, info: Info, amounts: ValueComponents): Promise<void>;
95
+ /**
96
+ * Melts (cancels) the specified order groups.
97
+ *
98
+ * For each order group, if the option is set to process fulfilled orders only,
99
+ * it filters accordingly. Then, for every valid group, the master and order cells are added
100
+ * as inputs to the transaction.
101
+ *
102
+ * @param tx - The smart transaction to which the inputs are added.
103
+ * @param groups - An array of order groups to be melted.
104
+ * @param options - Optional parameters:
105
+ * - isFulfilledOnly: If true, only order groups with fully or partially fulfilled orders are processed.
106
+ *
107
+ * @returns void
108
+ */
109
+ collect(tx: SmartTransaction, groups: OrderGroup[], options?: {
110
+ isFulfilledOnly?: boolean;
111
+ }): void;
112
+ /**
113
+ * Retrieves the L1 state from the blockchain.
114
+ *
115
+ * The method performs the following:
116
+ * - Obtains the current block tip and calculates the exchange ratio.
117
+ * - Fetches available CKB and the maturing CKB based on bot capacities and deposit snapshots.
118
+ * - Filters orders into user-owned and system orders based on the provided locks.
119
+ * - Estimates user-owned orders maturity.
120
+ *
121
+ * @param client - The blockchain client interface.
122
+ * @param locks - An array of lock scripts used to filter user cells.
123
+ * @returns A promise that resolves to an object containing:
124
+ * - system: The system state (fee rate, tip header, exchange ratio, order pool, etc.).
125
+ * - user: The user's orders grouped as an array of OrderGroup.
126
+ */
127
+ getL1State(client: ccc.Client, locks: ccc.Script[]): Promise<{
128
+ system: SystemState;
129
+ user: {
130
+ orders: OrderGroup[];
131
+ };
132
+ }>;
133
+ /**
134
+ * Retrieves available CKB and maturing CKB values from the blockchain.
135
+ *
136
+ * This method:
137
+ * - Fetches bot withdrawal requests and deposit snapshots.
138
+ * - Aggregates available CKB balances from bot capacities.
139
+ * - Calculates maturing CKB values (with their expected maturity timestamps)
140
+ * based on deposit pool snapshots or via direct deposit cell lookups.
141
+ * - Sorts and cumulatively sums the maturing values for later lookup.
142
+ *
143
+ * @param client - The blockchain client used for fetching data.
144
+ * @param tip - The current block tip header.
145
+ * @returns A Promise that resolves with:
146
+ * - ckbAvailable: The total available CKB (as a FixedPoint).
147
+ * - ckbMaturing: An array of maturing CKB objects containing the cumulative CKB
148
+ * and the associated maturity timestamp.
149
+ */
150
+ private getCkb;
151
+ }
152
+ /**
153
+ * Represents the state of the system.
154
+ */
155
+ export interface SystemState {
156
+ /** The fee rate for transactions. */
157
+ feeRate: ccc.Num;
158
+ /** The tip for the current block header. */
159
+ tip: ccc.ClientBlockHeader;
160
+ /** The exchange ratio between CKB and UDT. */
161
+ exchangeRatio: Ratio;
162
+ /** The order pool containing order cells matching system criteria. */
163
+ orderPool: OrderCell[];
164
+ /** The total available CKB (as FixedPoint). */
165
+ ckbAvailable: ccc.FixedPoint;
166
+ /** Array of CKB maturing entries with cumulative amounts and maturity timestamps. */
167
+ ckbMaturing: CkbCumulative[];
168
+ }
169
+ /**
170
+ * Represents a cumulative CKB maturing entry.
171
+ */
172
+ export interface CkbCumulative {
173
+ /** The cumulative CKB value (as FixedPoint) up to this maturity. */
174
+ ckbCumulative: ccc.FixedPoint;
175
+ /** The maturity timestamp (as ccc.Num). */
176
+ maturity: ccc.Num;
177
+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