@ar.io/sdk 3.24.0 → 4.0.0-alpha.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.
Files changed (169) hide show
  1. package/README.md +682 -600
  2. package/lib/esm/cli/cli.js +188 -152
  3. package/lib/esm/cli/commands/antCommands.js +23 -58
  4. package/lib/esm/cli/commands/arnsPurchaseCommands.js +48 -30
  5. package/lib/esm/cli/commands/escrowCommands.js +221 -0
  6. package/lib/esm/cli/commands/gatewayWriteCommands.js +142 -23
  7. package/lib/esm/cli/commands/pruneCommands.js +150 -0
  8. package/lib/esm/cli/commands/readCommands.js +22 -3
  9. package/lib/esm/cli/commands/transfer.js +6 -6
  10. package/lib/esm/cli/options.js +124 -58
  11. package/lib/esm/cli/utils.js +280 -174
  12. package/lib/esm/common/ant-registry.js +17 -143
  13. package/lib/esm/common/ant.js +44 -1167
  14. package/lib/esm/common/faucet.js +11 -6
  15. package/lib/esm/common/index.js +0 -4
  16. package/lib/esm/common/io.js +25 -1412
  17. package/lib/esm/constants.js +13 -19
  18. package/lib/esm/solana/ant-readable.js +724 -0
  19. package/lib/esm/solana/ant-registry-readable.js +133 -0
  20. package/lib/esm/solana/ant-registry-writeable.js +472 -0
  21. package/lib/esm/solana/ant-writeable.js +384 -0
  22. package/lib/esm/solana/ata.js +70 -0
  23. package/lib/esm/solana/canonical-message.js +128 -0
  24. package/lib/esm/solana/clusters.js +111 -0
  25. package/lib/esm/solana/constants.js +146 -0
  26. package/lib/esm/solana/delegation-math.js +112 -0
  27. package/lib/esm/solana/deserialize.js +711 -0
  28. package/lib/esm/solana/escrow.js +839 -0
  29. package/lib/{cjs/utils/json.js → esm/solana/events.js} +15 -10
  30. package/lib/esm/solana/funding-plan.js +699 -0
  31. package/lib/esm/solana/index.js +126 -0
  32. package/lib/esm/solana/instruction.js +39 -0
  33. package/lib/esm/solana/io-readable.js +2182 -0
  34. package/lib/esm/solana/io-writeable.js +3196 -0
  35. package/lib/esm/solana/json-rpc.js +90 -0
  36. package/lib/esm/solana/metadata.js +81 -0
  37. package/lib/esm/solana/mpl-core.js +192 -0
  38. package/lib/esm/solana/pda.js +332 -0
  39. package/lib/esm/solana/predict-prescribed-observers.js +110 -0
  40. package/lib/esm/solana/retry.js +117 -0
  41. package/lib/esm/solana/rpc-circuit-breaker.js +258 -0
  42. package/lib/esm/solana/send.js +372 -0
  43. package/lib/esm/solana/spawn-ant.js +224 -0
  44. package/lib/esm/solana/types.js +1 -0
  45. package/lib/esm/types/ant.js +27 -15
  46. package/lib/esm/types/io.js +8 -11
  47. package/lib/esm/utils/ant.js +0 -63
  48. package/lib/esm/utils/index.js +0 -3
  49. package/lib/esm/version.js +1 -1
  50. package/lib/types/cli/commands/antCommands.d.ts +5 -13
  51. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +33 -7
  52. package/lib/types/cli/commands/escrowCommands.d.ts +68 -0
  53. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +12 -11
  54. package/lib/types/cli/commands/pruneCommands.d.ts +31 -0
  55. package/lib/types/cli/commands/readCommands.d.ts +27 -22
  56. package/lib/types/cli/commands/transfer.d.ts +9 -9
  57. package/lib/types/cli/options.d.ts +76 -21
  58. package/lib/types/cli/types.d.ts +11 -13
  59. package/lib/types/cli/utils.d.ts +71 -31
  60. package/lib/types/common/ant-registry.d.ts +49 -47
  61. package/lib/types/common/ant.d.ts +54 -539
  62. package/lib/types/common/faucet.d.ts +20 -8
  63. package/lib/types/common/index.d.ts +0 -3
  64. package/lib/types/common/io.d.ts +51 -263
  65. package/lib/types/constants.d.ts +11 -18
  66. package/lib/types/solana/ant-readable.d.ts +180 -0
  67. package/lib/types/solana/ant-registry-readable.d.ts +105 -0
  68. package/lib/types/solana/ant-registry-writeable.d.ts +249 -0
  69. package/lib/types/solana/ant-writeable.d.ts +177 -0
  70. package/lib/types/solana/ata.d.ts +44 -0
  71. package/lib/types/solana/canonical-message.d.ts +121 -0
  72. package/lib/types/solana/clusters.d.ts +109 -0
  73. package/lib/types/solana/constants.d.ts +119 -0
  74. package/lib/types/solana/delegation-math.d.ts +45 -0
  75. package/lib/types/solana/deserialize.d.ts +262 -0
  76. package/lib/types/solana/escrow.d.ts +480 -0
  77. package/lib/types/solana/events.d.ts +38 -0
  78. package/lib/types/solana/funding-plan.d.ts +225 -0
  79. package/lib/types/solana/index.d.ts +87 -0
  80. package/lib/types/solana/instruction.d.ts +39 -0
  81. package/lib/types/solana/io-readable.d.ts +499 -0
  82. package/lib/types/solana/io-writeable.d.ts +893 -0
  83. package/lib/types/solana/json-rpc.d.ts +47 -0
  84. package/lib/types/solana/metadata.d.ts +84 -0
  85. package/lib/types/solana/mpl-core.d.ts +120 -0
  86. package/lib/types/solana/pda.d.ts +95 -0
  87. package/lib/types/solana/predict-prescribed-observers.d.ts +28 -0
  88. package/lib/types/solana/retry.d.ts +62 -0
  89. package/lib/types/solana/rpc-circuit-breaker.d.ts +78 -0
  90. package/lib/types/solana/send.d.ts +94 -0
  91. package/lib/types/solana/spawn-ant.d.ts +145 -0
  92. package/lib/types/solana/types.d.ts +82 -0
  93. package/lib/types/types/ant-registry.d.ts +43 -4
  94. package/lib/types/types/ant.d.ts +114 -96
  95. package/lib/types/types/common.d.ts +18 -74
  96. package/lib/types/types/faucet.d.ts +2 -2
  97. package/lib/types/types/io.d.ts +244 -158
  98. package/lib/types/types/token.d.ts +0 -12
  99. package/lib/types/utils/ant.d.ts +1 -12
  100. package/lib/types/utils/index.d.ts +0 -3
  101. package/lib/types/version.d.ts +1 -1
  102. package/package.json +36 -33
  103. package/lib/cjs/cli/cli.js +0 -822
  104. package/lib/cjs/cli/commands/antCommands.js +0 -113
  105. package/lib/cjs/cli/commands/arnsPurchaseCommands.js +0 -212
  106. package/lib/cjs/cli/commands/gatewayWriteCommands.js +0 -210
  107. package/lib/cjs/cli/commands/readCommands.js +0 -215
  108. package/lib/cjs/cli/commands/transfer.js +0 -159
  109. package/lib/cjs/cli/options.js +0 -470
  110. package/lib/cjs/cli/types.js +0 -2
  111. package/lib/cjs/cli/utils.js +0 -639
  112. package/lib/cjs/common/ant-registry.js +0 -155
  113. package/lib/cjs/common/ant-versions.js +0 -93
  114. package/lib/cjs/common/ant.js +0 -1182
  115. package/lib/cjs/common/arweave.js +0 -27
  116. package/lib/cjs/common/contracts/ao-process.js +0 -224
  117. package/lib/cjs/common/error.js +0 -64
  118. package/lib/cjs/common/faucet.js +0 -150
  119. package/lib/cjs/common/hyperbeam/hb.js +0 -173
  120. package/lib/cjs/common/index.js +0 -42
  121. package/lib/cjs/common/io.js +0 -1423
  122. package/lib/cjs/common/logger.js +0 -83
  123. package/lib/cjs/common/loggers/winston.js +0 -68
  124. package/lib/cjs/common/marketplace.js +0 -731
  125. package/lib/cjs/common/turbo.js +0 -223
  126. package/lib/cjs/constants.js +0 -41
  127. package/lib/cjs/node/index.js +0 -39
  128. package/lib/cjs/package.json +0 -1
  129. package/lib/cjs/types/ant-registry.js +0 -2
  130. package/lib/cjs/types/ant.js +0 -168
  131. package/lib/cjs/types/common.js +0 -2
  132. package/lib/cjs/types/faucet.js +0 -2
  133. package/lib/cjs/types/index.js +0 -37
  134. package/lib/cjs/types/io.js +0 -51
  135. package/lib/cjs/types/token.js +0 -116
  136. package/lib/cjs/utils/ant.js +0 -108
  137. package/lib/cjs/utils/ao.js +0 -432
  138. package/lib/cjs/utils/arweave.js +0 -285
  139. package/lib/cjs/utils/base64.js +0 -62
  140. package/lib/cjs/utils/hash.js +0 -56
  141. package/lib/cjs/utils/index.js +0 -38
  142. package/lib/cjs/utils/processes.js +0 -173
  143. package/lib/cjs/utils/random.js +0 -30
  144. package/lib/cjs/utils/schema.js +0 -15
  145. package/lib/cjs/utils/url.js +0 -37
  146. package/lib/cjs/version.js +0 -20
  147. package/lib/cjs/web/index.js +0 -41
  148. package/lib/esm/common/ant-versions.js +0 -87
  149. package/lib/esm/common/arweave.js +0 -21
  150. package/lib/esm/common/contracts/ao-process.js +0 -220
  151. package/lib/esm/common/hyperbeam/hb.js +0 -169
  152. package/lib/esm/common/marketplace.js +0 -724
  153. package/lib/esm/common/turbo.js +0 -215
  154. package/lib/esm/node/index.js +0 -20
  155. package/lib/esm/utils/ao.js +0 -420
  156. package/lib/esm/utils/arweave.js +0 -271
  157. package/lib/esm/utils/processes.js +0 -167
  158. package/lib/esm/web/index.js +0 -20
  159. package/lib/types/common/ant-versions.d.ts +0 -39
  160. package/lib/types/common/arweave.d.ts +0 -17
  161. package/lib/types/common/contracts/ao-process.d.ts +0 -47
  162. package/lib/types/common/hyperbeam/hb.d.ts +0 -88
  163. package/lib/types/common/marketplace.d.ts +0 -568
  164. package/lib/types/common/turbo.d.ts +0 -61
  165. package/lib/types/node/index.d.ts +0 -20
  166. package/lib/types/utils/ao.d.ts +0 -80
  167. package/lib/types/utils/arweave.d.ts +0 -79
  168. package/lib/types/utils/processes.d.ts +0 -39
  169. package/lib/types/web/index.d.ts +0 -20
