@ar.io/sdk 3.22.2 → 3.23.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.
- package/README.md +248 -248
- package/lib/cjs/cli/cli.js +11 -2
- package/lib/cjs/cli/options.js +5 -0
- package/lib/cjs/cli/utils.js +18 -2
- package/lib/cjs/common/ant-registry.js +1 -1
- package/lib/cjs/common/ant.js +10 -1
- package/lib/cjs/common/index.js +1 -0
- package/lib/cjs/common/loggers/winston.js +1 -1
- package/lib/cjs/common/marketplace.js +575 -0
- package/lib/cjs/constants.js +2 -1
- package/lib/cjs/utils/json.js +1 -1
- package/lib/cjs/utils/processes.js +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/cli/cli.js +11 -2
- package/lib/esm/cli/options.js +5 -0
- package/lib/esm/cli/utils.js +18 -2
- package/lib/esm/common/ant-registry.js +1 -1
- package/lib/esm/common/ant.js +10 -1
- package/lib/esm/common/index.js +1 -0
- package/lib/esm/common/loggers/winston.js +1 -1
- package/lib/esm/common/marketplace.js +568 -0
- package/lib/esm/constants.js +1 -0
- package/lib/esm/utils/json.js +1 -1
- package/lib/esm/utils/processes.js +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/types/cli/options.d.ts +5 -0
- package/lib/types/common/ant.d.ts +7 -1
- package/lib/types/common/index.d.ts +1 -0
- package/lib/types/common/marketplace.d.ts +434 -0
- package/lib/types/constants.d.ts +1 -0
- package/lib/types/types/ant.d.ts +1 -0
- package/lib/types/version.d.ts +1 -1
- package/package.json +12 -25
package/lib/esm/cli/utils.js
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
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 { readFileSync } from 'fs';
|
|
1
17
|
/**
|
|
2
18
|
* Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
|
|
3
19
|
*
|
|
@@ -16,7 +32,6 @@
|
|
|
16
32
|
import { EthereumSigner } from '@dha-team/arbundles';
|
|
17
33
|
import { connect } from '@permaweb/aoconnect';
|
|
18
34
|
import { program } from 'commander';
|
|
19
|
-
import { readFileSync } from 'fs';
|
|
20
35
|
import prompts from 'prompts';
|
|
21
36
|
import { ANT, ANTRegistry, ANT_REGISTRY_ID, ANT_REGISTRY_TESTNET_ID, AOProcess, ARIO, ARIOToken, ARIO_DEVNET_PROCESS_ID, ARIO_MAINNET_PROCESS_ID, ARIO_TESTNET_PROCESS_ID, ArweaveSigner, Logger, createAoSigner, fromB64Url, fundFromOptions, initANTStateForAddress, isValidFundFrom, isValidIntent, mARIOToken, sha256B64Url, validIntents, } from '../node/index.js';
|
|
22
37
|
import { globalOptions } from './options.js';
|
|
@@ -129,7 +144,8 @@ export function readARIOFromOptions(options) {
|
|
|
129
144
|
return ARIO.init({
|
|
130
145
|
hyperbeamUrl: options.hyperbeamUrl,
|
|
131
146
|
process: aoProcessFromOptions({
|
|
132
|
-
cuUrl: '
|
|
147
|
+
cuUrl: 'http://localhost:6363', // default to ardrive cu for ARIO process
|
|
148
|
+
//cuUrl: 'https://cu.ardrive.io', // default to ardrive cu for ARIO process
|
|
133
149
|
...options,
|
|
134
150
|
}),
|
|
135
151
|
paymentUrl: options.paymentUrl,
|
|
@@ -108,7 +108,7 @@ export class AoANTRegistryReadable {
|
|
|
108
108
|
Controlled: json.Controlled,
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
|
-
catch (
|
|
111
|
+
catch (_error) {
|
|
112
112
|
retries++;
|
|
113
113
|
this.logger.debug('Failed to fetch ant registry acl for address from hyperbeam', address, retries);
|
|
114
114
|
await new Promise((resolve) => setTimeout(resolve, 1000 * retries ** 2));
|
package/lib/esm/common/ant.js
CHANGED
|
@@ -704,17 +704,26 @@ export class AoANTWriteable extends AoANTReadable {
|
|
|
704
704
|
}
|
|
705
705
|
/**
|
|
706
706
|
* @param target @type {string} The address of the account you want to transfer the ANT to.
|
|
707
|
+
* @param removeControllers @type {boolean} Whether to remove the controllers of the ANT. Default is true.
|
|
708
|
+
* @example
|
|
709
|
+
* ```ts
|
|
710
|
+
* ant.transfer({ target: "fGht8v4STuwPnTck1zFVkQqJh5K9q9Zik4Y5-5dV7nk", removeControllers: false }); // will not remove the controllers of the ANT and just transfer ownership
|
|
711
|
+
* ```
|
|
707
712
|
* @returns {Promise<AoMessageResult>} The result of the interaction.
|
|
708
713
|
* @example
|
|
709
714
|
* ```ts
|
|
710
715
|
* ant.transfer({ target: "fGht8v4STuwPnTck1zFVkQqJh5K9q9Zik4Y5-5dV7nk" });
|
|
711
716
|
* ```
|
|
712
717
|
*/
|
|
713
|
-
async transfer({ target }, options) {
|
|
718
|
+
async transfer({ target, removeControllers = true, }, options) {
|
|
714
719
|
const tags = [
|
|
715
720
|
...(options?.tags ?? []),
|
|
716
721
|
{ name: 'Action', value: 'Transfer' },
|
|
717
722
|
{ name: 'Recipient', value: target },
|
|
723
|
+
{
|
|
724
|
+
name: 'Remove-Controllers',
|
|
725
|
+
value: removeControllers ? 'true' : 'false',
|
|
726
|
+
},
|
|
718
727
|
];
|
|
719
728
|
return this.process.send({
|
|
720
729
|
tags,
|
package/lib/esm/common/index.js
CHANGED
|
@@ -22,7 +22,7 @@ export class WinstonLogger {
|
|
|
22
22
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
23
23
|
this.winston = require('winston');
|
|
24
24
|
}
|
|
25
|
-
catch (
|
|
25
|
+
catch (_error) {
|
|
26
26
|
throw new Error('Winston is not installed. Install it with: npm install winston');
|
|
27
27
|
}
|
|
28
28
|
this.logger = this.winston.createLogger({
|
|
@@ -0,0 +1,568 @@
|
|
|
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
|
+
export class ArNSMarketplaceRead {
|
|
18
|
+
process;
|
|
19
|
+
logger;
|
|
20
|
+
constructor({ process = new AOProcess({
|
|
21
|
+
processId: MARKETPLACE_CONTRACT_ID,
|
|
22
|
+
}), logger = Logger.default, }) {
|
|
23
|
+
this.process = process;
|
|
24
|
+
this.logger = logger;
|
|
25
|
+
}
|
|
26
|
+
async getInfo() {
|
|
27
|
+
return this.process.read({
|
|
28
|
+
tags: [{ name: 'Action', value: 'Info' }],
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async getPaginatedIntents({ cursor, limit, sortBy, sortOrder, filters, } = {}) {
|
|
32
|
+
const tags = [
|
|
33
|
+
{ name: 'Action', value: 'Get-Paginated-Intents' },
|
|
34
|
+
{ name: 'Cursor', value: cursor },
|
|
35
|
+
{ name: 'Limit', value: limit?.toString() },
|
|
36
|
+
{ name: 'Sort-By', value: sortBy },
|
|
37
|
+
{ name: 'Sort-Order', value: sortOrder },
|
|
38
|
+
{ name: 'Filters', value: JSON.stringify(filters) },
|
|
39
|
+
];
|
|
40
|
+
const filteredTags = tags.filter((tag) => tag.value !== undefined);
|
|
41
|
+
return this.process.read({
|
|
42
|
+
tags: filteredTags,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async getIntent(intentId) {
|
|
46
|
+
return this.process.read({
|
|
47
|
+
tags: [
|
|
48
|
+
{ name: 'Action', value: 'Get-Intent-By-Id' },
|
|
49
|
+
{ name: 'Intent-Id', value: intentId },
|
|
50
|
+
],
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async getIntentByANTId(antId) {
|
|
54
|
+
const res = await this.getPaginatedIntents({
|
|
55
|
+
filters: {
|
|
56
|
+
antProcessId: antId,
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
if (res.items.length === 0) {
|
|
60
|
+
throw new Error(`No intent found for ANT ID: ${antId}`);
|
|
61
|
+
}
|
|
62
|
+
return res.items[0];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Get orders with flexible selectors
|
|
66
|
+
* @param params - Parameters for filtering and pagination
|
|
67
|
+
* @returns Orders matching the criteria
|
|
68
|
+
*/
|
|
69
|
+
async getPaginatedOrders(params) {
|
|
70
|
+
const tags = [
|
|
71
|
+
{ name: 'Action', value: 'Get-Orders' },
|
|
72
|
+
{ name: 'Status', value: params?.status },
|
|
73
|
+
{ name: 'Ids', value: params?.ids?.join(',') },
|
|
74
|
+
{ name: 'Dominant-Token', value: params?.dominantToken },
|
|
75
|
+
{ name: 'Swap-Token', value: params?.swapToken },
|
|
76
|
+
{ name: 'Cursor', value: params?.cursor },
|
|
77
|
+
{ name: 'Limit', value: params?.limit?.toString() },
|
|
78
|
+
{ name: 'Sort-By', value: params?.sortBy },
|
|
79
|
+
{ name: 'Sort-Order', value: params?.sortOrder },
|
|
80
|
+
{
|
|
81
|
+
name: 'Filters',
|
|
82
|
+
value: params?.filters ? JSON.stringify(params.filters) : undefined,
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
const filteredTags = tags.filter((tag) => tag.value !== undefined);
|
|
86
|
+
return this.process.read({ tags: filteredTags });
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Get a single order by ID
|
|
90
|
+
* @param orderId - The order ID to fetch
|
|
91
|
+
* @returns The order if found
|
|
92
|
+
*/
|
|
93
|
+
async getOrder(orderId) {
|
|
94
|
+
return this.process.read({
|
|
95
|
+
tags: [
|
|
96
|
+
{ name: 'Action', value: 'Get-Order' },
|
|
97
|
+
{ name: 'Order-Id', value: orderId },
|
|
98
|
+
],
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async getOrderByANTId(antId) {
|
|
102
|
+
const res = await this.getPaginatedOrders({
|
|
103
|
+
dominantToken: antId,
|
|
104
|
+
});
|
|
105
|
+
if (res.items.length === 0) {
|
|
106
|
+
throw new Error(`No order found for ANT ID: ${antId}`);
|
|
107
|
+
}
|
|
108
|
+
// Strange behaviour here. It seems that the filter logic will return an order with potentially different dominant token.
|
|
109
|
+
const order = res.items[0];
|
|
110
|
+
if (order.dominantToken !== antId) {
|
|
111
|
+
throw new Error(`No order for ANT ID: ${antId}`);
|
|
112
|
+
}
|
|
113
|
+
return res.items[0];
|
|
114
|
+
}
|
|
115
|
+
async getPaginatedMarketplaceBalances(params) {
|
|
116
|
+
return this.process.read({
|
|
117
|
+
tags: [
|
|
118
|
+
{ name: 'Action', value: 'Get-Paginated-Balances' },
|
|
119
|
+
...paginationParamsToTags(params),
|
|
120
|
+
],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Get ARIO balance for an address in the marketplace
|
|
125
|
+
*/
|
|
126
|
+
async getMarketplaceBalance({ address, }) {
|
|
127
|
+
return this.process.read({
|
|
128
|
+
tags: [
|
|
129
|
+
{ name: 'Action', value: 'Get-Balance' },
|
|
130
|
+
{ name: 'Address', value: address },
|
|
131
|
+
],
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async getUserAssets({ address, arioProcessId, }) {
|
|
135
|
+
async function fetchIntents(context) {
|
|
136
|
+
const intents = [];
|
|
137
|
+
// fetch all intents for user, paginating as needed and adding each ant id to the set
|
|
138
|
+
let intentsCursor = undefined;
|
|
139
|
+
let intentsHasMore = true;
|
|
140
|
+
while (intentsHasMore) {
|
|
141
|
+
const intentsRes = await context.getPaginatedIntents({
|
|
142
|
+
cursor: intentsCursor,
|
|
143
|
+
limit: 1000,
|
|
144
|
+
filters: {
|
|
145
|
+
initiator: address,
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
intentsRes.items.forEach((intent) => {
|
|
149
|
+
intents.push(intent);
|
|
150
|
+
});
|
|
151
|
+
intentsCursor = intentsRes.nextCursor;
|
|
152
|
+
intentsHasMore = intentsRes.hasMore;
|
|
153
|
+
}
|
|
154
|
+
return intents;
|
|
155
|
+
}
|
|
156
|
+
async function fetchOrders(context) {
|
|
157
|
+
const orders = [];
|
|
158
|
+
// fetch all orders for user, paginating as needed
|
|
159
|
+
let ordersCursor = undefined;
|
|
160
|
+
let ordersHasMore = true;
|
|
161
|
+
while (ordersHasMore) {
|
|
162
|
+
const ordersRes = await context.getPaginatedOrders({
|
|
163
|
+
cursor: ordersCursor,
|
|
164
|
+
limit: 1000,
|
|
165
|
+
filters: {
|
|
166
|
+
creator: address,
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
ordersRes.items.forEach((order) => {
|
|
170
|
+
orders.push(order);
|
|
171
|
+
});
|
|
172
|
+
ordersCursor = ordersRes.nextCursor;
|
|
173
|
+
ordersHasMore = ordersRes.hasMore;
|
|
174
|
+
}
|
|
175
|
+
return orders;
|
|
176
|
+
}
|
|
177
|
+
// parallel fetch balances, intents, and orders
|
|
178
|
+
const [balances, intents, orders] = await Promise.all([
|
|
179
|
+
this.getMarketplaceBalance({ address }),
|
|
180
|
+
fetchIntents(this),
|
|
181
|
+
fetchOrders(this),
|
|
182
|
+
]);
|
|
183
|
+
const antIdsArray = Array.from(new Set([
|
|
184
|
+
...intents.map((intent) => intent.antProcessId),
|
|
185
|
+
...orders.map((order) => order.dominantToken),
|
|
186
|
+
...orders.map((order) => order.swapToken),
|
|
187
|
+
])).filter((antId) => antId !== arioProcessId); // since we add both swap and dominant token for simplicity, we need to filter out the ario token
|
|
188
|
+
return { intents, orders, balances, antIds: antIdsArray };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
export class ArNSMarketplaceWrite extends ArNSMarketplaceRead {
|
|
192
|
+
process;
|
|
193
|
+
signer;
|
|
194
|
+
ario;
|
|
195
|
+
constructor({ process = new AOProcess({
|
|
196
|
+
processId: MARKETPLACE_CONTRACT_ID,
|
|
197
|
+
}), signer, ario, logger = Logger.default, }) {
|
|
198
|
+
super({ process: process, logger: logger });
|
|
199
|
+
this.process = process;
|
|
200
|
+
this.signer = signer;
|
|
201
|
+
this.ario = ario;
|
|
202
|
+
this.logger = logger;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Deposit ARIO to the marketplace (simulates Credit-Notice from ARIO token process)
|
|
206
|
+
* Returns the message ID for verification
|
|
207
|
+
*/
|
|
208
|
+
async depositArIO(params) {
|
|
209
|
+
return this.ario.transfer({
|
|
210
|
+
// the marketplace process id is the target
|
|
211
|
+
target: this.process.processId,
|
|
212
|
+
qty: Number(params.amount),
|
|
213
|
+
}, {
|
|
214
|
+
tags: [{ name: 'X-Action', value: 'Deposit' }],
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Withdraw ARIO from the marketplace back to user
|
|
219
|
+
*/
|
|
220
|
+
async withdrawArIO(params) {
|
|
221
|
+
return this.process.send({
|
|
222
|
+
tags: [
|
|
223
|
+
{ name: 'Action', value: 'Withdraw-Ario' },
|
|
224
|
+
{ name: 'Quantity', value: params.amount },
|
|
225
|
+
],
|
|
226
|
+
signer: this.signer,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
async createIntent({ antId, orderType, quantity, price, expirationTime, minimumPrice, decreaseInterval, }) {
|
|
230
|
+
const tags = [
|
|
231
|
+
{ name: 'Action', value: 'Create-Intent' },
|
|
232
|
+
{ name: 'X-Intent-ANT-Id', value: antId },
|
|
233
|
+
{ name: 'X-Intent-Order-Type', value: orderType },
|
|
234
|
+
{ name: 'X-Intent-Quantity', value: quantity },
|
|
235
|
+
{ name: 'X-Intent-Price', value: price },
|
|
236
|
+
{ name: 'X-Intent-Expiration-Time', value: expirationTime },
|
|
237
|
+
{ name: 'X-Intent-Minimum-Price', value: minimumPrice },
|
|
238
|
+
{ name: 'X-Intent-Decrease-Interval', value: decreaseInterval },
|
|
239
|
+
];
|
|
240
|
+
const filteredTags = tags.filter((tag) => tag.value !== undefined);
|
|
241
|
+
return this.process.send({
|
|
242
|
+
tags: filteredTags,
|
|
243
|
+
signer: this.signer,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
async pushANTIntentResolution(intentId) {
|
|
247
|
+
return this.process.send({
|
|
248
|
+
tags: [
|
|
249
|
+
{ name: 'Action', value: 'Push-ANT-Intent-Resolution' },
|
|
250
|
+
{ name: 'X-Intent-Id', value: intentId },
|
|
251
|
+
],
|
|
252
|
+
signer: this.signer,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
async settleAuction(params) {
|
|
256
|
+
const tags = [
|
|
257
|
+
{ name: 'Action', value: 'Settle-Auction' },
|
|
258
|
+
{ name: 'Order-Id', value: params.orderId },
|
|
259
|
+
{ name: 'Dominant-Token', value: params.dominantToken },
|
|
260
|
+
{ name: 'Swap-Token', value: params.swapToken },
|
|
261
|
+
];
|
|
262
|
+
const filteredTags = tags.filter((tag) => tag.value !== undefined);
|
|
263
|
+
return this.process.send({
|
|
264
|
+
tags: filteredTags,
|
|
265
|
+
signer: this.signer,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
async listNameForSale({ name, expirationTime, price, type, walletAddress, minimumPrice, decreaseInterval, }) {
|
|
269
|
+
// Get arns record for the current ant id associated with it
|
|
270
|
+
const record = await this.ario.getArNSRecord({ name: name });
|
|
271
|
+
this.logger.info(`Record ${name} found: ${JSON.stringify(record)}`);
|
|
272
|
+
if (record === undefined) {
|
|
273
|
+
throw new Error(`Record ${name} not found`);
|
|
274
|
+
}
|
|
275
|
+
const antId = record.processId;
|
|
276
|
+
this.logger.info(`ANT ID for ${name} found: ${antId}`);
|
|
277
|
+
const ant = ANT.init({
|
|
278
|
+
process: new AOProcess({
|
|
279
|
+
processId: antId,
|
|
280
|
+
ao: this.process.ao,
|
|
281
|
+
}),
|
|
282
|
+
signer: this.signer,
|
|
283
|
+
});
|
|
284
|
+
const antState = await ant.getState();
|
|
285
|
+
if (antState.Owner !== walletAddress) {
|
|
286
|
+
this.logger.error(`Wallet address ${walletAddress} does not match the owner of the ANT ${antId}. Only the owner can list the name for sale.`);
|
|
287
|
+
throw new Error('Wallet address does not match the owner of the ANT. Only the owner can list the name for sale.');
|
|
288
|
+
}
|
|
289
|
+
let intent;
|
|
290
|
+
try {
|
|
291
|
+
const intentResult = await this.createIntent({
|
|
292
|
+
antId,
|
|
293
|
+
orderType: type,
|
|
294
|
+
quantity: price,
|
|
295
|
+
expirationTime: expirationTime.toString(),
|
|
296
|
+
price: price,
|
|
297
|
+
minimumPrice: minimumPrice,
|
|
298
|
+
decreaseInterval: decreaseInterval,
|
|
299
|
+
});
|
|
300
|
+
if (intentResult.result === undefined) {
|
|
301
|
+
throw new Error('Failed to create intent: ' + intentResult.id);
|
|
302
|
+
}
|
|
303
|
+
this.logger.info(`Intent created: ${JSON.stringify(intentResult.result)}`);
|
|
304
|
+
intent = intentResult.result;
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
this.logger.error(`Error creating intent: ${error.message}`);
|
|
308
|
+
// check error for existing intent. Will be a contract error message.
|
|
309
|
+
const isExistingIntentError = error.message.includes('An intent already exists for this ANT ID');
|
|
310
|
+
if (isExistingIntentError) {
|
|
311
|
+
intent = await this.getIntentByANTId(antId).catch((error) => {
|
|
312
|
+
this.logger.error(`Failed to get intent: ${error.message}`);
|
|
313
|
+
throw new Error('An intent already exists for this ANT ID but failed to get intent:\n\n' +
|
|
314
|
+
error.message);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
// Possible to get other errors, eg insufficient deposited ario balance. Rethrow them here.
|
|
319
|
+
throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Type guard to ensure intent is defined
|
|
323
|
+
if (intent === undefined) {
|
|
324
|
+
throw new Error('Failed to create intent');
|
|
325
|
+
}
|
|
326
|
+
let antTransferResult;
|
|
327
|
+
try {
|
|
328
|
+
antTransferResult = await ant.transfer({
|
|
329
|
+
target: this.process.processId,
|
|
330
|
+
removeControllers: false, // important: do not remove the controllers of the ANT to prevent loss of control
|
|
331
|
+
}, {
|
|
332
|
+
tags: [{ name: 'X-Intent-Id', value: intent.intentId }],
|
|
333
|
+
});
|
|
334
|
+
this.logger.info(`ANT transferred: ${JSON.stringify(antTransferResult)}`);
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
this.logger.error(`Failed to transfer ANT: ${error.message}`);
|
|
338
|
+
return {
|
|
339
|
+
intent,
|
|
340
|
+
order: null,
|
|
341
|
+
antTransferResult: null,
|
|
342
|
+
error: error,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
// poll for the order to be created
|
|
346
|
+
// This is to ensure the order is created before returning the result for ux purposes.
|
|
347
|
+
// This may still fail, in which case we return the intent and ant transfer result and handle the error in the client.
|
|
348
|
+
let order = null;
|
|
349
|
+
let tries = 0;
|
|
350
|
+
while (order === null && tries < 5) {
|
|
351
|
+
try {
|
|
352
|
+
order = await this.getOrderByANTId(antId).catch((error) => {
|
|
353
|
+
console.log(new Error('Failed to get order: ' + error.message));
|
|
354
|
+
return null;
|
|
355
|
+
});
|
|
356
|
+
if (order === null) {
|
|
357
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
358
|
+
this.logger.info(`Waiting for order to be created...`);
|
|
359
|
+
if (tries === 5) {
|
|
360
|
+
this.logger.error(`Failed to get order after ${tries} attempts`);
|
|
361
|
+
throw new Error(`Failed to get order after ${tries} attempts`);
|
|
362
|
+
}
|
|
363
|
+
tries++;
|
|
364
|
+
}
|
|
365
|
+
// if the order is found, break the loop
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
this.logger.error(`Failed to get order: ${error.message}`);
|
|
370
|
+
return {
|
|
371
|
+
intent,
|
|
372
|
+
order: null,
|
|
373
|
+
antTransferResult,
|
|
374
|
+
error: new Error('Failed to get order: ' + error.message),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (order === null) {
|
|
379
|
+
this.logger.error(`Failed to get order`);
|
|
380
|
+
return {
|
|
381
|
+
intent,
|
|
382
|
+
order: null,
|
|
383
|
+
antTransferResult,
|
|
384
|
+
error: new Error('Failed to get order'),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
return { intent, order, antTransferResult, error: null };
|
|
388
|
+
}
|
|
389
|
+
async cancelOrder(orderId) {
|
|
390
|
+
const tags = [
|
|
391
|
+
{ name: 'Action', value: 'Cancel-Order' },
|
|
392
|
+
{ name: 'Order-Id', value: orderId },
|
|
393
|
+
];
|
|
394
|
+
return this.process.send({
|
|
395
|
+
tags,
|
|
396
|
+
signer: this.signer,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
async createOrder({ swapToken, quantity, orderType, price, expirationTime, minimumPrice, decreaseInterval, transferDenomination, }) {
|
|
400
|
+
const tags = [
|
|
401
|
+
{ name: 'Action', value: 'Create-Order' },
|
|
402
|
+
{ name: 'Swap-Token', value: swapToken },
|
|
403
|
+
{ name: 'Quantity', value: quantity },
|
|
404
|
+
{ name: 'Order-Type', value: orderType },
|
|
405
|
+
{ name: 'Price', value: price },
|
|
406
|
+
{ name: 'Expiration-Time', value: expirationTime },
|
|
407
|
+
{ name: 'Minimum-Price', value: minimumPrice },
|
|
408
|
+
{ name: 'Decrease-Interval', value: decreaseInterval },
|
|
409
|
+
{ name: 'Transfer-Denomination', value: transferDenomination },
|
|
410
|
+
];
|
|
411
|
+
const filteredTags = tags.filter((tag) => tag.value !== undefined);
|
|
412
|
+
// Send the message
|
|
413
|
+
return this.process.send({
|
|
414
|
+
tags: filteredTags,
|
|
415
|
+
signer: this.signer,
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
async buyFixedPriceANT(params) {
|
|
419
|
+
const order = await this.getOrderByANTId(params.antId);
|
|
420
|
+
if (order === undefined) {
|
|
421
|
+
throw new Error(`No active sell order found for ANT: ${params.antId}`);
|
|
422
|
+
}
|
|
423
|
+
if (order.status !== 'active') {
|
|
424
|
+
throw new Error(`Order status is ${order.status}, must be active`);
|
|
425
|
+
}
|
|
426
|
+
if (order.price === undefined) {
|
|
427
|
+
throw new Error(`Order price is undefined for ANT: ${params.antId}`);
|
|
428
|
+
}
|
|
429
|
+
// Create a buy order that matches the sell order
|
|
430
|
+
// This should trigger immediate execution if prices match
|
|
431
|
+
// For ArNS: buying 1 ANT, so quantity = price = total cost
|
|
432
|
+
return this.createOrder({
|
|
433
|
+
swapToken: params.antId,
|
|
434
|
+
quantity: order.price, // Total ARIO cost
|
|
435
|
+
orderType: 'fixed',
|
|
436
|
+
price: order.price, // Match their asking price
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
async buyDutchAuctionANT(params) {
|
|
440
|
+
const order = await this.getOrderByANTId(params.antId);
|
|
441
|
+
if (order === undefined) {
|
|
442
|
+
throw new Error(`No active sell order found for ANT: ${params.antId}`);
|
|
443
|
+
}
|
|
444
|
+
if (order.status !== 'active') {
|
|
445
|
+
throw new Error(`Order status is ${order.status}, must be active`);
|
|
446
|
+
}
|
|
447
|
+
if (order.orderType !== 'dutch') {
|
|
448
|
+
throw new Error(`Order is not a Dutch auction, it's: ${order.orderType}`);
|
|
449
|
+
}
|
|
450
|
+
if (order.price === undefined) {
|
|
451
|
+
throw new Error(`Order starting price is undefined for ANT: ${params.antId}`);
|
|
452
|
+
}
|
|
453
|
+
// For Dutch auction, the current price will be calculated on execution
|
|
454
|
+
return this.createOrder({
|
|
455
|
+
swapToken: params.antId,
|
|
456
|
+
quantity: order.price,
|
|
457
|
+
orderType: 'fixed',
|
|
458
|
+
price: order.price,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Place a bid on an English auction
|
|
463
|
+
* Note: This requires you to have sufficient ARIO balance in the marketplace
|
|
464
|
+
*/
|
|
465
|
+
async bidOnANTEnglishAuction(params) {
|
|
466
|
+
const order = await this.getOrderByANTId(params.antId);
|
|
467
|
+
if (order === undefined) {
|
|
468
|
+
throw new Error(`No active sell order found for ANT: ${params.antId}`);
|
|
469
|
+
}
|
|
470
|
+
if (order.status !== 'active') {
|
|
471
|
+
throw new Error(`Order status is ${order.status}, must be active`);
|
|
472
|
+
}
|
|
473
|
+
if (order.orderType !== 'english') {
|
|
474
|
+
throw new Error(`Order is not an English auction, it's: ${order.orderType}`);
|
|
475
|
+
}
|
|
476
|
+
// Check if auction has expired
|
|
477
|
+
if (order.expirationTime !== undefined &&
|
|
478
|
+
Date.now() >= order.expirationTime) {
|
|
479
|
+
throw new Error(`Auction has already expired for ANT: ${params.antId}`);
|
|
480
|
+
}
|
|
481
|
+
return this.process.send({
|
|
482
|
+
tags: [
|
|
483
|
+
{ name: 'Action', value: 'Bid-On-English-Auction' },
|
|
484
|
+
{ name: 'Order-Id', value: order.id },
|
|
485
|
+
{ name: 'Bid-Amount', value: params.bidAmount },
|
|
486
|
+
],
|
|
487
|
+
signer: this.signer,
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Settle an expired English auction
|
|
492
|
+
* Can be called by anyone after the auction expires
|
|
493
|
+
* The highest bidder wins the ANT
|
|
494
|
+
*/
|
|
495
|
+
async settleANTEnglishAuction(params) {
|
|
496
|
+
const order = await this.getOrderByANTId(params.antId);
|
|
497
|
+
if (order === undefined) {
|
|
498
|
+
throw new Error(`No active sell order found for ANT: ${params.antId}`);
|
|
499
|
+
}
|
|
500
|
+
if (order.orderType !== 'english') {
|
|
501
|
+
throw new Error(`Order is not an English auction, it's: ${order.orderType}`);
|
|
502
|
+
}
|
|
503
|
+
// Check if auction has expired
|
|
504
|
+
if (order.expirationTime !== undefined &&
|
|
505
|
+
Date.now() < order.expirationTime) {
|
|
506
|
+
throw new Error(`Auction has not yet expired for ANT: ${params.antId}. Expires at: ${new Date(order.expirationTime).toISOString()}`);
|
|
507
|
+
}
|
|
508
|
+
return this.settleAuction({
|
|
509
|
+
orderId: order.id,
|
|
510
|
+
dominantToken: order.dominantToken,
|
|
511
|
+
swapToken: order.swapToken,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Calculates the listing fee for an order based on the end timestamp.
|
|
517
|
+
* The fee is calculated by rounding up the hours until the end timestamp to the nearest hour.
|
|
518
|
+
*
|
|
519
|
+
* @param params - Parameters for calculating the listing fee
|
|
520
|
+
* @param params.listingFeePerHour - The listing fee per hour in mARIO (as a string)
|
|
521
|
+
* @param params.endTimestamp - Unix timestamp when the order expires
|
|
522
|
+
* @returns The listing fee in mARIO as a BigInt
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* ```typescript
|
|
526
|
+
* const info = await marketplace.getInfo();
|
|
527
|
+
* const endTimestamp = Date.now() + 24 * 60 * 60 * 1000; // 24 hours from now
|
|
528
|
+
* const listingFee = calculateListingFee({
|
|
529
|
+
* listingFeePerHour: info.fees.listingFeePerHour,
|
|
530
|
+
* endTimestamp,
|
|
531
|
+
* });
|
|
532
|
+
* ```
|
|
533
|
+
*/
|
|
534
|
+
export function calculateListingFee({ listingFeePerHour, endTimestamp, }) {
|
|
535
|
+
const now = Date.now();
|
|
536
|
+
const millisecondsUntilEnd = endTimestamp - now;
|
|
537
|
+
if (millisecondsUntilEnd <= 0) {
|
|
538
|
+
return BigInt(0);
|
|
539
|
+
}
|
|
540
|
+
// Convert milliseconds to hours and round up to the nearest hour
|
|
541
|
+
const hoursUntilEnd = Math.ceil(millisecondsUntilEnd / (1000 * 60 * 60));
|
|
542
|
+
// Calculate listing fee: hours * fee per hour
|
|
543
|
+
return BigInt(hoursUntilEnd) * BigInt(listingFeePerHour);
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Calculates the sale tax for an order based on the sale amount.
|
|
547
|
+
*
|
|
548
|
+
* @param params - Parameters for calculating the sale tax
|
|
549
|
+
* @param params.saleAmount - The sale amount in mARIO (as a string or number)
|
|
550
|
+
* @param params.saleTaxNumerator - The numerator for sale tax calculation
|
|
551
|
+
* @param params.saleTaxDenominator - The denominator for sale tax calculation
|
|
552
|
+
* @returns The sale tax in mARIO as a BigInt
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
* ```typescript
|
|
556
|
+
* const info = await marketplace.getInfo();
|
|
557
|
+
* const saleAmount = 100000000000; // 100 ARIO in mARIO
|
|
558
|
+
* const tax = calculateSaleTax({
|
|
559
|
+
* saleAmount,
|
|
560
|
+
* saleTaxNumerator: info.fees.saleTaxNumerator,
|
|
561
|
+
* saleTaxDenominator: info.fees.saleTaxDenominator,
|
|
562
|
+
* });
|
|
563
|
+
* ```
|
|
564
|
+
*/
|
|
565
|
+
export function calculateSaleTax({ saleAmount, saleTaxNumerator, saleTaxDenominator, }) {
|
|
566
|
+
// Calculate tax: (saleAmount * numerator) / denominator
|
|
567
|
+
return ((BigInt(saleAmount) * BigInt(saleTaxNumerator)) / BigInt(saleTaxDenominator));
|
|
568
|
+
}
|
package/lib/esm/constants.js
CHANGED
|
@@ -23,6 +23,7 @@ export const ARIO_TESTNET_PROCESS_ID = 'agYcCFJtrMG6cqMuZfskIkFTGvUPddICmtQSBIoP
|
|
|
23
23
|
export const ARIO_MAINNET_PROCESS_ID = 'qNvAoz0TgcH7DMg8BCVn8jF32QH5L6T29VjHxhHqqGE';
|
|
24
24
|
export const ANT_REGISTRY_TESTNET_ID = 'RR0vheYqtsKuJCWh6xj0beE35tjaEug5cejMw9n2aa8';
|
|
25
25
|
export const ANT_REGISTRY_ID = 'i_le_yKKPVstLTDSmkHRqf-wYphMnwB9OhleiTgMkWc';
|
|
26
|
+
export const MARKETPLACE_CONTRACT_ID = 'wPh88ziUF4meLpHfffmgdA6IFtzmXHgdeg-epzBjkao';
|
|
26
27
|
export const MARIO_PER_ARIO = 1_000_000;
|
|
27
28
|
/**
|
|
28
29
|
* @deprecated - use ANT.versions.getLatestANTVersion() to get latest ANT module
|