@ar.io/sdk 3.24.0 → 4.0.0-alpha.2

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