@@ -1,731 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ArNSMarketplaceWrite = exports.ArNSMarketplaceRead = void 0;
4
- exports.calculateListingFee = calculateListingFee;
5
- exports.calculateSaleTax = calculateSaleTax;
6
- /**
7
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
- *
9
- * Licensed under the Apache License, Version 2.0 (the "License");
10
- * you may not use this file except in compliance with the License.
11
- * You may obtain a copy of the License at
12
- *
13
- * http://www.apache.org/licenses/LICENSE-2.0
14
- *
15
- * Unless required by applicable law or agreed to in writing, software
16
- * distributed under the License is distributed on an "AS IS" BASIS,
17
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- * See the License for the specific language governing permissions and
19
- * limitations under the License.
20
- */
21
- const index_js_1 = require("../node/index.js");
22
- /**
23
- * Read-only client for the ArNS marketplace
24
- * @experimental
25
- */
26
- class ArNSMarketplaceRead {
27
- process;
28
- logger;
29
- constructor({ process = new index_js_1.AOProcess({
30
- processId: index_js_1.MARKETPLACE_CONTRACT_ID,
31
- }), logger = index_js_1.Logger.default, }) {
32
- this.process = process;
33
- this.logger = logger;
34
- }
35
- async getInfo() {
36
- return this.process.read({
37
- tags: [{ name: 'Action', value: 'Info' }],
38
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Info-Notice'),
39
- });
40
- }
41
- async getPaginatedIntents({ cursor, limit, sortBy, sortOrder, filters, } = {}) {
42
- const tags = [
43
- { name: 'Action', value: 'Get-Paginated-Intents' },
44
- { name: 'Cursor', value: cursor },
45
- { name: 'Limit', value: limit?.toString() },
46
- { name: 'Sort-By', value: sortBy },
47
- { name: 'Sort-Order', value: sortOrder },
48
- { name: 'Filters', value: JSON.stringify(filters) },
49
- ];
50
- const filteredTags = tags.filter((tag) => tag.value !== undefined);
51
- return this.process.read({
52
- tags: filteredTags,
53
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' &&
54
- tag.value === 'Get-Paginated-Intents-Notice'),
55
- });
56
- }
57
- async getIntent(intentId) {
58
- return this.process.read({
59
- tags: [
60
- { name: 'Action', value: 'Get-Intent-By-Id' },
61
- { name: 'Intent-Id', value: intentId },
62
- ],
63
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Get-Intent-By-Id-Notice'),
64
- });
65
- }
66
- async getIntentByANTId(antId) {
67
- const res = await this.getPaginatedIntents({
68
- filters: {
69
- antProcessId: antId,
70
- },
71
- });
72
- if (res.items.length === 0) {
73
- throw new Error(`No intent found for ANT ID: ${antId}`);
74
- }
75
- return res.items[0];
76
- }
77
- /**
78
- * Get orders with flexible selectors
79
- * @param params - Parameters for filtering and pagination
80
- * @returns Orders matching the criteria
81
- */
82
- async getPaginatedOrders(params) {
83
- const tags = [
84
- { name: 'Action', value: 'Get-Orders' },
85
- { name: 'Status', value: params?.status },
86
- { name: 'Ids', value: params?.ids?.join(',') },
87
- { name: 'Dominant-Token', value: params?.dominantToken },
88
- { name: 'Swap-Token', value: params?.swapToken },
89
- { name: 'Cursor', value: params?.cursor },
90
- { name: 'Limit', value: params?.limit?.toString() },
91
- { name: 'Sort-By', value: params?.sortBy },
92
- { name: 'Sort-Order', value: params?.sortOrder },
93
- {
94
- name: 'Filters',
95
- value: params?.filters ? JSON.stringify(params.filters) : undefined,
96
- },
97
- ];
98
- const filteredTags = tags.filter((tag) => tag.value !== undefined);
99
- return this.process.read({
100
- tags: filteredTags,
101
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Get-Orders-Notice'),
102
- });
103
- }
104
- /**
105
- * Get a single order by ID
106
- * @param orderId - The order ID to fetch
107
- * @returns The order if found
108
- */
109
- async getOrder(orderId) {
110
- return this.process.read({
111
- tags: [
112
- { name: 'Action', value: 'Get-Order' },
113
- { name: 'Order-Id', value: orderId },
114
- ],
115
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Get-Order-Notice'),
116
- });
117
- }
118
- async getOrderByANTId(antId) {
119
- const res = await this.getPaginatedOrders({
120
- dominantToken: antId,
121
- });
122
- if (res.items.length === 0) {
123
- throw new Error(`No order found for ANT ID: ${antId}`);
124
- }
125
- // Strange behaviour here. It seems that the filter logic will return an order with potentially different dominant token.
126
- const order = res.items[0];
127
- if (order.dominantToken !== antId) {
128
- throw new Error(`No order for ANT ID: ${antId}`);
129
- }
130
- return res.items[0];
131
- }
132
- async getPaginatedMarketplaceBalances(params) {
133
- return this.process.read({
134
- tags: [
135
- { name: 'Action', value: 'Get-Paginated-Balances' },
136
- ...(0, index_js_1.paginationParamsToTags)(params),
137
- ],
138
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' &&
139
- tag.value === 'Get-Paginated-Balances-Notice'),
140
- });
141
- }
142
- /**
143
- * Get ARIO balance for an address in the marketplace
144
- */
145
- async getMarketplaceBalance({ address, }) {
146
- return this.process.read({
147
- tags: [
148
- { name: 'Action', value: 'Get-Balance' },
149
- { name: 'Address', value: address },
150
- ],
151
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Get-Balance-Notice'),
152
- });
153
- }
154
- async getUserAssets({ address, arioProcessId, }) {
155
- async function fetchIntents(context) {
156
- const intents = [];
157
- // fetch all intents for user, paginating as needed and adding each ant id to the set
158
- let intentsCursor = undefined;
159
- let intentsHasMore = true;
160
- while (intentsHasMore) {
161
- const intentsRes = await context.getPaginatedIntents({
162
- cursor: intentsCursor,
163
- limit: 1000,
164
- filters: {
165
- initiator: address,
166
- },
167
- });
168
- intentsRes.items.forEach((intent) => {
169
- intents.push(intent);
170
- });
171
- intentsCursor = intentsRes.nextCursor;
172
- intentsHasMore = intentsRes.hasMore;
173
- }
174
- return intents;
175
- }
176
- async function fetchOrders(context) {
177
- const orders = [];
178
- // fetch all orders for user, paginating as needed
179
- let ordersCursor = undefined;
180
- let ordersHasMore = true;
181
- while (ordersHasMore) {
182
- const ordersRes = await context.getPaginatedOrders({
183
- cursor: ordersCursor,
184
- limit: 1000,
185
- filters: {
186
- creator: address,
187
- },
188
- });
189
- ordersRes.items.forEach((order) => {
190
- orders.push(order);
191
- });
192
- ordersCursor = ordersRes.nextCursor;
193
- ordersHasMore = ordersRes.hasMore;
194
- }
195
- return orders;
196
- }
197
- // parallel fetch balances, intents, and orders
198
- const [balances, intents, orders] = await Promise.all([
199
- this.getMarketplaceBalance({ address }),
200
- fetchIntents(this),
201
- fetchOrders(this),
202
- ]);
203
- const antIdsArray = Array.from(new Set([
204
- ...intents.map((intent) => intent.antProcessId),
205
- ...orders.map((order) => order.dominantToken),
206
- ...orders.map((order) => order.swapToken),
207
- ])).filter((antId) => antId !== arioProcessId); // since we add both swap and dominant token for simplicity, we need to filter out the ario token
208
- return { intents, orders, balances, antIds: antIdsArray };
209
- }
210
- }
211
- exports.ArNSMarketplaceRead = ArNSMarketplaceRead;
212
- /**
213
- * Write client for the ArNS marketplace
214
- * @experimental
215
- */
216
- class ArNSMarketplaceWrite extends ArNSMarketplaceRead {
217
- process;
218
- signer;
219
- ario;
220
- constructor({ process = new index_js_1.AOProcess({
221
- processId: index_js_1.MARKETPLACE_CONTRACT_ID,
222
- }), signer, ario, logger = index_js_1.Logger.default, }) {
223
- super({ process: process, logger: logger });
224
- this.process = process;
225
- this.signer = signer;
226
- this.ario = ario;
227
- this.logger = logger;
228
- }
229
- /**
230
- * Deposit ARIO to the marketplace (simulates Credit-Notice from ARIO token process)
231
- * Returns the message ID for verification
232
- */
233
- async depositArIO(params) {
234
- return this.ario.transfer({
235
- // the marketplace process id is the target
236
- target: this.process.processId,
237
- qty: Number(params.amount),
238
- }, {
239
- tags: [{ name: 'X-Action', value: 'Deposit' }],
240
- });
241
- }
242
- /**
243
- * Withdraw ARIO from the marketplace back to user
244
- */
245
- async withdrawArIO(params) {
246
- return this.process.send({
247
- tags: [
248
- { name: 'Action', value: 'Withdraw-Ario' },
249
- { name: 'Quantity', value: params.amount },
250
- ],
251
- signer: this.signer,
252
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Withdraw-Ario-Notice'),
253
- });
254
- }
255
- async createIntent({ antId, orderType, quantity, price, expirationTime, minimumPrice, decreaseInterval, }) {
256
- const tags = [
257
- { name: 'Action', value: 'Create-Intent' },
258
- { name: 'X-Intent-ANT-Id', value: antId },
259
- { name: 'X-Intent-Order-Type', value: orderType },
260
- { name: 'X-Intent-Quantity', value: quantity },
261
- { name: 'X-Intent-Price', value: price },
262
- { name: 'X-Intent-Expiration-Time', value: expirationTime },
263
- { name: 'X-Intent-Minimum-Price', value: minimumPrice },
264
- { name: 'X-Intent-Decrease-Interval', value: decreaseInterval },
265
- ];
266
- const filteredTags = tags.filter((tag) => tag.value !== undefined);
267
- return this.process.send({
268
- tags: filteredTags,
269
- signer: this.signer,
270
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Create-Intent-Notice'),
271
- });
272
- }
273
- async pushANTIntentResolution(intentId) {
274
- return this.process.send({
275
- tags: [
276
- { name: 'Action', value: 'Push-ANT-Intent-Resolution' },
277
- { name: 'X-Intent-Id', value: intentId },
278
- ],
279
- signer: this.signer,
280
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' &&
281
- tag.value === 'Push-ANT-Intent-Resolution-Notice'),
282
- });
283
- }
284
- async settleAuction(params) {
285
- const tags = [
286
- { name: 'Action', value: 'Settle-Auction' },
287
- { name: 'Order-Id', value: params.orderId },
288
- { name: 'Dominant-Token', value: params.dominantToken },
289
- { name: 'Swap-Token', value: params.swapToken },
290
- ];
291
- const filteredTags = tags.filter((tag) => tag.value !== undefined);
292
- return this.process.send({
293
- tags: filteredTags,
294
- signer: this.signer,
295
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Settle-Auction-Notice'),
296
- });
297
- }
298
- async listNameForSale({ name, expirationTime, price, type, walletAddress, minimumPrice, decreaseInterval, onProgress = (event) => {
299
- this.logger.info(`List name for sale progress: ${event.step}`);
300
- }, }, timeoutOptions) {
301
- const maxRetries = timeoutOptions?.maxRetries ?? 15;
302
- const statusPollIntervalMs = timeoutOptions?.statusPollIntervalMs ?? 3000;
303
- // Get arns record for the current ant id associated with it
304
- const record = await this.ario.getArNSRecord({ name: name });
305
- this.logger.info(`Record ${name} found: ${JSON.stringify(record)}`);
306
- if (record === undefined) {
307
- throw new Error(`Record ${name} not found`);
308
- }
309
- const antId = record.processId;
310
- this.logger.info(`ANT ID for ${name} found: ${antId}`);
311
- const ant = index_js_1.ANT.init({
312
- process: new index_js_1.AOProcess({
313
- processId: antId,
314
- ao: this.process.ao,
315
- logger: this.logger,
316
- }),
317
- signer: this.signer,
318
- });
319
- const antState = await ant.getState();
320
- if (antState.Owner !== walletAddress) {
321
- this.logger.error(`Wallet address ${walletAddress} does not match the owner of the ANT ${antId}. Only the owner can list the name for sale.`);
322
- throw new Error('Wallet address does not match the owner of the ANT. Only the owner can list the name for sale.');
323
- }
324
- let intent;
325
- const createIntentEventData = {
326
- name,
327
- antId,
328
- orderType: type,
329
- price,
330
- expirationTime,
331
- };
332
- try {
333
- onProgress({
334
- step: 'creating-intent',
335
- ...createIntentEventData,
336
- });
337
- const intentResult = await this.createIntent({
338
- antId,
339
- orderType: type,
340
- quantity: price,
341
- expirationTime: expirationTime.toString(),
342
- price: price,
343
- minimumPrice: minimumPrice,
344
- decreaseInterval: decreaseInterval,
345
- });
346
- if (intentResult.result === undefined) {
347
- throw new Error('Failed to create intent: ' + intentResult.id);
348
- }
349
- this.logger.info(`Intent created: ${JSON.stringify(intentResult.result)}`);
350
- intent = intentResult.result;
351
- onProgress({
352
- step: 'intent-created',
353
- ...createIntentEventData,
354
- intent,
355
- });
356
- }
357
- catch (error) {
358
- this.logger.error(`Error creating intent: ${error.message}`);
359
- // check error for existing intent. Will be a contract error message.
360
- const isExistingIntentError = error.message.includes('An intent already exists for this ANT ID');
361
- if (isExistingIntentError) {
362
- let fetchedIntent;
363
- let lastIntentError = null;
364
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
365
- try {
366
- fetchedIntent = await this.getIntentByANTId(antId);
367
- lastIntentError = null;
368
- break;
369
- }
370
- catch (getIntentError) {
371
- lastIntentError = getIntentError;
372
- this.logger.error(`Failed to get intent (attempt ${attempt + 1}/${maxRetries + 1}): ${getIntentError.message}`);
373
- if (attempt < maxRetries) {
374
- const backoffMs = statusPollIntervalMs * Math.pow(2, attempt);
375
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
376
- }
377
- }
378
- }
379
- if (lastIntentError !== null || fetchedIntent === undefined) {
380
- const intentError = new Error('An intent already exists for this ANT ID but failed to get intent:\n\n' +
381
- (lastIntentError?.message ?? 'Unknown error'));
382
- onProgress({
383
- step: 'error',
384
- name,
385
- antId,
386
- error: intentError,
387
- failedStep: 'creating-intent',
388
- });
389
- throw intentError;
390
- }
391
- intent = fetchedIntent;
392
- }
393
- else {
394
- // Possible to get other errors, eg insufficient deposited ario balance. Rethrow them here.
395
- onProgress({
396
- step: 'error',
397
- name,
398
- antId,
399
- error: error,
400
- failedStep: 'creating-intent',
401
- });
402
- throw error;
403
- }
404
- }
405
- // Type guard to ensure intent is defined
406
- if (intent === undefined) {
407
- const intentError = new Error('Failed to create intent');
408
- onProgress({
409
- step: 'error',
410
- name,
411
- antId,
412
- error: intentError,
413
- failedStep: 'creating-intent',
414
- });
415
- throw intentError;
416
- }
417
- const transferAntEventData = {
418
- name,
419
- antId,
420
- intentId: intent.intentId,
421
- marketplaceProcessId: this.process.processId,
422
- };
423
- let antTransferResult;
424
- try {
425
- onProgress({
426
- step: 'transferring-ant',
427
- ...transferAntEventData,
428
- });
429
- let transferResult;
430
- let lastTransferError = null;
431
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
432
- try {
433
- transferResult = await ant.transfer({
434
- target: this.process.processId,
435
- removeControllers: false, // important: do not remove the controllers of the ANT to prevent loss of control
436
- }, {
437
- tags: [{ name: 'X-Intent-Id', value: intent.intentId }],
438
- });
439
- lastTransferError = null;
440
- break;
441
- }
442
- catch (error) {
443
- lastTransferError = error;
444
- this.logger.error(`Failed to transfer ANT (attempt ${attempt + 1}/${maxRetries + 1}): ${error.message}`);
445
- if (attempt < maxRetries) {
446
- const backoffMs = statusPollIntervalMs * Math.pow(2, attempt);
447
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
448
- }
449
- }
450
- }
451
- if (lastTransferError !== null || transferResult === undefined) {
452
- throw lastTransferError ?? new Error('Failed to transfer ANT');
453
- }
454
- antTransferResult = transferResult;
455
- this.logger.info(`ANT transferred: ${JSON.stringify(antTransferResult)}`);
456
- onProgress({
457
- step: 'ant-transferred',
458
- ...transferAntEventData,
459
- transferResult: antTransferResult,
460
- });
461
- }
462
- catch (error) {
463
- this.logger.error(`Failed to transfer ANT: ${error.message}`);
464
- onProgress({
465
- step: 'error',
466
- name,
467
- antId,
468
- error: error,
469
- failedStep: 'transferring-ant',
470
- intent,
471
- });
472
- return {
473
- intent,
474
- order: null,
475
- antTransferResult: null,
476
- error: error,
477
- };
478
- }
479
- // poll for the order to be created
480
- // This is to ensure the order is created before returning the result for ux purposes.
481
- // This may still fail, in which case we return the intent and ant transfer result and handle the error in the client.
482
- let order = null;
483
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
484
- try {
485
- order = await this.getOrderByANTId(antId).catch((error) => {
486
- this.logger.warn(`Failed to get order: ${error.message}`);
487
- return null;
488
- });
489
- if (order !== null) {
490
- break;
491
- }
492
- if (attempt < maxRetries) {
493
- this.logger.info(`Waiting for order to be created...`);
494
- const backoffMs = statusPollIntervalMs * Math.pow(2, attempt);
495
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
496
- }
497
- }
498
- catch (error) {
499
- this.logger.error(`Failed to get order: ${error.message}`);
500
- const orderError = new Error('Failed to get order: ' + error.message);
501
- onProgress({
502
- step: 'error',
503
- name,
504
- antId,
505
- error: orderError,
506
- failedStep: 'transferring-ant',
507
- intent,
508
- });
509
- return {
510
- intent,
511
- order: null,
512
- antTransferResult,
513
- error: orderError,
514
- };
515
- }
516
- }
517
- if (order === null) {
518
- this.logger.error(`Failed to get order`);
519
- const orderError = new Error('Failed to get order');
520
- onProgress({
521
- step: 'error',
522
- name,
523
- antId,
524
- error: orderError,
525
- failedStep: 'transferring-ant',
526
- intent,
527
- });
528
- return {
529
- intent,
530
- order: null,
531
- antTransferResult,
532
- error: orderError,
533
- };
534
- }
535
- onProgress({
536
- step: 'complete',
537
- name,
538
- antId,
539
- intent,
540
- order,
541
- transferResult: antTransferResult,
542
- });
543
- return { intent, order, antTransferResult, error: null };
544
- }
545
- async cancelOrder(orderId) {
546
- const tags = [
547
- { name: 'Action', value: 'Cancel-Order' },
548
- { name: 'Order-Id', value: orderId },
549
- ];
550
- return this.process.send({
551
- tags,
552
- signer: this.signer,
553
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Cancel-Order-Notice'),
554
- });
555
- }
556
- async createOrder({ swapToken, quantity, orderType, price, expirationTime, minimumPrice, decreaseInterval, transferDenomination, }) {
557
- const tags = [
558
- { name: 'Action', value: 'Create-Order' },
559
- { name: 'Swap-Token', value: swapToken },
560
- { name: 'Quantity', value: quantity },
561
- { name: 'Order-Type', value: orderType },
562
- { name: 'Price', value: price },
563
- { name: 'Expiration-Time', value: expirationTime },
564
- { name: 'Minimum-Price', value: minimumPrice },
565
- { name: 'Decrease-Interval', value: decreaseInterval },
566
- { name: 'Transfer-Denomination', value: transferDenomination },
567
- ];
568
- const filteredTags = tags.filter((tag) => tag.value !== undefined);
569
- // Send the message
570
- return this.process.send({
571
- tags: filteredTags,
572
- signer: this.signer,
573
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' && tag.value === 'Create-Order-Notice'),
574
- });
575
- }
576
- async buyFixedPriceANT(params) {
577
- const order = await this.getOrderByANTId(params.antId);
578
- if (order === undefined) {
579
- throw new Error(`No active sell order found for ANT: ${params.antId}`);
580
- }
581
- if (order.status !== 'active') {
582
- throw new Error(`Order status is ${order.status}, must be active`);
583
- }
584
- if (order.price === undefined) {
585
- throw new Error(`Order price is undefined for ANT: ${params.antId}`);
586
- }
587
- // Create a buy order that matches the sell order
588
- // This should trigger immediate execution if prices match
589
- // For ArNS: buying 1 ANT, so quantity = price = total cost
590
- return this.createOrder({
591
- swapToken: params.antId,
592
- quantity: order.price, // Total ARIO cost
593
- orderType: 'fixed',
594
- price: order.price, // Match their asking price
595
- });
596
- }
597
- async buyDutchAuctionANT(params) {
598
- const order = await this.getOrderByANTId(params.antId);
599
- if (order === undefined) {
600
- throw new Error(`No active sell order found for ANT: ${params.antId}`);
601
- }
602
- if (order.status !== 'active') {
603
- throw new Error(`Order status is ${order.status}, must be active`);
604
- }
605
- if (order.orderType !== 'dutch') {
606
- throw new Error(`Order is not a Dutch auction, it's: ${order.orderType}`);
607
- }
608
- if (order.price === undefined) {
609
- throw new Error(`Order starting price is undefined for ANT: ${params.antId}`);
610
- }
611
- // For Dutch auction, the current price will be calculated on execution
612
- return this.createOrder({
613
- swapToken: params.antId,
614
- quantity: order.price,
615
- orderType: 'fixed',
616
- price: order.price,
617
- });
618
- }
619
- /**
620
- * Place a bid on an English auction
621
- * Note: This requires you to have sufficient ARIO balance in the marketplace
622
- */
623
- async bidOnANTEnglishAuction(params) {
624
- const order = await this.getOrderByANTId(params.antId);
625
- if (order === undefined) {
626
- throw new Error(`No active sell order found for ANT: ${params.antId}`);
627
- }
628
- if (order.status !== 'active') {
629
- throw new Error(`Order status is ${order.status}, must be active`);
630
- }
631
- if (order.orderType !== 'english') {
632
- throw new Error(`Order is not an English auction, it's: ${order.orderType}`);
633
- }
634
- // Check if auction has expired
635
- if (order.expirationTime !== undefined &&
636
- Date.now() >= order.expirationTime) {
637
- throw new Error(`Auction has already expired for ANT: ${params.antId}`);
638
- }
639
- return this.process.send({
640
- tags: [
641
- { name: 'Action', value: 'Bid-On-English-Auction' },
642
- { name: 'Order-Id', value: order.id },
643
- { name: 'Bid-Amount', value: params.bidAmount },
644
- ],
645
- signer: this.signer,
646
- select: (message) => message.Tags.some((tag) => tag.name === 'Action' &&
647
- tag.value === 'Bid-On-English-Auction-Notice'),
648
- });
649
- }
650
- /**
651
- * Settle an expired English auction
652
- * Can be called by anyone after the auction expires
653
- * The highest bidder wins the ANT
654
- */
655
- async settleANTEnglishAuction(params) {
656
- const order = await this.getOrderByANTId(params.antId);
657
- if (order === undefined) {
658
- throw new Error(`No active sell order found for ANT: ${params.antId}`);
659
- }
660
- if (order.orderType !== 'english') {
661
- throw new Error(`Order is not an English auction, it's: ${order.orderType}`);
662
- }
663
- // Check if auction has expired
664
- if (order.expirationTime !== undefined &&
665
- Date.now() < order.expirationTime) {
666
- throw new Error(`Auction has not yet expired for ANT: ${params.antId}. Expires at: ${new Date(order.expirationTime).toISOString()}`);
667
- }
668
- return this.settleAuction({
669
- orderId: order.id,
670
- dominantToken: order.dominantToken,
671
- swapToken: order.swapToken,
672
- });
673
- }
674
- }
675
- exports.ArNSMarketplaceWrite = ArNSMarketplaceWrite;
676
- /**
677
- * Calculates the listing fee for an order based on the end timestamp.
678
- * The fee is calculated by rounding up the hours until the end timestamp to the nearest hour.
679
- *
680
- * @experimental
681
- * @param params - Parameters for calculating the listing fee
682
- * @param params.listingFeePerHour - The listing fee per hour in mARIO (as a string)
683
- * @param params.endTimestamp - Unix timestamp when the order expires
684
- * @returns The listing fee in mARIO as a BigInt
685
- *
686
- * @example
687
- * ```typescript
688
- * const info = await marketplace.getInfo();
689
- * const endTimestamp = Date.now() + 24 * 60 * 60 * 1000; // 24 hours from now
690
- * const listingFee = calculateListingFee({
691
- * listingFeePerHour: info.fees.listingFeePerHour,
692
- * endTimestamp,
693
- * });
694
- * ```
695
- */
696
- function calculateListingFee({ listingFeePerHour, endTimestamp, }) {
697
- const now = Date.now();
698
- const millisecondsUntilEnd = endTimestamp - now;
699
- if (millisecondsUntilEnd <= 0) {
700
- return BigInt(0);
701
- }
702
- // Convert milliseconds to hours and round up to the nearest hour
703
- const hoursUntilEnd = Math.ceil(millisecondsUntilEnd / (1000 * 60 * 60));
704
- // Calculate listing fee: hours * fee per hour
705
- return BigInt(hoursUntilEnd) * BigInt(listingFeePerHour);
706
- }
707
- /**
708
- * Calculates the sale tax for an order based on the sale amount.
709
- *
710
- * @experimental
711
- * @param params - Parameters for calculating the sale tax
712
- * @param params.saleAmount - The sale amount in mARIO (as a string or number)
713
- * @param params.saleTaxNumerator - The numerator for sale tax calculation
714
- * @param params.saleTaxDenominator - The denominator for sale tax calculation
715
- * @returns The sale tax in mARIO as a BigInt
716
- *
717
- * @example
718
- * ```typescript
719
- * const info = await marketplace.getInfo();
720
- * const saleAmount = 100000000000; // 100 ARIO in mARIO
721
- * const tax = calculateSaleTax({
722
- * saleAmount,
723
- * saleTaxNumerator: info.fees.saleTaxNumerator,
724
- * saleTaxDenominator: info.fees.saleTaxDenominator,
725
- * });
726
- * ```
727
- */
728
- function calculateSaleTax({ saleAmount, saleTaxNumerator, saleTaxDenominator, }) {
729
- // Calculate tax: (saleAmount * numerator) / denominator
730
- return ((BigInt(saleAmount) * BigInt(saleTaxNumerator)) / BigInt(saleTaxDenominator));
731
- }