@ickb/sdk 1000.0.82 → 9001.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +84 -32
  2. package/dist/constants.d.ts +9 -22
  3. package/dist/constants.d.ts.map +1 -1
  4. package/dist/constants.js +62 -76
  5. package/dist/constants.js.map +1 -1
  6. package/dist/conversion/estimate.d.ts +33 -0
  7. package/dist/conversion/estimate.d.ts.map +1 -0
  8. package/dist/conversion/estimate.js +117 -0
  9. package/dist/conversion/estimate.js.map +1 -0
  10. package/dist/conversion/maturity.d.ts +15 -0
  11. package/dist/conversion/maturity.d.ts.map +1 -0
  12. package/dist/conversion/maturity.js +113 -0
  13. package/dist/conversion/maturity.js.map +1 -0
  14. package/dist/conversion/plans.d.ts +20 -0
  15. package/dist/conversion/plans.d.ts.map +1 -0
  16. package/dist/conversion/plans.js +106 -0
  17. package/dist/conversion/plans.js.map +1 -0
  18. package/dist/conversion/projection.d.ts +21 -0
  19. package/dist/conversion/projection.d.ts.map +1 -0
  20. package/dist/conversion/projection.js +94 -0
  21. package/dist/conversion/projection.js.map +1 -0
  22. package/dist/conversion/types.d.ts +264 -0
  23. package/dist/conversion/types.d.ts.map +1 -0
  24. package/dist/conversion/types.js +2 -0
  25. package/dist/conversion/types.js.map +1 -0
  26. package/dist/conversion/withdrawal_ring.d.ts +34 -0
  27. package/dist/conversion/withdrawal_ring.d.ts.map +1 -0
  28. package/dist/conversion/withdrawal_ring.js +87 -0
  29. package/dist/conversion/withdrawal_ring.js.map +1 -0
  30. package/dist/dao.d.ts +100 -0
  31. package/dist/dao.d.ts.map +1 -0
  32. package/dist/dao.js +125 -0
  33. package/dist/dao.js.map +1 -0
  34. package/dist/index.d.ts +49 -3
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +20 -3
  37. package/dist/index.js.map +1 -1
  38. package/dist/logic.d.ts +81 -0
  39. package/dist/logic.d.ts.map +1 -0
  40. package/dist/logic.js +173 -0
  41. package/dist/logic.js.map +1 -0
  42. package/dist/order/cells.d.ts +168 -0
  43. package/dist/order/cells.d.ts.map +1 -0
  44. package/dist/order/cells.js +309 -0
  45. package/dist/order/cells.js.map +1 -0
  46. package/dist/order/conversion.d.ts +37 -0
  47. package/dist/order/conversion.d.ts.map +1 -0
  48. package/dist/order/conversion.js +120 -0
  49. package/dist/order/conversion.js.map +1 -0
  50. package/dist/order/fee.d.ts +9 -0
  51. package/dist/order/fee.d.ts.map +1 -0
  52. package/dist/order/fee.js +24 -0
  53. package/dist/order/fee.js.map +1 -0
  54. package/dist/order/fill.d.ts +36 -0
  55. package/dist/order/fill.d.ts.map +1 -0
  56. package/dist/order/fill.js +53 -0
  57. package/dist/order/fill.js.map +1 -0
  58. package/dist/order/info.d.ts +62 -0
  59. package/dist/order/info.d.ts.map +1 -0
  60. package/dist/order/info.js +102 -0
  61. package/dist/order/info.js.map +1 -0
  62. package/dist/order/master.d.ts +49 -0
  63. package/dist/order/master.d.ts.map +1 -0
  64. package/dist/order/master.js +27 -0
  65. package/dist/order/master.js.map +1 -0
  66. package/dist/order/matcher.d.ts +43 -0
  67. package/dist/order/matcher.d.ts.map +1 -0
  68. package/dist/order/matcher.js +124 -0
  69. package/dist/order/matcher.js.map +1 -0
  70. package/dist/order/order.d.ts +63 -0
  71. package/dist/order/order.d.ts.map +1 -0
  72. package/dist/order/order.js +234 -0
  73. package/dist/order/order.js.map +1 -0
  74. package/dist/order/order_data.d.ts +51 -0
  75. package/dist/order/order_data.d.ts.map +1 -0
  76. package/dist/order/order_data.js +67 -0
  77. package/dist/order/order_data.js.map +1 -0
  78. package/dist/order/ratio.d.ts +40 -0
  79. package/dist/order/ratio.d.ts.map +1 -0
  80. package/dist/order/ratio.js +74 -0
  81. package/dist/order/ratio.js.map +1 -0
  82. package/dist/order/relative.d.ts +43 -0
  83. package/dist/order/relative.d.ts.map +1 -0
  84. package/dist/order/relative.js +57 -0
  85. package/dist/order/relative.js.map +1 -0
  86. package/dist/owned_owner.d.ts +108 -0
  87. package/dist/owned_owner.d.ts.map +1 -0
  88. package/dist/owned_owner.js +260 -0
  89. package/dist/owned_owner.js.map +1 -0
  90. package/dist/sdk.d.ts +113 -41
  91. package/dist/sdk.d.ts.map +1 -1
  92. package/dist/sdk.js +410 -209
  93. package/dist/sdk.js.map +1 -1
  94. package/dist/send/sign_and_send_transaction.d.ts +61 -0
  95. package/dist/send/sign_and_send_transaction.d.ts.map +1 -0
  96. package/dist/send/sign_and_send_transaction.js +201 -0
  97. package/dist/send/sign_and_send_transaction.js.map +1 -0
  98. package/dist/send/wait_transaction.d.ts +42 -0
  99. package/dist/send/wait_transaction.d.ts.map +1 -0
  100. package/dist/send/wait_transaction.js +172 -0
  101. package/dist/send/wait_transaction.js.map +1 -0
  102. package/dist/udt.d.ts +108 -0
  103. package/dist/udt.d.ts.map +1 -0
  104. package/dist/udt.js +180 -0
  105. package/dist/udt.js.map +1 -0
  106. package/dist/utils/chain.d.ts +3 -0
  107. package/dist/utils/chain.d.ts.map +1 -0
  108. package/dist/utils/chain.js +2 -0
  109. package/dist/utils/chain.js.map +1 -0
  110. package/dist/utils/codec.d.ts +19 -0
  111. package/dist/utils/codec.d.ts.map +1 -0
  112. package/dist/utils/codec.js +69 -0
  113. package/dist/utils/codec.js.map +1 -0
  114. package/dist/utils/utils.d.ts +99 -0
  115. package/dist/utils/utils.d.ts.map +1 -0
  116. package/dist/utils/utils.js +130 -0
  117. package/dist/utils/utils.js.map +1 -0
  118. package/dist/utils/verified_client.d.ts +19 -0
  119. package/dist/utils/verified_client.d.ts.map +1 -0
  120. package/dist/utils/verified_client.js +92 -0
  121. package/dist/utils/verified_client.js.map +1 -0
  122. package/package.json +19 -26
  123. package/src/constants.ts +65 -181
  124. package/src/conversion/estimate.ts +155 -0
  125. package/src/conversion/maturity.ts +158 -0
  126. package/src/conversion/plans.ts +144 -0
  127. package/src/conversion/projection.ts +136 -0
  128. package/src/conversion/types.ts +302 -0
  129. package/src/conversion/withdrawal_ring.ts +122 -0
  130. package/src/dao.ts +196 -0
  131. package/src/index.ts +89 -3
  132. package/src/logic.ts +283 -0
  133. package/src/order/cells.ts +383 -0
  134. package/src/order/conversion.ts +162 -0
  135. package/src/order/fee.ts +30 -0
  136. package/src/order/fill.ts +83 -0
  137. package/src/order/info.ts +181 -0
  138. package/src/order/master.ts +42 -0
  139. package/src/order/matcher.ts +191 -0
  140. package/src/order/order.ts +288 -0
  141. package/src/order/order_data.ts +131 -0
  142. package/src/order/ratio.ts +127 -0
  143. package/src/order/relative.ts +109 -0
  144. package/src/owned_owner.ts +364 -0
  145. package/src/sdk.ts +542 -440
  146. package/src/send/sign_and_send_transaction.ts +256 -0
  147. package/src/send/wait_transaction.ts +227 -0
  148. package/src/udt.ts +249 -0
  149. package/src/utils/chain.ts +2 -0
  150. package/src/utils/codec.ts +78 -0
  151. package/src/utils/utils.ts +208 -0
  152. package/src/utils/verified_client.ts +136 -0
  153. package/dist/codec.d.ts +0 -3
  154. package/dist/codec.d.ts.map +0 -1
  155. package/dist/codec.js +0 -58
  156. package/dist/codec.js.map +0 -1
  157. package/src/codec.ts +0 -138
package/dist/sdk.js CHANGED
@@ -1,242 +1,443 @@
1
1
  import { ccc } from "@ckb-ccc/core";
2
- import { collect, CapacityManager, SmartTransaction, binarySearch, hexFrom, getHeader, Epoch, } from "@ickb/utils";
3
- import { convert, ICKB_DEPOSIT_CAP, ickbExchangeRatio, } from "@ickb/core";
4
- import { Info, OrderManager, Ratio, } from "@ickb/order";
5
2
  import { getConfig } from "./constants.js";
6
- import { PoolSnapshot } from "./codec.js";
3
+ import { minimumOrderAmount } from "./conversion/estimate.js";
4
+ import { ckbToIckbConversionPlans, ickbToCkbConversionPlans, } from "./conversion/plans.js";
5
+ import { assertDaoOutputLimit, assertFresh, broadcastDeadline, DaoHeaderIndexError, DaoOutputLimitError, pushHeaderDep, tipMaxAgeMs, } from "./dao.js";
6
+ import { Ratio } from "./order/ratio.js";
7
+ import { ickbExchangeRatio } from "./udt.js";
8
+ import { compareBigInt, findCells, isPlainCapacityCell, unique } from "./utils/utils.js";
9
+ import { verifiedClient } from "./utils/verified_client.js";
10
+ /**
11
+ * Input count up to which one own transaction sweeps liquid cells.
12
+ *
13
+ * @remarks A compaction target, not a validity bound: required funding and the fee may go
14
+ * past it. Counted rather than measured in bytes because a same-lock input costs a fixed
15
+ * 44 bytes (52 with an extra witness slot), so 1,000 inputs stay near 50 KB, far under the
16
+ * node's 512,000-byte limit, and near the one measured point (1,000 inputs: 44 KB, about
17
+ * 180 ms of local completion). A miner paying the bot adds about forty cellbase cells per
18
+ * turn, which this outpaces; a larger backlog takes several transactions.
19
+ */
20
+ export const SWEEP_INPUT_LIMIT = 1000;
21
+ /**
22
+ * The whole SDK, which the Node actors drive by relative import; the package barrel
23
+ * exposes the two conversion-workflow methods, and its assignment checks they agree.
24
+ */
7
25
  export class IckbSdk {
8
- constructor(ownedOwner, ickbLogic, order, capacity, bots) {
9
- Object.defineProperty(this, "ownedOwner", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: ownedOwner
14
- });
15
- Object.defineProperty(this, "ickbLogic", {
16
- enumerable: true,
17
- configurable: true,
18
- writable: true,
19
- value: ickbLogic
20
- });
21
- Object.defineProperty(this, "order", {
22
- enumerable: true,
23
- configurable: true,
24
- writable: true,
25
- value: order
26
- });
27
- Object.defineProperty(this, "capacity", {
28
- enumerable: true,
29
- configurable: true,
30
- writable: true,
31
- value: capacity
32
- });
33
- Object.defineProperty(this, "bots", {
34
- enumerable: true,
35
- configurable: true,
36
- writable: true,
37
- value: bots
38
- });
26
+ ickbUdt;
27
+ ownedOwner;
28
+ ickbLogic;
29
+ order;
30
+ constructor({ ickbUdt, ownedOwner, ickbLogic, order }) {
31
+ this.ickbUdt = ickbUdt;
32
+ this.ownedOwner = ownedOwner;
33
+ this.ickbLogic = ickbLogic;
34
+ this.order = order;
39
35
  }
40
- static from(...args) {
41
- const { managers: { ownedOwner, logic, order, capacity }, bots, } = getConfig(...args);
42
- return new IckbSdk(ownedOwner, logic, order, capacity, bots);
36
+ /** Creates the SDK for one chain's deployment. */
37
+ static fromChain(chain) {
38
+ return new IckbSdk(getConfig(chain));
43
39
  }
44
- static estimate(isCkb2Udt, amounts, system, options) {
45
- options = {
46
- fee: 1n,
47
- feeBase: 100000n,
48
- ...options,
40
+ // ---- State reads -------------------------------------------------------------------
41
+ /**
42
+ * Reads system, user-order, and account state at the sampled tip's parent, under the
43
+ * caller's withdrawal timing rules (`BOT_LOCK_UP` or `WALLET_LOCK_UP`) and, when given, a
44
+ * positive fee rate cap that replaces CCC's ceiling; a cap of zero or less throws.
45
+ *
46
+ * @remarks Every read goes through `verifiedClient` and the tip's parent is bounded by the
47
+ * policy's slack, so a caller passes a plain client. Every read is complete and uncapped: a large
48
+ * book or pool costs a slower read, never a partial or failed one. Each account lock is
49
+ * enumerated by one uncached unfiltered exact-lock scan and classified client-side.
50
+ */
51
+ async getL1AccountState(plainClient, locks, lockUp, maxFeeRate) {
52
+ // CCC reads a zero cap as no cap at all and would plan at a negative one.
53
+ if (maxFeeRate !== undefined && ccc.numFrom(maxFeeRate) <= ccc.Zero) {
54
+ throw new RangeError("maxFeeRate must be positive");
55
+ }
56
+ const client = verifiedClient(plainClient);
57
+ const live = await client.getTipHeader();
58
+ // The live tip can still lose a one-block race, and a transaction naming it as a header
59
+ // dep is then refused after signing; every recorded fork was one block deep.
60
+ const tip = await client.getHeaderByNumber(live.number - 1n);
61
+ if (tip?.hash !== live.parentHash) {
62
+ throw new Error(`Block ${String(live.number - 1n)} is not the parent of tip ${live.hash}`);
63
+ }
64
+ // The age bound is on the header the read is priced at: a fresh tip a node invented can
65
+ // name any old block as its parent.
66
+ assertFresh(tip, tipMaxAgeMs(lockUp));
67
+ const exchangeRatio = Ratio.from(ickbExchangeRatio(tip));
68
+ const [poolDeposits, orders, feeRate, accounts] = await Promise.all([
69
+ this.ickbLogic.findDeposits(client, tip),
70
+ this.order.findOrders(client),
71
+ // CCC clamps the sampled median at the cap, the connector's chosen rate too. A given cap
72
+ // replaces CCC's default ceiling, on purpose: the caller's cap is the ceiling.
73
+ client.getFeeRate(undefined, maxFeeRate === undefined ? undefined : { maxFeeRate }),
74
+ Promise.all([...unique(locks)].map(async (lock) => this.readLockCells(client, lock, tip))),
75
+ ]);
76
+ return {
77
+ system: {
78
+ feeRate,
79
+ tip,
80
+ exchangeRatio,
81
+ // One book, two filters: the market side is every order
82
+ // past par, the wallet's own included, since the bot fills by price, not by owner.
83
+ orderPool: orders.filter((group) => isPastPar(group, exchangeRatio)),
84
+ poolDeposits,
85
+ lockUp,
86
+ },
87
+ userOrders: orders.filter((group) => group.isOwner(...locks)),
88
+ account: {
89
+ capacityCells: accounts.flatMap((account) => account.capacityCells),
90
+ nativeUdtCells: accounts.flatMap((account) => account.nativeUdtCells),
91
+ receipts: accounts.flatMap((account) => account.receipts),
92
+ withdrawalGroups: accounts.flatMap((account) => account.withdrawalGroups),
93
+ },
49
94
  };
50
- const { convertedAmount, ckbFee, info } = OrderManager.convert(isCkb2Udt, system.exchangeRatio, amounts, options);
51
- const maturity = ckbFee >= 10n * system.feeRate
52
- ? IckbSdk.maturity({ info, amounts }, system)
53
- : undefined;
54
- return { convertedAmount, ckbFee, info, maturity };
55
- }
56
- static maturity(o, system) {
57
- const info = "info" in o ? o.info : o.data.info;
58
- const amounts = "amounts" in o
59
- ? o.amounts
60
- : { ckbValue: o.ckbUnoccupied, udtValue: o.udtValue };
61
- if (info.isDualRatio()) {
62
- return;
95
+ }
96
+ /** Every Stack cell one lock owns, classified from a single exact-lock scan. */
97
+ async readLockCells(client, lock, tip) {
98
+ const scanned = await findCells(client, {
99
+ script: lock,
100
+ scriptType: "lock",
101
+ scriptSearchMode: "exact",
102
+ withData: true,
103
+ });
104
+ const cells = scanned.map(({ cell }) => cell);
105
+ const [receipts, withdrawalGroups] = await Promise.all([
106
+ this.ickbLogic.receiptsFrom(client, scanned),
107
+ this.ownedOwner.withdrawalGroupsFrom(client, scanned, tip),
108
+ ]);
109
+ return {
110
+ capacityCells: cells.filter(isPlainCapacityCell),
111
+ nativeUdtCells: cells.filter((cell) => this.ickbUdt.isUdt(cell)),
112
+ receipts,
113
+ withdrawalGroups,
114
+ };
115
+ }
116
+ // ---- Conversion planning -----------------------------------------------------------
117
+ /**
118
+ * Builds and completes one conversion transaction from a conversion context.
119
+ *
120
+ * @remarks
121
+ * Every branch returns a transaction funded from the signer's committed cells: the
122
+ * candidate plans (deposit counts, or prefixes of the greedy withdrawal selection with
123
+ * their rebuilt remainder order) are completed most direct first and the first fundable one
124
+ * wins, so a wallet short of CKB degrades to fewer direct actions plus a larger standing
125
+ * order rather than failing. Failure results are
126
+ * expected planning outcomes; when no plan can be funded the last completion error throws.
127
+ */
128
+ async buildConversionTransaction(options) {
129
+ const { amount, context, direction } = options;
130
+ if (amount < 0n) {
131
+ return conversionFailure("amount-negative", context.estimatedMaturity);
63
132
  }
64
- const isCkb2Udt = info.isCkb2Udt();
65
- const amount = isCkb2Udt ? amounts.ckbValue : amounts.udtValue;
66
- const ratio = isCkb2Udt ? info.ckbToUdt : info.udtToCkb;
67
- if (amount === 0n) {
68
- return 0n;
69
- }
70
- const { tip, exchangeRatio, orderPool, ckbAvailable, ckbMaturing } = system;
71
- const b = new Info(ratio, ratio, 1);
72
- let ckb = isCkb2Udt ? amount : 0n;
73
- let udt = isCkb2Udt ? 0n : amount;
74
- for (const o of orderPool) {
75
- const a = o.data.info;
76
- if (a.isCkb2Udt()) {
77
- if (!isCkb2Udt || a.ckb2UdtCompare(b) < 0) {
78
- ckb += o.ckbUnoccupied;
79
- }
80
- }
81
- else {
82
- if (isCkb2Udt || a.udt2CkbCompare(b) < 0) {
83
- udt += o.udtValue;
84
- }
85
- }
133
+ if (direction === "ckb-to-ickb" && amount > context.ckbAvailable) {
134
+ return conversionFailure("insufficient-ckb", context.estimatedMaturity);
86
135
  }
87
- ckb -= convert(false, udt, exchangeRatio);
88
- let maturity = 10n * 60n * 1000n;
89
- if (isCkb2Udt) {
90
- if (ckb > 0n) {
91
- maturity *= 1n + ckb / ccc.fixedPointFrom("200000");
92
- }
93
- return maturity + ("info" in o ? BigInt(Date.now()) : tip.timestamp);
136
+ if (direction === "ickb-to-ckb" && amount > context.ickbAvailable) {
137
+ return conversionFailure("insufficient-ickb", context.estimatedMaturity);
94
138
  }
95
- ckb += ckbAvailable;
96
- if (ckb >= 0) {
97
- return maturity + ("info" in o ? BigInt(Date.now()) : tip.timestamp);
139
+ const resolved = {
140
+ ...options,
141
+ lock: options.lock ?? (await options.signer.getRecommendedAddressObj()).script,
142
+ };
143
+ if (amount === 0n) {
144
+ return this.buildCollectOnlyConversion(resolved);
98
145
  }
99
- const ckbNeeded = -ckb;
100
- const i = binarySearch(ckbMaturing.length, (n) => ckbMaturing[n].ckbCumulative >= ckbNeeded);
101
- return ckbMaturing[i]?.maturity;
146
+ return direction === "ckb-to-ickb"
147
+ ? this.buildCkbToIckbConversion(resolved)
148
+ : this.buildIckbToCkbConversion(resolved);
102
149
  }
103
- async request(tx, user, info, amounts) {
104
- user =
105
- "codeHash" in user
106
- ? user
107
- : (await user.getRecommendedAddressObj()).script;
108
- this.order.mint(tx, user, info, amounts);
109
- }
110
- collect(tx, groups, options) {
111
- this.order.melt(tx, groups, options);
150
+ async buildCollectOnlyConversion(options) {
151
+ const { context, lock, signer } = options;
152
+ const tx = this.buildBaseTransaction(ccc.Transaction.default(), context);
153
+ // An empty collection to a lock of the signer's own would only compact the account;
154
+ // to another lock it moves the liquid cells, which completion builds from the sweep.
155
+ if (!hasTransactionActivity(tx) &&
156
+ (context.cells.length === 0 || (await isOwnLock(signer, lock)))) {
157
+ return conversionFailure("nothing-to-do", context.estimatedMaturity);
158
+ }
159
+ const completed = await this.completeConversion(tx, options);
160
+ return {
161
+ ok: true,
162
+ tx: completed,
163
+ estimatedMaturity: context.estimatedMaturity,
164
+ conversionKind: "collect-only",
165
+ isSweepComplete: sweepsAll(completed, context.cells),
166
+ };
112
167
  }
113
- async getL1State(client, locks) {
114
- const tip = await client.getTipHeader();
115
- const exchangeRatio = Ratio.from(ickbExchangeRatio(tip));
116
- const [{ ckbAvailable, ckbMaturing }, orders, feeRate] = await Promise.all([
117
- this.getCkb(client, tip),
118
- collect(this.order.findOrders(client)),
119
- client.getFeeRate(),
120
- ]);
121
- const midInfo = new Info(exchangeRatio, exchangeRatio, 1);
122
- const userOrders = [];
123
- const systemOrders = [];
124
- for (const group of orders) {
125
- if (group.isOwner(...locks)) {
126
- userOrders.push(group);
168
+ async buildCkbToIckbConversion(options) {
169
+ const { context, lock } = options;
170
+ // A plan is dropped only for an unrepresentable remainder order.
171
+ const plans = ckbToIckbConversionPlans(options);
172
+ if (plans.length === 0) {
173
+ return {
174
+ ok: false,
175
+ reason: "amount-too-small",
176
+ estimatedMaturity: context.estimatedMaturity,
177
+ minimum: minimumOrderAmount(true, context.system),
178
+ };
179
+ }
180
+ const { candidate: plan, tx } = await completeFirstFundable(plans, (candidate) => {
181
+ let partial = this.buildBaseTransaction(ccc.Transaction.default(), context);
182
+ if (candidate.depositCount > 0) {
183
+ partial = this.ickbLogic.deposit(partial, candidate.depositCount, candidate.depositCapacity, lock);
127
184
  }
128
- const { order } = group;
129
- const info = order.data.info;
130
- if ((order.isCkb2UdtMatchable() && info.ckb2UdtCompare(midInfo) < 0) ||
131
- (order.isUdt2CkbMatchable() && info.udt2CkbCompare(midInfo) < 0)) {
132
- systemOrders.push(order);
185
+ if (candidate.order !== undefined) {
186
+ partial = this.order.mint(partial, lock, candidate.order.estimate.info, candidate.order.amounts);
133
187
  }
134
- }
135
- const system = {
136
- feeRate,
137
- tip,
138
- exchangeRatio,
139
- orderPool: systemOrders,
140
- ckbAvailable,
141
- ckbMaturing,
188
+ return partial;
189
+ }, async (partial) => this.completeConversion(partial, options));
190
+ return {
191
+ ok: true,
192
+ tx,
193
+ estimatedMaturity: plan.estimatedMaturity,
194
+ conversionKind: conversionKind(plan.depositCount > 0, plan.order !== undefined),
195
+ isSweepComplete: sweepsAll(tx, context.cells),
142
196
  };
143
- for (const { order } of userOrders) {
144
- order.maturity = IckbSdk.maturity(order, system);
197
+ }
198
+ async buildIckbToCkbConversion(options) {
199
+ const { context, lock } = options;
200
+ const plans = ickbToCkbConversionPlans(options, context.system.poolDeposits);
201
+ if (plans.length === 0) {
202
+ return {
203
+ ok: false,
204
+ reason: "amount-too-small",
205
+ estimatedMaturity: context.estimatedMaturity,
206
+ minimum: minimumOrderAmount(false, context.system),
207
+ };
145
208
  }
209
+ const { candidate: plan, tx } = await completeFirstFundable(plans, (candidate) => {
210
+ let partial = this.buildBaseTransaction(ccc.Transaction.default(), context, {
211
+ deposits: candidate.selectedDeposits,
212
+ lock,
213
+ });
214
+ if (candidate.order !== undefined) {
215
+ partial = this.order.mint(partial, lock, candidate.order.estimate.info, candidate.order.amounts);
216
+ }
217
+ return partial;
218
+ }, async (partial) => this.completeConversion(partial, options));
219
+ const notice = plan.order?.estimate.notice;
220
+ const broadcastBefore = broadcastDeadline(plan.selectedDeposits.map((deposit) => deposit.claimEpoch), context.system.lockUp);
146
221
  return {
147
- system,
148
- user: {
149
- orders: userOrders,
150
- },
222
+ ok: true,
223
+ tx,
224
+ estimatedMaturity: plan.estimatedMaturity,
225
+ conversionKind: conversionKind(plan.selectedDeposits.length > 0, plan.order !== undefined),
226
+ ...(notice === undefined ? {} : { conversionNotice: notice }),
227
+ isSweepComplete: sweepsAll(tx, context.cells),
228
+ ...(broadcastBefore === undefined ? {} : { broadcastBefore }),
151
229
  };
152
230
  }
153
- async getCkb(client, tip) {
154
- const opts = {
155
- onChain: true,
156
- tip,
157
- };
158
- const promiseBotWithdrawals = collect(this.ownedOwner.findWithdrawalGroups(client, this.bots, opts));
159
- let poolSnapshotHex = "0x";
160
- let poolSnapshotEpoch = Epoch.from([0n, 0n, 1n]);
161
- const bot2Ckb = new Map();
162
- const reserved = -ccc.fixedPointFrom("2000");
163
- for await (const c of this.capacity.findCapacities(client, this.bots, opts)) {
164
- const key = hexFrom(c.cell.cellOutput.lock);
165
- const ckb = (bot2Ckb.get(key) ?? reserved) + c.ckbValue;
166
- bot2Ckb.set(key, ckb);
167
- const outputData = c.cell.outputData;
168
- if (outputData.length % 256 === 2) {
169
- const h = await getHeader(client, {
170
- type: "txHash",
171
- value: c.cell.outPoint.txHash,
172
- });
173
- const e = Epoch.from(h.epoch);
174
- if (poolSnapshotEpoch.compare(e) < 0) {
175
- poolSnapshotHex = outputData;
176
- poolSnapshotEpoch = e;
177
- }
231
+ async completeConversion(tx, options) {
232
+ return this.completeTransaction(tx, {
233
+ signer: options.signer,
234
+ lock: options.lock,
235
+ feeRate: options.context.system.feeRate,
236
+ cells: options.context.cells,
237
+ protocolCells: [
238
+ ...options.context.receipts,
239
+ ...options.context.system.poolDeposits,
240
+ ],
241
+ tip: options.context.system.tip,
242
+ });
243
+ }
244
+ // ---- Transaction building ----------------------------------------------------------
245
+ /**
246
+ * Adds the context's collect steps to a partial transaction: the withdrawal requests when
247
+ * given, then the collectable orders, the receipts, and the ready withdrawals.
248
+ *
249
+ * @remarks
250
+ * The result is still partial. Callers should use `completeTransaction` before
251
+ * signing and sending. The withdrawals move their deposit headers to the front of
252
+ * `headerDeps`, so the given transaction must not reference a header by position.
253
+ */
254
+ buildBaseTransaction(txLike, steps, withdrawalRequest) {
255
+ let tx = ccc.Transaction.from(txLike);
256
+ if (withdrawalRequest !== undefined && withdrawalRequest.deposits.length > 0) {
257
+ tx = this.ownedOwner.requestWithdrawal(tx, withdrawalRequest.deposits, withdrawalRequest.lock);
258
+ }
259
+ if (steps.availableOrders.length > 0) {
260
+ tx = this.order.melt(tx, steps.availableOrders);
261
+ }
262
+ if (steps.receipts.length > 0) {
263
+ tx = this.ickbLogic.completeDeposit(tx, steps.receipts);
264
+ }
265
+ if (steps.readyWithdrawals.length > 0) {
266
+ tx = this.ownedOwner.withdraw(tx, steps.readyWithdrawals);
267
+ }
268
+ return tx;
269
+ }
270
+ /**
271
+ * Completes iCKB inputs, iCKB change, plain change, and the fee from the cells it is given.
272
+ *
273
+ * @remarks Completion never scans. `cells` are the signer's known liquid cells, plain
274
+ * CKB and iCKB, from the account state already read: the largest ones fund what the
275
+ * outputs need, the rest ride along as a sweep while the transaction has fewer than
276
+ * {@link SWEEP_INPUT_LIMIT} inputs, so every own transaction compacts the account.
277
+ * Ordinary change is always a plain cell; existing outputs
278
+ * are never reinterpreted or resized as fee change. This does not sign or send.
279
+ */
280
+ async completeTransaction(txLike, options) {
281
+ const { signer, feeRate } = options;
282
+ const tx = ccc.Transaction.from(txLike).clone();
283
+ tx.addCellDeps(this.ickbUdt.cellDeps);
284
+ const changeLock = options.lock ?? (await signer.getRecommendedAddressObj()).script;
285
+ // Inputs come from one state read, each cell once, and each action spends its own
286
+ // cell kind, so a repeated out point is a builder bug: this is the one place that
287
+ // names it, the node would refuse the transaction anyway.
288
+ const spent = new Set();
289
+ for (const { previousOutput } of tx.inputs) {
290
+ const key = previousOutput.toHex();
291
+ if (spent.has(key)) {
292
+ throw new Error(`Input ${key} is spent twice`);
178
293
  }
294
+ spent.add(key);
179
295
  }
180
- const ckbMaturing = new Array();
181
- for (const wr of await promiseBotWithdrawals) {
182
- if (wr.owned.isReady) {
183
- const key = hexFrom(wr.owner.cell.cellOutput.lock);
184
- const ckb = (bot2Ckb.get(key) ?? reserved) + wr.ckbValue;
185
- bot2Ckb.set(key, ckb);
186
- continue;
296
+ const unspent = options.cells.filter((cell) => !spent.has(cell.outPoint.toHex()));
297
+ const ickbCells = unspent
298
+ .filter((cell) => this.ickbUdt.isUdt(cell))
299
+ .toSorted((left, right) => compareBigInt(udtBalance(right), udtBalance(left)));
300
+ const plainCells = unspent
301
+ .filter(isPlainCapacityCell)
302
+ .toSorted((left, right) => compareBigInt(right.cellOutput.capacity, left.cellOutput.capacity));
303
+ await this.completeIckb(tx, signer.client, changeLock, ickbCells, options.protocolCells);
304
+ // Plain CKB: the sweep first, then whatever the fee still needs beyond the limit.
305
+ const swept = sweep(tx, plainCells);
306
+ // Last of the header deps, so no index another step names shifts, and before the fee so
307
+ // its 32 bytes are paid for.
308
+ pushHeaderDep(tx, options.tip.hash);
309
+ await completeFee(tx, signer, changeLock, feeRate, plainCells.slice(swept));
310
+ assertDaoOutputLimit(tx, this.ickbLogic.dao.script);
311
+ return tx;
312
+ }
313
+ /** iCKB: what the outputs need first, then the sweep while the limit allows, then change. */
314
+ async completeIckb(tx, client, changeLock, ickbCells, protocolCells) {
315
+ const required = tx.getOutputsUdtBalance(this.ickbUdt.script);
316
+ let balance = await this.ickbUdt.inputBalance(tx, client, protocolCells);
317
+ for (const cell of ickbCells) {
318
+ if (balance >= required && tx.inputs.length >= SWEEP_INPUT_LIMIT) {
319
+ break;
187
320
  }
188
- ckbMaturing.push({
189
- ckbValue: wr.ckbValue,
190
- maturity: wr.owned.maturity.toUnix(tip),
321
+ tx.addInput(cell);
322
+ balance += udtBalance(cell);
323
+ }
324
+ if (balance < required) {
325
+ throw new IckbError(`Insufficient iCKB, need ${String(required - balance)} more`, {
326
+ code: "insufficient_ickb",
191
327
  });
192
328
  }
193
- let ckbAvailable = 0n;
194
- for (const ckb of bot2Ckb.values()) {
195
- if (ckb > 0n) {
196
- ckbAvailable += ckb;
197
- }
329
+ this.ickbUdt.addChange(tx, changeLock, balance - required);
330
+ }
331
+ }
332
+ /** Whether the transaction already carries any input or output. */
333
+ function hasTransactionActivity(tx) {
334
+ return tx.inputs.length > 0 || tx.outputs.length > 0;
335
+ }
336
+ /** An order the market can fill at a gain: priced past the DAO ratio on its matchable side. */
337
+ function isPastPar(group, exchangeRatio) {
338
+ const { order } = group;
339
+ const { info } = order.data;
340
+ return ((order.isCkb2UdtMatchable() && info.ckbToUdt.compare(exchangeRatio) < 0) ||
341
+ (order.isUdt2CkbMatchable() && exchangeRatio.compare(info.udtToCkb) < 0));
342
+ }
343
+ function conversionFailure(reason, estimatedMaturity) {
344
+ return { ok: false, reason, estimatedMaturity };
345
+ }
346
+ /** A plan always carries a deposit or an order, else it would be a collection. */
347
+ function conversionKind(hasDirect, hasOrder) {
348
+ if (hasDirect && hasOrder) {
349
+ return "direct-plus-order";
350
+ }
351
+ return hasDirect ? "direct" : "order";
352
+ }
353
+ /** Whether every liquid cell became an input; false when the input limit cut the sweep. */
354
+ function sweepsAll(tx, cells) {
355
+ const spent = new Set(tx.inputs.map((input) => input.previousOutput.toHex()));
356
+ return cells.every((cell) => spent.has(cell.outPoint.toHex()));
357
+ }
358
+ async function isOwnLock(signer, lock) {
359
+ return (await signer.getAddressObjs()).some(({ script }) => script.eq(lock));
360
+ }
361
+ function udtBalance(cell) {
362
+ return ccc.udtBalanceFrom(cell.outputData);
363
+ }
364
+ /** Adds cells while the input count stays under the limit; returns how many were added. */
365
+ function sweep(tx, cells) {
366
+ const added = Math.min(cells.length, Math.max(0, SWEEP_INPUT_LIMIT - tx.inputs.length));
367
+ for (const cell of cells.slice(0, added)) {
368
+ tx.addInput(cell);
369
+ }
370
+ return added;
371
+ }
372
+ /** Completes the fee, adding reserve cells one at a time while capacity is short. */
373
+ async function completeFee(tx, signer, changeLock, feeRate, reserve) {
374
+ const remaining = [...reserve];
375
+ for (;;) {
376
+ try {
377
+ await tx.completeFeeChangeToLock(signer, changeLock, feeRate, undefined, {
378
+ shouldAddInputs: false,
379
+ });
380
+ return;
198
381
  }
199
- const tipEpoch = Epoch.from(tip.epoch);
200
- const oneCycle = Epoch.from([180n, 0n, 1n]);
201
- if (poolSnapshotHex !== "0x") {
202
- const eNumber = tip.epoch[0];
203
- let start = Epoch.from([eNumber - (eNumber % 180n), 0n, 1n]);
204
- const step = Epoch.from([0n, 180n, 1024n]);
205
- const depositSize = convert(false, ICKB_DEPOSIT_CAP, tip);
206
- for (const binAmount of PoolSnapshot.decode(poolSnapshotHex)) {
207
- const end = start.add(step);
208
- if (binAmount > 0) {
209
- ckbMaturing.push({
210
- ckbValue: BigInt(binAmount) * depositSize,
211
- maturity: tipEpoch.compare(tipEpoch) < 0
212
- ?
213
- end.add(oneCycle).toUnix(tip)
214
- :
215
- end.toUnix(tip),
216
- });
217
- }
218
- start = end;
382
+ catch (error) {
383
+ if (!(error instanceof ccc.ErrorTransactionInsufficientCapacity)) {
384
+ throw error;
219
385
  }
220
- }
221
- else {
222
- for await (const d of this.ickbLogic.findDeposits(client, opts)) {
223
- ckbMaturing.push({
224
- ckbValue: d.ckbValue,
225
- maturity: d.maturity.toUnix(tip),
386
+ const cell = remaining.shift();
387
+ if (cell === undefined) {
388
+ throw new IckbError(error.message, {
389
+ code: "insufficient_capacity",
390
+ cause: error,
226
391
  });
227
392
  }
393
+ tx.addInput(cell);
228
394
  }
229
- ckbMaturing.sort((a, b) => Number(a.maturity - b.maturity));
230
- let cumulative = 0n;
231
- const ckbCumulativeMaturing = [];
232
- for (const { ckbValue, maturity } of ckbMaturing) {
233
- cumulative += ckbValue;
234
- ckbCumulativeMaturing.push({ ckbCumulative: cumulative, maturity });
395
+ }
396
+ }
397
+ /** Typed SDK failure with a stable machine-readable code. */
398
+ export class IckbError extends Error {
399
+ /** Stable failure code for callers and observability. */
400
+ code;
401
+ /** Creates a typed SDK failure while preserving its cause. */
402
+ constructor(message, options) {
403
+ super(message, options);
404
+ this.name = "IckbError";
405
+ this.code = options.code;
406
+ }
407
+ }
408
+ /**
409
+ * Completes the first candidate that the real completer can fund.
410
+ *
411
+ * @remarks
412
+ * Only completion knows what a transaction costs once markers, remainder orders, change, and
413
+ * fee are in, so no count is computed up front: each candidate is built and completed in turn.
414
+ * Capacity, DAO output-limit and DAO header-index failures advance
415
+ * the walk; transport, scan, signer, and malformed-transaction errors propagate. Exhausting
416
+ * the candidates throws the last advancing failure.
417
+ */
418
+ export async function completeFirstFundable(candidates, build, complete) {
419
+ let error;
420
+ for (const candidate of candidates) {
421
+ try {
422
+ return { candidate, tx: await complete(build(candidate)) };
423
+ }
424
+ catch (failure) {
425
+ if (!isFundabilityFailure(failure)) {
426
+ throw failure;
427
+ }
428
+ error = failure;
235
429
  }
236
- return {
237
- ckbAvailable,
238
- ckbMaturing: ckbCumulativeMaturing,
239
- };
240
430
  }
431
+ throw error ?? new Error("No candidate could be completed");
432
+ }
433
+ /**
434
+ * A failure the walk advances past: the candidate costs more than the account funds, or
435
+ * needs more DAO outputs or deposit-header slots than one transaction has.
436
+ */
437
+ export function isFundabilityFailure(error) {
438
+ return (error instanceof IckbError ||
439
+ error instanceof ccc.ErrorTransactionInsufficientCapacity ||
440
+ error instanceof DaoOutputLimitError ||
441
+ error instanceof DaoHeaderIndexError);
241
442
  }
242
443
  //# sourceMappingURL=sdk.js.map