@imtbl/sdk 0.3.3 → 0.4.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.
@@ -0,0 +1,1985 @@
1
+ import axios from 'axios';
2
+ import FormData from 'form-data';
3
+ import { providers, BigNumber, constants, utils, Contract } from 'ethers';
4
+ import { Seaport as Seaport$1 } from '@opensea/seaport-js';
5
+
6
+ class BaseHttpRequest {
7
+ config;
8
+ constructor(config) {
9
+ this.config = config;
10
+ }
11
+ }
12
+
13
+ class ApiError extends Error {
14
+ url;
15
+ status;
16
+ statusText;
17
+ body;
18
+ request;
19
+ constructor(request, response, message) {
20
+ super(message);
21
+ this.name = 'ApiError';
22
+ this.url = response.url;
23
+ this.status = response.status;
24
+ this.statusText = response.statusText;
25
+ this.body = response.body;
26
+ this.request = request;
27
+ }
28
+ }
29
+
30
+ /* istanbul ignore file */
31
+ /* tslint:disable */
32
+ /* eslint-disable */
33
+ class CancelError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = 'CancelError';
37
+ }
38
+ get isCancelled() {
39
+ return true;
40
+ }
41
+ }
42
+ class CancelablePromise {
43
+ [Symbol.toStringTag];
44
+ _isResolved;
45
+ _isRejected;
46
+ _isCancelled;
47
+ _cancelHandlers;
48
+ _promise;
49
+ _resolve;
50
+ _reject;
51
+ constructor(executor) {
52
+ this._isResolved = false;
53
+ this._isRejected = false;
54
+ this._isCancelled = false;
55
+ this._cancelHandlers = [];
56
+ this._promise = new Promise((resolve, reject) => {
57
+ this._resolve = resolve;
58
+ this._reject = reject;
59
+ const onResolve = (value) => {
60
+ if (this._isResolved || this._isRejected || this._isCancelled) {
61
+ return;
62
+ }
63
+ this._isResolved = true;
64
+ this._resolve?.(value);
65
+ };
66
+ const onReject = (reason) => {
67
+ if (this._isResolved || this._isRejected || this._isCancelled) {
68
+ return;
69
+ }
70
+ this._isRejected = true;
71
+ this._reject?.(reason);
72
+ };
73
+ const onCancel = (cancelHandler) => {
74
+ if (this._isResolved || this._isRejected || this._isCancelled) {
75
+ return;
76
+ }
77
+ this._cancelHandlers.push(cancelHandler);
78
+ };
79
+ Object.defineProperty(onCancel, 'isResolved', {
80
+ get: () => this._isResolved,
81
+ });
82
+ Object.defineProperty(onCancel, 'isRejected', {
83
+ get: () => this._isRejected,
84
+ });
85
+ Object.defineProperty(onCancel, 'isCancelled', {
86
+ get: () => this._isCancelled,
87
+ });
88
+ return executor(onResolve, onReject, onCancel);
89
+ });
90
+ }
91
+ then(onFulfilled, onRejected) {
92
+ return this._promise.then(onFulfilled, onRejected);
93
+ }
94
+ catch(onRejected) {
95
+ return this._promise.catch(onRejected);
96
+ }
97
+ finally(onFinally) {
98
+ return this._promise.finally(onFinally);
99
+ }
100
+ cancel() {
101
+ if (this._isResolved || this._isRejected || this._isCancelled) {
102
+ return;
103
+ }
104
+ this._isCancelled = true;
105
+ if (this._cancelHandlers.length) {
106
+ try {
107
+ for (const cancelHandler of this._cancelHandlers) {
108
+ cancelHandler();
109
+ }
110
+ }
111
+ catch (error) {
112
+ console.warn('Cancellation threw an error', error);
113
+ return;
114
+ }
115
+ }
116
+ this._cancelHandlers.length = 0;
117
+ this._reject?.(new CancelError('Request aborted'));
118
+ }
119
+ get isCancelled() {
120
+ return this._isCancelled;
121
+ }
122
+ }
123
+
124
+ /* istanbul ignore file */
125
+ /* tslint:disable */
126
+ /* eslint-disable */
127
+ const isDefined = (value) => {
128
+ return value !== undefined && value !== null;
129
+ };
130
+ const isString = (value) => {
131
+ return typeof value === 'string';
132
+ };
133
+ const isStringWithValue = (value) => {
134
+ return isString(value) && value !== '';
135
+ };
136
+ const isBlob = (value) => {
137
+ return (typeof value === 'object' &&
138
+ typeof value.type === 'string' &&
139
+ typeof value.stream === 'function' &&
140
+ typeof value.arrayBuffer === 'function' &&
141
+ typeof value.constructor === 'function' &&
142
+ typeof value.constructor.name === 'string' &&
143
+ /^(Blob|File)$/.test(value.constructor.name) &&
144
+ /^(Blob|File)$/.test(value[Symbol.toStringTag]));
145
+ };
146
+ const isFormData = (value) => {
147
+ return value instanceof FormData;
148
+ };
149
+ const isSuccess = (status) => {
150
+ return status >= 200 && status < 300;
151
+ };
152
+ const base64 = (str) => {
153
+ try {
154
+ return btoa(str);
155
+ }
156
+ catch (err) {
157
+ // @ts-ignore
158
+ return Buffer.from(str).toString('base64');
159
+ }
160
+ };
161
+ const getQueryString = (params) => {
162
+ const qs = [];
163
+ const append = (key, value) => {
164
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
165
+ };
166
+ const process = (key, value) => {
167
+ if (isDefined(value)) {
168
+ if (Array.isArray(value)) {
169
+ value.forEach(v => {
170
+ process(key, v);
171
+ });
172
+ }
173
+ else if (typeof value === 'object') {
174
+ Object.entries(value).forEach(([k, v]) => {
175
+ process(`${key}[${k}]`, v);
176
+ });
177
+ }
178
+ else {
179
+ append(key, value);
180
+ }
181
+ }
182
+ };
183
+ Object.entries(params).forEach(([key, value]) => {
184
+ process(key, value);
185
+ });
186
+ if (qs.length > 0) {
187
+ return `?${qs.join('&')}`;
188
+ }
189
+ return '';
190
+ };
191
+ const getUrl = (config, options) => {
192
+ const encoder = config.ENCODE_PATH || encodeURI;
193
+ const path = options.url
194
+ .replace('{api-version}', config.VERSION)
195
+ .replace(/{(.*?)}/g, (substring, group) => {
196
+ if (options.path?.hasOwnProperty(group)) {
197
+ return encoder(String(options.path[group]));
198
+ }
199
+ return substring;
200
+ });
201
+ const url = `${config.BASE}${path}`;
202
+ if (options.query) {
203
+ return `${url}${getQueryString(options.query)}`;
204
+ }
205
+ return url;
206
+ };
207
+ const getFormData = (options) => {
208
+ if (options.formData) {
209
+ const formData = new FormData();
210
+ const process = (key, value) => {
211
+ if (isString(value) || isBlob(value)) {
212
+ formData.append(key, value);
213
+ }
214
+ else {
215
+ formData.append(key, JSON.stringify(value));
216
+ }
217
+ };
218
+ Object.entries(options.formData)
219
+ .filter(([_, value]) => isDefined(value))
220
+ .forEach(([key, value]) => {
221
+ if (Array.isArray(value)) {
222
+ value.forEach(v => process(key, v));
223
+ }
224
+ else {
225
+ process(key, value);
226
+ }
227
+ });
228
+ return formData;
229
+ }
230
+ return undefined;
231
+ };
232
+ const resolve = async (options, resolver) => {
233
+ if (typeof resolver === 'function') {
234
+ return resolver(options);
235
+ }
236
+ return resolver;
237
+ };
238
+ const getHeaders = async (config, options, formData) => {
239
+ const token = await resolve(options, config.TOKEN);
240
+ const username = await resolve(options, config.USERNAME);
241
+ const password = await resolve(options, config.PASSWORD);
242
+ const additionalHeaders = await resolve(options, config.HEADERS);
243
+ const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {};
244
+ const headers = Object.entries({
245
+ Accept: 'application/json',
246
+ ...additionalHeaders,
247
+ ...options.headers,
248
+ ...formHeaders,
249
+ })
250
+ .filter(([_, value]) => isDefined(value))
251
+ .reduce((headers, [key, value]) => ({
252
+ ...headers,
253
+ [key]: String(value),
254
+ }), {});
255
+ if (isStringWithValue(token)) {
256
+ headers['Authorization'] = `Bearer ${token}`;
257
+ }
258
+ if (isStringWithValue(username) && isStringWithValue(password)) {
259
+ const credentials = base64(`${username}:${password}`);
260
+ headers['Authorization'] = `Basic ${credentials}`;
261
+ }
262
+ if (options.body) {
263
+ if (options.mediaType) {
264
+ headers['Content-Type'] = options.mediaType;
265
+ }
266
+ else if (isBlob(options.body)) {
267
+ headers['Content-Type'] = options.body.type || 'application/octet-stream';
268
+ }
269
+ else if (isString(options.body)) {
270
+ headers['Content-Type'] = 'text/plain';
271
+ }
272
+ else if (!isFormData(options.body)) {
273
+ headers['Content-Type'] = 'application/json';
274
+ }
275
+ }
276
+ return headers;
277
+ };
278
+ const getRequestBody = (options) => {
279
+ if (options.body) {
280
+ return options.body;
281
+ }
282
+ return undefined;
283
+ };
284
+ const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
285
+ const source = axios.CancelToken.source();
286
+ const requestConfig = {
287
+ url,
288
+ headers,
289
+ data: body ?? formData,
290
+ method: options.method,
291
+ withCredentials: config.WITH_CREDENTIALS,
292
+ cancelToken: source.token,
293
+ };
294
+ onCancel(() => source.cancel('The user aborted a request.'));
295
+ try {
296
+ return await axios.request(requestConfig);
297
+ }
298
+ catch (error) {
299
+ const axiosError = error;
300
+ if (axiosError.response) {
301
+ return axiosError.response;
302
+ }
303
+ throw error;
304
+ }
305
+ };
306
+ const getResponseHeader = (response, responseHeader) => {
307
+ if (responseHeader) {
308
+ const content = response.headers[responseHeader];
309
+ if (isString(content)) {
310
+ return content;
311
+ }
312
+ }
313
+ return undefined;
314
+ };
315
+ const getResponseBody = (response) => {
316
+ if (response.status !== 204) {
317
+ return response.data;
318
+ }
319
+ return undefined;
320
+ };
321
+ const catchErrorCodes = (options, result) => {
322
+ const errors = {
323
+ 400: 'Bad Request',
324
+ 401: 'Unauthorized',
325
+ 403: 'Forbidden',
326
+ 404: 'Not Found',
327
+ 500: 'Internal Server Error',
328
+ 502: 'Bad Gateway',
329
+ 503: 'Service Unavailable',
330
+ ...options.errors,
331
+ };
332
+ const error = errors[result.status];
333
+ if (error) {
334
+ throw new ApiError(options, result, error);
335
+ }
336
+ if (!result.ok) {
337
+ throw new ApiError(options, result, 'Generic Error');
338
+ }
339
+ };
340
+ /**
341
+ * Request method
342
+ * @param config The OpenAPI configuration object
343
+ * @param options The request options from the service
344
+ * @returns CancelablePromise<T>
345
+ * @throws ApiError
346
+ */
347
+ const request = (config, options) => {
348
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
349
+ try {
350
+ const url = getUrl(config, options);
351
+ const formData = getFormData(options);
352
+ const body = getRequestBody(options);
353
+ const headers = await getHeaders(config, options, formData);
354
+ if (!onCancel.isCancelled) {
355
+ const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
356
+ const responseBody = getResponseBody(response);
357
+ const responseHeader = getResponseHeader(response, options.responseHeader);
358
+ const result = {
359
+ url,
360
+ ok: isSuccess(response.status),
361
+ status: response.status,
362
+ statusText: response.statusText,
363
+ body: responseHeader ?? responseBody,
364
+ };
365
+ catchErrorCodes(options, result);
366
+ resolve(result.body);
367
+ }
368
+ }
369
+ catch (error) {
370
+ reject(error);
371
+ }
372
+ });
373
+ };
374
+
375
+ class AxiosHttpRequest extends BaseHttpRequest {
376
+ constructor(config) {
377
+ super(config);
378
+ }
379
+ /**
380
+ * Request method
381
+ * @param options The request options from the service
382
+ * @returns CancelablePromise<T>
383
+ * @throws ApiError
384
+ */
385
+ request(options) {
386
+ return request(this.config, options);
387
+ }
388
+ }
389
+
390
+ class OrdersService {
391
+ httpRequest;
392
+ constructor(httpRequest) {
393
+ this.httpRequest = httpRequest;
394
+ }
395
+ /**
396
+ * List all listings
397
+ * List all listings
398
+ * @returns ListListingsResult OK response.
399
+ * @throws ApiError
400
+ */
401
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, pageSize, sortBy, sortDirection, pageCursor, }) {
402
+ return this.httpRequest.request({
403
+ method: 'GET',
404
+ url: '/v1/chains/{chain_name}/orders/listings',
405
+ path: {
406
+ 'chain_name': chainName,
407
+ },
408
+ query: {
409
+ 'status': status,
410
+ 'sell_item_contract_address': sellItemContractAddress,
411
+ 'buy_item_contract_address': buyItemContractAddress,
412
+ 'sell_item_token_id': sellItemTokenId,
413
+ 'page_size': pageSize,
414
+ 'sort_by': sortBy,
415
+ 'sort_direction': sortDirection,
416
+ 'page_cursor': pageCursor,
417
+ },
418
+ errors: {
419
+ 400: `Bad Request (400)`,
420
+ 404: `The specified resource was not found (404)`,
421
+ 500: `Internal Server Error (500)`,
422
+ },
423
+ });
424
+ }
425
+ /**
426
+ * Create a listing
427
+ * Create a listing
428
+ * @returns ListingResult Created response.
429
+ * @throws ApiError
430
+ */
431
+ createListing({ chainName, requestBody, }) {
432
+ return this.httpRequest.request({
433
+ method: 'POST',
434
+ url: '/v1/chains/{chain_name}/orders/listings',
435
+ path: {
436
+ 'chain_name': chainName,
437
+ },
438
+ body: requestBody,
439
+ mediaType: 'application/json',
440
+ errors: {
441
+ 400: `Bad Request (400)`,
442
+ 404: `The specified resource was not found (404)`,
443
+ 500: `Internal Server Error (500)`,
444
+ },
445
+ });
446
+ }
447
+ /**
448
+ * Get a single listing by ID
449
+ * Get a single listing by ID
450
+ * @returns ListingResult OK response.
451
+ * @throws ApiError
452
+ */
453
+ getListing({ chainName, listingId, }) {
454
+ return this.httpRequest.request({
455
+ method: 'GET',
456
+ url: '/v1/chains/{chain_name}/orders/listings/{listing_id}',
457
+ path: {
458
+ 'chain_name': chainName,
459
+ 'listing_id': listingId,
460
+ },
461
+ errors: {
462
+ 400: `Bad Request (400)`,
463
+ 404: `The specified resource was not found (404)`,
464
+ 500: `Internal Server Error (500)`,
465
+ },
466
+ });
467
+ }
468
+ }
469
+
470
+ class OrderBookClient {
471
+ orders;
472
+ request;
473
+ constructor(config, HttpRequest = AxiosHttpRequest) {
474
+ this.request = new HttpRequest({
475
+ BASE: config?.BASE ?? 'https://order-book-mr.dev.imtbl.com',
476
+ VERSION: config?.VERSION ?? '1.0.0',
477
+ WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
478
+ CREDENTIALS: config?.CREDENTIALS ?? 'include',
479
+ TOKEN: config?.TOKEN,
480
+ USERNAME: config?.USERNAME,
481
+ PASSWORD: config?.PASSWORD,
482
+ HEADERS: config?.HEADERS,
483
+ ENCODE_PATH: config?.ENCODE_PATH,
484
+ });
485
+ this.orders = new OrdersService(this.request);
486
+ }
487
+ }
488
+
489
+ /* istanbul ignore file */
490
+ /* tslint:disable */
491
+ /* eslint-disable */
492
+ var CreateOrderProtocolData;
493
+ (function (CreateOrderProtocolData) {
494
+ (function (order_type) {
495
+ order_type["FULL_RESTRICTED"] = "FULL_RESTRICTED";
496
+ })(CreateOrderProtocolData.order_type || (CreateOrderProtocolData.order_type = {}));
497
+ })(CreateOrderProtocolData || (CreateOrderProtocolData = {}));
498
+
499
+ /* istanbul ignore file */
500
+ /* tslint:disable */
501
+ /* eslint-disable */
502
+ var Fee;
503
+ (function (Fee) {
504
+ (function (fee_type) {
505
+ fee_type["ROYALTY"] = "ROYALTY";
506
+ })(Fee.fee_type || (Fee.fee_type = {}));
507
+ })(Fee || (Fee = {}));
508
+
509
+ /* istanbul ignore file */
510
+ /* tslint:disable */
511
+ /* eslint-disable */
512
+ /**
513
+ * The Order status
514
+ */
515
+ var OrderStatus;
516
+ (function (OrderStatus) {
517
+ OrderStatus["PENDING"] = "PENDING";
518
+ OrderStatus["ACTIVE"] = "ACTIVE";
519
+ OrderStatus["INACTIVE"] = "INACTIVE";
520
+ OrderStatus["FILLED"] = "FILLED";
521
+ OrderStatus["CANCELLED"] = "CANCELLED";
522
+ OrderStatus["EXPIRED"] = "EXPIRED";
523
+ })(OrderStatus || (OrderStatus = {}));
524
+
525
+ /* eslint-disable */
526
+ // TODO: Resolve these from seaport-js.
527
+ // There is some bundling issue that is preventing this from working
528
+ const SEAPORT_CONTRACT_NAME = 'ImmutableSeaport';
529
+ const SEAPORT_CONTRACT_VERSION_V1_4 = '1.4';
530
+ const SEAPORT_CONTRACT_VERSION_V1_5 = '1.5';
531
+ const EIP_712_ORDER_TYPE = {
532
+ OrderComponents: [
533
+ { name: 'offerer', type: 'address' },
534
+ { name: 'zone', type: 'address' },
535
+ { name: 'offer', type: 'OfferItem[]' },
536
+ { name: 'consideration', type: 'ConsiderationItem[]' },
537
+ { name: 'orderType', type: 'uint8' },
538
+ { name: 'startTime', type: 'uint256' },
539
+ { name: 'endTime', type: 'uint256' },
540
+ { name: 'zoneHash', type: 'bytes32' },
541
+ { name: 'salt', type: 'uint256' },
542
+ { name: 'conduitKey', type: 'bytes32' },
543
+ { name: 'counter', type: 'uint256' },
544
+ ],
545
+ OfferItem: [
546
+ { name: 'itemType', type: 'uint8' },
547
+ { name: 'token', type: 'address' },
548
+ { name: 'identifierOrCriteria', type: 'uint256' },
549
+ { name: 'startAmount', type: 'uint256' },
550
+ { name: 'endAmount', type: 'uint256' },
551
+ ],
552
+ ConsiderationItem: [
553
+ { name: 'itemType', type: 'uint8' },
554
+ { name: 'token', type: 'address' },
555
+ { name: 'identifierOrCriteria', type: 'uint256' },
556
+ { name: 'startAmount', type: 'uint256' },
557
+ { name: 'endAmount', type: 'uint256' },
558
+ { name: 'recipient', type: 'address' },
559
+ ],
560
+ };
561
+ var OrderType;
562
+ (function (OrderType) {
563
+ OrderType[OrderType["FULL_OPEN"] = 0] = "FULL_OPEN";
564
+ OrderType[OrderType["PARTIAL_OPEN"] = 1] = "PARTIAL_OPEN";
565
+ OrderType[OrderType["FULL_RESTRICTED"] = 2] = "FULL_RESTRICTED";
566
+ OrderType[OrderType["PARTIAL_RESTRICTED"] = 3] = "PARTIAL_RESTRICTED";
567
+ })(OrderType || (OrderType = {}));
568
+ var ItemType;
569
+ (function (ItemType) {
570
+ ItemType[ItemType["NATIVE"] = 0] = "NATIVE";
571
+ ItemType[ItemType["ERC20"] = 1] = "ERC20";
572
+ ItemType[ItemType["ERC721"] = 2] = "ERC721";
573
+ ItemType[ItemType["ERC1155"] = 3] = "ERC1155";
574
+ ItemType[ItemType["ERC721_WITH_CRITERIA"] = 4] = "ERC721_WITH_CRITERIA";
575
+ ItemType[ItemType["ERC1155_WITH_CRITERIA"] = 5] = "ERC1155_WITH_CRITERIA";
576
+ })(ItemType || (ItemType = {}));
577
+ var Side;
578
+ (function (Side) {
579
+ Side[Side["OFFER"] = 0] = "OFFER";
580
+ Side[Side["CONSIDERATION"] = 1] = "CONSIDERATION";
581
+ })(Side || (Side = {}));
582
+ var BasicOrderRouteType;
583
+ (function (BasicOrderRouteType) {
584
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC721"] = 0] = "ETH_TO_ERC721";
585
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC1155"] = 1] = "ETH_TO_ERC1155";
586
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC721"] = 2] = "ERC20_TO_ERC721";
587
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC1155"] = 3] = "ERC20_TO_ERC1155";
588
+ BasicOrderRouteType[BasicOrderRouteType["ERC721_TO_ERC20"] = 4] = "ERC721_TO_ERC20";
589
+ BasicOrderRouteType[BasicOrderRouteType["ERC1155_TO_ERC20"] = 5] = "ERC1155_TO_ERC20";
590
+ })(BasicOrderRouteType || (BasicOrderRouteType = {}));
591
+
592
+ function getOrderComponentsFromMessage(orderMessage) {
593
+ const data = JSON.parse(orderMessage);
594
+ const orderComponents = data.message;
595
+ orderComponents.salt = BigNumber.from(orderComponents.salt).toHexString();
596
+ return orderComponents;
597
+ }
598
+
599
+ // Add 20% more gas than estimate to prevent out of gas errors
600
+ // This can always be overwritten by the user signing the transaction
601
+ async function prepareTransaction(transactionMethods) {
602
+ const transaction = await transactionMethods.buildTransaction();
603
+ transaction.gasLimit = await transactionMethods.estimateGas();
604
+ transaction.gasLimit = transaction.gasLimit
605
+ .add(transaction.gasLimit.div(5));
606
+ return transaction;
607
+ }
608
+
609
+ function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
610
+ const considerationItems = order.buy.map((buyItem) => {
611
+ switch (buyItem.item_type) {
612
+ case 'NATIVE':
613
+ return {
614
+ startAmount: buyItem.start_amount,
615
+ endAmount: buyItem.start_amount,
616
+ itemType: ItemType.NATIVE,
617
+ recipient: order.account_address,
618
+ token: constants.AddressZero,
619
+ identifierOrCriteria: '0',
620
+ };
621
+ case 'ERC20':
622
+ return {
623
+ startAmount: buyItem.start_amount,
624
+ endAmount: buyItem.start_amount,
625
+ itemType: ItemType.ERC20,
626
+ recipient: order.account_address,
627
+ token: buyItem.contract_address || constants.AddressZero,
628
+ identifierOrCriteria: '0',
629
+ };
630
+ default: // ERC721
631
+ return {
632
+ startAmount: '1',
633
+ endAmount: '1',
634
+ itemType: ItemType.ERC721,
635
+ recipient: order.account_address,
636
+ token: buyItem.contract_address || constants.AddressZero,
637
+ identifierOrCriteria: '0',
638
+ };
639
+ }
640
+ });
641
+ const fees = order.fees.map((fee) => ({
642
+ startAmount: fee.amount,
643
+ endAmount: fee.amount,
644
+ itemType: order.buy[0].item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
645
+ recipient: fee.recipient,
646
+ token: order.buy[0].item_type === 'ERC20'
647
+ ? order.buy[0].contract_address
648
+ : constants.AddressZero,
649
+ identifierOrCriteria: '0',
650
+ }));
651
+ return {
652
+ conduitKey: constants.HashZero,
653
+ consideration: [...considerationItems, ...fees],
654
+ offer: order.sell.map((sellItem) => {
655
+ const erc721Item = sellItem;
656
+ return {
657
+ startAmount: '1',
658
+ endAmount: '1',
659
+ itemType: ItemType.ERC721,
660
+ token: erc721Item.contract_address,
661
+ identifierOrCriteria: erc721Item.token_id,
662
+ };
663
+ }),
664
+ counter,
665
+ endTime: Math.round(new Date(order.end_time).getTime() / 1000).toString(),
666
+ startTime: Math.round(new Date(order.start_time).getTime() / 1000).toString(),
667
+ salt: order.salt,
668
+ offerer: order.account_address,
669
+ zone: zoneAddress,
670
+ totalOriginalConsiderationItems: 2,
671
+ orderType: OrderType.FULL_RESTRICTED,
672
+ zoneHash: constants.HashZero,
673
+ };
674
+ }
675
+
676
+ class Seaport {
677
+ seaportLibFactory;
678
+ provider;
679
+ seaportContractAddress;
680
+ zoneContractAddress;
681
+ constructor(seaportLibFactory, provider, seaportContractAddress, zoneContractAddress) {
682
+ this.seaportLibFactory = seaportLibFactory;
683
+ this.provider = provider;
684
+ this.seaportContractAddress = seaportContractAddress;
685
+ this.zoneContractAddress = zoneContractAddress;
686
+ }
687
+ async prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
688
+ const { actions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry);
689
+ let approvalTransaction;
690
+ const approvalAction = actions
691
+ .find((action) => action.type === 'approval');
692
+ if (approvalAction) {
693
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
694
+ }
695
+ const createAction = actions
696
+ .find((action) => action.type === 'create');
697
+ if (!createAction) {
698
+ throw new Error('No create order action found');
699
+ }
700
+ const orderMessageToSign = await createAction.getMessageToSign();
701
+ const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
702
+ return {
703
+ unsignedApprovalTransaction: approvalTransaction,
704
+ typedOrderMessageForSigning: await this.getTypedDataFromOrderComponents(orderComponents),
705
+ orderComponents,
706
+ orderHash: this.getSeaportLib().getOrderHash(orderComponents),
707
+ };
708
+ }
709
+ async fulfilOrder(order, account) {
710
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
711
+ const seaportLib = this.getSeaportLib(order);
712
+ const { actions } = await seaportLib.fulfillOrders({
713
+ accountAddress: account,
714
+ fulfillOrderDetails: [{
715
+ order: {
716
+ parameters: orderComponents,
717
+ signature: order.signature,
718
+ },
719
+ extraData: order.protocol_data.operator_signature,
720
+ }],
721
+ });
722
+ let approvalTransaction;
723
+ const approvalAction = actions
724
+ .find((action) => action.type === 'approval');
725
+ if (approvalAction) {
726
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
727
+ }
728
+ const fulfillmentAction = actions
729
+ .find((action) => action.type === 'exchange');
730
+ if (!fulfillmentAction) {
731
+ throw new Error('No exchange action found');
732
+ }
733
+ const fulfillmentTransaction = await prepareTransaction(fulfillmentAction.transactionMethods);
734
+ return {
735
+ unsignedApprovalTransaction: approvalTransaction,
736
+ unsignedFulfillmentTransaction: fulfillmentTransaction,
737
+ };
738
+ }
739
+ async cancelOrder(order, account) {
740
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
741
+ const seaportLib = this.getSeaportLib(order);
742
+ const cancellationTransaction = await seaportLib.cancelOrders([orderComponents], account);
743
+ return prepareTransaction(cancellationTransaction);
744
+ }
745
+ mapImmutableOrderToSeaportOrderComponents(order) {
746
+ const orderCounter = order.protocol_data.counter;
747
+ return mapImmutableOrderToSeaportOrderComponents(order, orderCounter, this.zoneContractAddress);
748
+ }
749
+ createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
750
+ const seaportLib = this.getSeaportLib();
751
+ return seaportLib.createOrder({
752
+ allowPartialFills: false,
753
+ offer: [
754
+ {
755
+ itemType: ItemType.ERC721,
756
+ token: listingItem.contractAddress,
757
+ identifier: listingItem.tokenId,
758
+ },
759
+ ],
760
+ consideration: [
761
+ {
762
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
763
+ amount: considerationItem.amount,
764
+ recipient: offerer,
765
+ },
766
+ {
767
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
768
+ amount: royaltyInfo.amountRequired,
769
+ recipient: royaltyInfo.recipient,
770
+ },
771
+ ],
772
+ startTime: (orderStart.getTime() / 1000).toFixed(0),
773
+ endTime: (orderExpiry.getTime() / 1000).toFixed(0),
774
+ zone: this.zoneContractAddress,
775
+ restrictedByZone: true,
776
+ }, offerer);
777
+ }
778
+ async getTypedDataFromOrderComponents(orderComponents) {
779
+ const { chainId } = await this.provider.getNetwork();
780
+ const domainData = {
781
+ name: SEAPORT_CONTRACT_NAME,
782
+ version: SEAPORT_CONTRACT_VERSION_V1_4,
783
+ chainId,
784
+ verifyingContract: this.seaportContractAddress,
785
+ };
786
+ return {
787
+ domain: domainData,
788
+ types: EIP_712_ORDER_TYPE,
789
+ value: orderComponents,
790
+ };
791
+ }
792
+ getSeaportLib(order) {
793
+ const seaportAddress = order?.protocol_data?.seaport_address ?? this.seaportContractAddress;
794
+ let seaportVersion = SEAPORT_CONTRACT_VERSION_V1_4;
795
+ if (order?.protocol_data?.seaport_version === SEAPORT_CONTRACT_VERSION_V1_5) {
796
+ seaportVersion = SEAPORT_CONTRACT_VERSION_V1_5;
797
+ }
798
+ return this.seaportLibFactory.create(seaportVersion, seaportAddress);
799
+ }
800
+ }
801
+
802
+ class ImmutableApiClient {
803
+ orderbookService;
804
+ chainName;
805
+ seaportAddress;
806
+ constructor(orderbookService, chainName, seaportAddress) {
807
+ this.orderbookService = orderbookService;
808
+ this.chainName = chainName;
809
+ this.seaportAddress = seaportAddress;
810
+ }
811
+ async getListing(listingId) {
812
+ return this.orderbookService.getListing({
813
+ chainName: this.chainName,
814
+ listingId,
815
+ });
816
+ }
817
+ async listListings(listOrderParams) {
818
+ return this.orderbookService.listListings({
819
+ chainName: this.chainName,
820
+ ...listOrderParams,
821
+ });
822
+ }
823
+ async createListing({ orderHash, orderComponents, orderSignature, }) {
824
+ if (orderComponents.offer.length !== 1) {
825
+ throw new Error('Only one item can be listed at a time');
826
+ }
827
+ if (Number(orderComponents.offer[0].itemType) !== ItemType.ERC721) {
828
+ throw new Error('Only ERC721 tokens can be listed');
829
+ }
830
+ const orderTypes = [
831
+ ...orderComponents.consideration.map((c) => c.itemType),
832
+ ];
833
+ const isSameConsiderationType = new Set(orderTypes).size === 1;
834
+ if (!isSameConsiderationType) {
835
+ throw new Error('All consideration items must be of the same type');
836
+ }
837
+ return this.orderbookService.createListing({
838
+ chainName: this.chainName,
839
+ requestBody: {
840
+ order_hash: orderHash,
841
+ account_address: orderComponents.offerer,
842
+ buy: [
843
+ {
844
+ item_type: Number(orderComponents.consideration[0].itemType)
845
+ === ItemType.NATIVE
846
+ ? 'NATIVE'
847
+ : 'ERC20',
848
+ start_amount: orderComponents.consideration[0].startAmount,
849
+ contract_address: orderComponents.consideration[0].token,
850
+ },
851
+ ],
852
+ fees: orderComponents.consideration.length > 1
853
+ ? [
854
+ {
855
+ amount: orderComponents.consideration[1].startAmount,
856
+ recipient: orderComponents.consideration[1].recipient,
857
+ fee_type: Fee.fee_type.ROYALTY,
858
+ },
859
+ ]
860
+ : [],
861
+ end_time: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
862
+ protocol_data: {
863
+ order_type: CreateOrderProtocolData.order_type.FULL_RESTRICTED,
864
+ zone_address: orderComponents.zone,
865
+ seaport_address: this.seaportAddress,
866
+ seaport_version: SEAPORT_CONTRACT_VERSION_V1_4,
867
+ counter: orderComponents.counter.toString(),
868
+ },
869
+ salt: orderComponents.salt,
870
+ sell: [
871
+ {
872
+ contract_address: orderComponents.offer[0].token,
873
+ token_id: orderComponents.offer[0].identifierOrCriteria,
874
+ item_type: 'ERC721',
875
+ },
876
+ ],
877
+ signature: orderSignature,
878
+ start_time: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
879
+ },
880
+ });
881
+ }
882
+ }
883
+
884
+ class ImmutableApiClientFactory {
885
+ chainName;
886
+ seaportAddress;
887
+ orderbookClient;
888
+ constructor(apiEndpoint, chainName, seaportAddress) {
889
+ this.chainName = chainName;
890
+ this.seaportAddress = seaportAddress;
891
+ this.orderbookClient = new OrderBookClient({
892
+ // eslint-disable-next-line @typescript-eslint/naming-convention
893
+ BASE: apiEndpoint,
894
+ });
895
+ }
896
+ create() {
897
+ return new ImmutableApiClient(this.orderbookClient.orders, this.chainName, this.seaportAddress);
898
+ }
899
+ }
900
+
901
+ const DEVNET_CHAIN_NAME = 'imtbl-zkevm-devnet';
902
+ const TESTNET_CHAIN_NAME = 'imtbl-zkevm-testnet';
903
+ const MAINNET_CHAIN_NAME = 'imtbl-zkevm-mainnet';
904
+ function getOrderbookConfig(chainName) {
905
+ switch (chainName) {
906
+ case DEVNET_CHAIN_NAME:
907
+ return {
908
+ seaportContractAddress: '0x41388404Efb7a68Fd31d75CEf71dF91e2BDBa2fb',
909
+ zoneContractAddress: '0xCb5063b0c1dcF4f7fed8E7eaa79faf9859792767',
910
+ apiEndpoint: 'https://order-book-mr.dev.imtbl.com',
911
+ provider: new providers.JsonRpcProvider('https://zkevm-rpc.dev.x.immutable.com'),
912
+ };
913
+ case TESTNET_CHAIN_NAME:
914
+ return {
915
+ seaportContractAddress: '0x45E23dA18804F99Cf67408AeBE85F67c958381Ff',
916
+ zoneContractAddress: '0x25b00b7eb97eab6194798E9B8eF63Aa526D5bd7E',
917
+ apiEndpoint: 'https://order-book-mr.sandbox.imtbl.com',
918
+ provider: new providers.JsonRpcProvider('https://zkevm-rpc.sandbox.x.immutable.com'),
919
+ };
920
+ case MAINNET_CHAIN_NAME:
921
+ // not yet deployed
922
+ return {
923
+ seaportContractAddress: '',
924
+ zoneContractAddress: '',
925
+ apiEndpoint: 'https://order-book-mr.imtbl.com',
926
+ provider: new providers.JsonRpcProvider('https://zkevm-rpc.x.immutable.com'),
927
+ };
928
+ default:
929
+ return null;
930
+ }
931
+ }
932
+
933
+ class ERC721 {
934
+ erc721;
935
+ constructor(erc721) {
936
+ this.erc721 = erc721;
937
+ }
938
+ async royaltyInfo(tokenId, salePrice) {
939
+ const [recipient, royaltyRequired] = await this.erc721.royaltyInfo(tokenId, salePrice);
940
+ return { recipient, amountRequired: royaltyRequired.toString() };
941
+ }
942
+ }
943
+
944
+ /* Autogenerated file. Do not edit manually. */
945
+ /* tslint:disable */
946
+ /* eslint-disable */
947
+ const _abi = [
948
+ {
949
+ inputs: [
950
+ {
951
+ internalType: "address",
952
+ name: "owner_",
953
+ type: "address",
954
+ },
955
+ {
956
+ internalType: "string",
957
+ name: "name_",
958
+ type: "string",
959
+ },
960
+ {
961
+ internalType: "string",
962
+ name: "symbol_",
963
+ type: "string",
964
+ },
965
+ {
966
+ internalType: "string",
967
+ name: "baseURI_",
968
+ type: "string",
969
+ },
970
+ {
971
+ internalType: "string",
972
+ name: "contractURI_",
973
+ type: "string",
974
+ },
975
+ {
976
+ internalType: "address",
977
+ name: "_receiver",
978
+ type: "address",
979
+ },
980
+ {
981
+ internalType: "uint96",
982
+ name: "_feeNumerator",
983
+ type: "uint96",
984
+ },
985
+ ],
986
+ stateMutability: "nonpayable",
987
+ type: "constructor",
988
+ },
989
+ {
990
+ inputs: [
991
+ {
992
+ internalType: "address",
993
+ name: "target",
994
+ type: "address",
995
+ },
996
+ ],
997
+ name: "ApproveTargetNotInAllowlist",
998
+ type: "error",
999
+ },
1000
+ {
1001
+ inputs: [
1002
+ {
1003
+ internalType: "address",
1004
+ name: "caller",
1005
+ type: "address",
1006
+ },
1007
+ ],
1008
+ name: "CallerNotInAllowlist",
1009
+ type: "error",
1010
+ },
1011
+ {
1012
+ anonymous: false,
1013
+ inputs: [
1014
+ {
1015
+ indexed: true,
1016
+ internalType: "address",
1017
+ name: "owner",
1018
+ type: "address",
1019
+ },
1020
+ {
1021
+ indexed: true,
1022
+ internalType: "address",
1023
+ name: "approved",
1024
+ type: "address",
1025
+ },
1026
+ {
1027
+ indexed: true,
1028
+ internalType: "uint256",
1029
+ name: "tokenId",
1030
+ type: "uint256",
1031
+ },
1032
+ ],
1033
+ name: "Approval",
1034
+ type: "event",
1035
+ },
1036
+ {
1037
+ anonymous: false,
1038
+ inputs: [
1039
+ {
1040
+ indexed: true,
1041
+ internalType: "address",
1042
+ name: "owner",
1043
+ type: "address",
1044
+ },
1045
+ {
1046
+ indexed: true,
1047
+ internalType: "address",
1048
+ name: "operator",
1049
+ type: "address",
1050
+ },
1051
+ {
1052
+ indexed: false,
1053
+ internalType: "bool",
1054
+ name: "approved",
1055
+ type: "bool",
1056
+ },
1057
+ ],
1058
+ name: "ApprovalForAll",
1059
+ type: "event",
1060
+ },
1061
+ {
1062
+ anonymous: false,
1063
+ inputs: [
1064
+ {
1065
+ indexed: true,
1066
+ internalType: "bytes32",
1067
+ name: "role",
1068
+ type: "bytes32",
1069
+ },
1070
+ {
1071
+ indexed: true,
1072
+ internalType: "bytes32",
1073
+ name: "previousAdminRole",
1074
+ type: "bytes32",
1075
+ },
1076
+ {
1077
+ indexed: true,
1078
+ internalType: "bytes32",
1079
+ name: "newAdminRole",
1080
+ type: "bytes32",
1081
+ },
1082
+ ],
1083
+ name: "RoleAdminChanged",
1084
+ type: "event",
1085
+ },
1086
+ {
1087
+ anonymous: false,
1088
+ inputs: [
1089
+ {
1090
+ indexed: true,
1091
+ internalType: "bytes32",
1092
+ name: "role",
1093
+ type: "bytes32",
1094
+ },
1095
+ {
1096
+ indexed: true,
1097
+ internalType: "address",
1098
+ name: "account",
1099
+ type: "address",
1100
+ },
1101
+ {
1102
+ indexed: true,
1103
+ internalType: "address",
1104
+ name: "sender",
1105
+ type: "address",
1106
+ },
1107
+ ],
1108
+ name: "RoleGranted",
1109
+ type: "event",
1110
+ },
1111
+ {
1112
+ anonymous: false,
1113
+ inputs: [
1114
+ {
1115
+ indexed: true,
1116
+ internalType: "bytes32",
1117
+ name: "role",
1118
+ type: "bytes32",
1119
+ },
1120
+ {
1121
+ indexed: true,
1122
+ internalType: "address",
1123
+ name: "account",
1124
+ type: "address",
1125
+ },
1126
+ {
1127
+ indexed: true,
1128
+ internalType: "address",
1129
+ name: "sender",
1130
+ type: "address",
1131
+ },
1132
+ ],
1133
+ name: "RoleRevoked",
1134
+ type: "event",
1135
+ },
1136
+ {
1137
+ anonymous: false,
1138
+ inputs: [
1139
+ {
1140
+ indexed: false,
1141
+ internalType: "address",
1142
+ name: "oldRegistry",
1143
+ type: "address",
1144
+ },
1145
+ {
1146
+ indexed: false,
1147
+ internalType: "address",
1148
+ name: "newRegistry",
1149
+ type: "address",
1150
+ },
1151
+ ],
1152
+ name: "RoyaltytAllowlistRegistryUpdated",
1153
+ type: "event",
1154
+ },
1155
+ {
1156
+ anonymous: false,
1157
+ inputs: [
1158
+ {
1159
+ indexed: true,
1160
+ internalType: "address",
1161
+ name: "from",
1162
+ type: "address",
1163
+ },
1164
+ {
1165
+ indexed: true,
1166
+ internalType: "address",
1167
+ name: "to",
1168
+ type: "address",
1169
+ },
1170
+ {
1171
+ indexed: true,
1172
+ internalType: "uint256",
1173
+ name: "tokenId",
1174
+ type: "uint256",
1175
+ },
1176
+ ],
1177
+ name: "Transfer",
1178
+ type: "event",
1179
+ },
1180
+ {
1181
+ inputs: [],
1182
+ name: "DEFAULT_ADMIN_ROLE",
1183
+ outputs: [
1184
+ {
1185
+ internalType: "bytes32",
1186
+ name: "",
1187
+ type: "bytes32",
1188
+ },
1189
+ ],
1190
+ stateMutability: "view",
1191
+ type: "function",
1192
+ },
1193
+ {
1194
+ inputs: [],
1195
+ name: "MINTER_ROLE",
1196
+ outputs: [
1197
+ {
1198
+ internalType: "bytes32",
1199
+ name: "",
1200
+ type: "bytes32",
1201
+ },
1202
+ ],
1203
+ stateMutability: "view",
1204
+ type: "function",
1205
+ },
1206
+ {
1207
+ inputs: [
1208
+ {
1209
+ internalType: "address",
1210
+ name: "to",
1211
+ type: "address",
1212
+ },
1213
+ {
1214
+ internalType: "uint256",
1215
+ name: "tokenId",
1216
+ type: "uint256",
1217
+ },
1218
+ ],
1219
+ name: "approve",
1220
+ outputs: [],
1221
+ stateMutability: "nonpayable",
1222
+ type: "function",
1223
+ },
1224
+ {
1225
+ inputs: [
1226
+ {
1227
+ internalType: "address",
1228
+ name: "owner",
1229
+ type: "address",
1230
+ },
1231
+ ],
1232
+ name: "balanceOf",
1233
+ outputs: [
1234
+ {
1235
+ internalType: "uint256",
1236
+ name: "",
1237
+ type: "uint256",
1238
+ },
1239
+ ],
1240
+ stateMutability: "view",
1241
+ type: "function",
1242
+ },
1243
+ {
1244
+ inputs: [],
1245
+ name: "baseURI",
1246
+ outputs: [
1247
+ {
1248
+ internalType: "string",
1249
+ name: "",
1250
+ type: "string",
1251
+ },
1252
+ ],
1253
+ stateMutability: "view",
1254
+ type: "function",
1255
+ },
1256
+ {
1257
+ inputs: [
1258
+ {
1259
+ internalType: "uint256",
1260
+ name: "tokenId",
1261
+ type: "uint256",
1262
+ },
1263
+ ],
1264
+ name: "burn",
1265
+ outputs: [],
1266
+ stateMutability: "nonpayable",
1267
+ type: "function",
1268
+ },
1269
+ {
1270
+ inputs: [],
1271
+ name: "contractURI",
1272
+ outputs: [
1273
+ {
1274
+ internalType: "string",
1275
+ name: "",
1276
+ type: "string",
1277
+ },
1278
+ ],
1279
+ stateMutability: "view",
1280
+ type: "function",
1281
+ },
1282
+ {
1283
+ inputs: [],
1284
+ name: "getAdmins",
1285
+ outputs: [
1286
+ {
1287
+ internalType: "address[]",
1288
+ name: "",
1289
+ type: "address[]",
1290
+ },
1291
+ ],
1292
+ stateMutability: "view",
1293
+ type: "function",
1294
+ },
1295
+ {
1296
+ inputs: [
1297
+ {
1298
+ internalType: "uint256",
1299
+ name: "tokenId",
1300
+ type: "uint256",
1301
+ },
1302
+ ],
1303
+ name: "getApproved",
1304
+ outputs: [
1305
+ {
1306
+ internalType: "address",
1307
+ name: "",
1308
+ type: "address",
1309
+ },
1310
+ ],
1311
+ stateMutability: "view",
1312
+ type: "function",
1313
+ },
1314
+ {
1315
+ inputs: [
1316
+ {
1317
+ internalType: "bytes32",
1318
+ name: "role",
1319
+ type: "bytes32",
1320
+ },
1321
+ ],
1322
+ name: "getRoleAdmin",
1323
+ outputs: [
1324
+ {
1325
+ internalType: "bytes32",
1326
+ name: "",
1327
+ type: "bytes32",
1328
+ },
1329
+ ],
1330
+ stateMutability: "view",
1331
+ type: "function",
1332
+ },
1333
+ {
1334
+ inputs: [
1335
+ {
1336
+ internalType: "bytes32",
1337
+ name: "role",
1338
+ type: "bytes32",
1339
+ },
1340
+ {
1341
+ internalType: "uint256",
1342
+ name: "index",
1343
+ type: "uint256",
1344
+ },
1345
+ ],
1346
+ name: "getRoleMember",
1347
+ outputs: [
1348
+ {
1349
+ internalType: "address",
1350
+ name: "",
1351
+ type: "address",
1352
+ },
1353
+ ],
1354
+ stateMutability: "view",
1355
+ type: "function",
1356
+ },
1357
+ {
1358
+ inputs: [
1359
+ {
1360
+ internalType: "bytes32",
1361
+ name: "role",
1362
+ type: "bytes32",
1363
+ },
1364
+ ],
1365
+ name: "getRoleMemberCount",
1366
+ outputs: [
1367
+ {
1368
+ internalType: "uint256",
1369
+ name: "",
1370
+ type: "uint256",
1371
+ },
1372
+ ],
1373
+ stateMutability: "view",
1374
+ type: "function",
1375
+ },
1376
+ {
1377
+ inputs: [
1378
+ {
1379
+ internalType: "address",
1380
+ name: "user",
1381
+ type: "address",
1382
+ },
1383
+ ],
1384
+ name: "grantMinterRole",
1385
+ outputs: [],
1386
+ stateMutability: "nonpayable",
1387
+ type: "function",
1388
+ },
1389
+ {
1390
+ inputs: [
1391
+ {
1392
+ internalType: "bytes32",
1393
+ name: "role",
1394
+ type: "bytes32",
1395
+ },
1396
+ {
1397
+ internalType: "address",
1398
+ name: "account",
1399
+ type: "address",
1400
+ },
1401
+ ],
1402
+ name: "grantRole",
1403
+ outputs: [],
1404
+ stateMutability: "nonpayable",
1405
+ type: "function",
1406
+ },
1407
+ {
1408
+ inputs: [
1409
+ {
1410
+ internalType: "bytes32",
1411
+ name: "role",
1412
+ type: "bytes32",
1413
+ },
1414
+ {
1415
+ internalType: "address",
1416
+ name: "account",
1417
+ type: "address",
1418
+ },
1419
+ ],
1420
+ name: "hasRole",
1421
+ outputs: [
1422
+ {
1423
+ internalType: "bool",
1424
+ name: "",
1425
+ type: "bool",
1426
+ },
1427
+ ],
1428
+ stateMutability: "view",
1429
+ type: "function",
1430
+ },
1431
+ {
1432
+ inputs: [
1433
+ {
1434
+ internalType: "address",
1435
+ name: "owner",
1436
+ type: "address",
1437
+ },
1438
+ {
1439
+ internalType: "address",
1440
+ name: "operator",
1441
+ type: "address",
1442
+ },
1443
+ ],
1444
+ name: "isApprovedForAll",
1445
+ outputs: [
1446
+ {
1447
+ internalType: "bool",
1448
+ name: "",
1449
+ type: "bool",
1450
+ },
1451
+ ],
1452
+ stateMutability: "view",
1453
+ type: "function",
1454
+ },
1455
+ {
1456
+ inputs: [
1457
+ {
1458
+ internalType: "address",
1459
+ name: "to",
1460
+ type: "address",
1461
+ },
1462
+ {
1463
+ internalType: "uint256",
1464
+ name: "amount",
1465
+ type: "uint256",
1466
+ },
1467
+ ],
1468
+ name: "mint",
1469
+ outputs: [],
1470
+ stateMutability: "nonpayable",
1471
+ type: "function",
1472
+ },
1473
+ {
1474
+ inputs: [],
1475
+ name: "name",
1476
+ outputs: [
1477
+ {
1478
+ internalType: "string",
1479
+ name: "",
1480
+ type: "string",
1481
+ },
1482
+ ],
1483
+ stateMutability: "view",
1484
+ type: "function",
1485
+ },
1486
+ {
1487
+ inputs: [
1488
+ {
1489
+ internalType: "uint256",
1490
+ name: "tokenId",
1491
+ type: "uint256",
1492
+ },
1493
+ ],
1494
+ name: "ownerOf",
1495
+ outputs: [
1496
+ {
1497
+ internalType: "address",
1498
+ name: "",
1499
+ type: "address",
1500
+ },
1501
+ ],
1502
+ stateMutability: "view",
1503
+ type: "function",
1504
+ },
1505
+ {
1506
+ inputs: [
1507
+ {
1508
+ internalType: "bytes32",
1509
+ name: "role",
1510
+ type: "bytes32",
1511
+ },
1512
+ {
1513
+ internalType: "address",
1514
+ name: "account",
1515
+ type: "address",
1516
+ },
1517
+ ],
1518
+ name: "renounceRole",
1519
+ outputs: [],
1520
+ stateMutability: "nonpayable",
1521
+ type: "function",
1522
+ },
1523
+ {
1524
+ inputs: [
1525
+ {
1526
+ internalType: "address",
1527
+ name: "user",
1528
+ type: "address",
1529
+ },
1530
+ ],
1531
+ name: "revokeMinterRole",
1532
+ outputs: [],
1533
+ stateMutability: "nonpayable",
1534
+ type: "function",
1535
+ },
1536
+ {
1537
+ inputs: [
1538
+ {
1539
+ internalType: "bytes32",
1540
+ name: "role",
1541
+ type: "bytes32",
1542
+ },
1543
+ {
1544
+ internalType: "address",
1545
+ name: "account",
1546
+ type: "address",
1547
+ },
1548
+ ],
1549
+ name: "revokeRole",
1550
+ outputs: [],
1551
+ stateMutability: "nonpayable",
1552
+ type: "function",
1553
+ },
1554
+ {
1555
+ inputs: [],
1556
+ name: "royaltyAllowlist",
1557
+ outputs: [
1558
+ {
1559
+ internalType: "contract IRoyaltyAllowlist",
1560
+ name: "",
1561
+ type: "address",
1562
+ },
1563
+ ],
1564
+ stateMutability: "view",
1565
+ type: "function",
1566
+ },
1567
+ {
1568
+ inputs: [
1569
+ {
1570
+ internalType: "uint256",
1571
+ name: "_tokenId",
1572
+ type: "uint256",
1573
+ },
1574
+ {
1575
+ internalType: "uint256",
1576
+ name: "_salePrice",
1577
+ type: "uint256",
1578
+ },
1579
+ ],
1580
+ name: "royaltyInfo",
1581
+ outputs: [
1582
+ {
1583
+ internalType: "address",
1584
+ name: "",
1585
+ type: "address",
1586
+ },
1587
+ {
1588
+ internalType: "uint256",
1589
+ name: "",
1590
+ type: "uint256",
1591
+ },
1592
+ ],
1593
+ stateMutability: "view",
1594
+ type: "function",
1595
+ },
1596
+ {
1597
+ inputs: [
1598
+ {
1599
+ internalType: "address",
1600
+ name: "from",
1601
+ type: "address",
1602
+ },
1603
+ {
1604
+ internalType: "address",
1605
+ name: "to",
1606
+ type: "address",
1607
+ },
1608
+ {
1609
+ internalType: "uint256",
1610
+ name: "tokenId",
1611
+ type: "uint256",
1612
+ },
1613
+ ],
1614
+ name: "safeTransferFrom",
1615
+ outputs: [],
1616
+ stateMutability: "nonpayable",
1617
+ type: "function",
1618
+ },
1619
+ {
1620
+ inputs: [
1621
+ {
1622
+ internalType: "address",
1623
+ name: "from",
1624
+ type: "address",
1625
+ },
1626
+ {
1627
+ internalType: "address",
1628
+ name: "to",
1629
+ type: "address",
1630
+ },
1631
+ {
1632
+ internalType: "uint256",
1633
+ name: "tokenId",
1634
+ type: "uint256",
1635
+ },
1636
+ {
1637
+ internalType: "bytes",
1638
+ name: "data",
1639
+ type: "bytes",
1640
+ },
1641
+ ],
1642
+ name: "safeTransferFrom",
1643
+ outputs: [],
1644
+ stateMutability: "nonpayable",
1645
+ type: "function",
1646
+ },
1647
+ {
1648
+ inputs: [
1649
+ {
1650
+ internalType: "address",
1651
+ name: "operator",
1652
+ type: "address",
1653
+ },
1654
+ {
1655
+ internalType: "bool",
1656
+ name: "approved",
1657
+ type: "bool",
1658
+ },
1659
+ ],
1660
+ name: "setApprovalForAll",
1661
+ outputs: [],
1662
+ stateMutability: "nonpayable",
1663
+ type: "function",
1664
+ },
1665
+ {
1666
+ inputs: [
1667
+ {
1668
+ internalType: "string",
1669
+ name: "baseURI_",
1670
+ type: "string",
1671
+ },
1672
+ ],
1673
+ name: "setBaseURI",
1674
+ outputs: [],
1675
+ stateMutability: "nonpayable",
1676
+ type: "function",
1677
+ },
1678
+ {
1679
+ inputs: [
1680
+ {
1681
+ internalType: "string",
1682
+ name: "_contractURI",
1683
+ type: "string",
1684
+ },
1685
+ ],
1686
+ name: "setContractURI",
1687
+ outputs: [],
1688
+ stateMutability: "nonpayable",
1689
+ type: "function",
1690
+ },
1691
+ {
1692
+ inputs: [
1693
+ {
1694
+ internalType: "address",
1695
+ name: "_royaltyAllowlist",
1696
+ type: "address",
1697
+ },
1698
+ ],
1699
+ name: "setRoyaltyAllowlistRegistry",
1700
+ outputs: [],
1701
+ stateMutability: "nonpayable",
1702
+ type: "function",
1703
+ },
1704
+ {
1705
+ inputs: [
1706
+ {
1707
+ internalType: "bytes4",
1708
+ name: "interfaceId",
1709
+ type: "bytes4",
1710
+ },
1711
+ ],
1712
+ name: "supportsInterface",
1713
+ outputs: [
1714
+ {
1715
+ internalType: "bool",
1716
+ name: "",
1717
+ type: "bool",
1718
+ },
1719
+ ],
1720
+ stateMutability: "view",
1721
+ type: "function",
1722
+ },
1723
+ {
1724
+ inputs: [],
1725
+ name: "symbol",
1726
+ outputs: [
1727
+ {
1728
+ internalType: "string",
1729
+ name: "",
1730
+ type: "string",
1731
+ },
1732
+ ],
1733
+ stateMutability: "view",
1734
+ type: "function",
1735
+ },
1736
+ {
1737
+ inputs: [
1738
+ {
1739
+ internalType: "uint256",
1740
+ name: "index",
1741
+ type: "uint256",
1742
+ },
1743
+ ],
1744
+ name: "tokenByIndex",
1745
+ outputs: [
1746
+ {
1747
+ internalType: "uint256",
1748
+ name: "",
1749
+ type: "uint256",
1750
+ },
1751
+ ],
1752
+ stateMutability: "view",
1753
+ type: "function",
1754
+ },
1755
+ {
1756
+ inputs: [
1757
+ {
1758
+ internalType: "address",
1759
+ name: "owner",
1760
+ type: "address",
1761
+ },
1762
+ {
1763
+ internalType: "uint256",
1764
+ name: "index",
1765
+ type: "uint256",
1766
+ },
1767
+ ],
1768
+ name: "tokenOfOwnerByIndex",
1769
+ outputs: [
1770
+ {
1771
+ internalType: "uint256",
1772
+ name: "",
1773
+ type: "uint256",
1774
+ },
1775
+ ],
1776
+ stateMutability: "view",
1777
+ type: "function",
1778
+ },
1779
+ {
1780
+ inputs: [
1781
+ {
1782
+ internalType: "uint256",
1783
+ name: "tokenId",
1784
+ type: "uint256",
1785
+ },
1786
+ ],
1787
+ name: "tokenURI",
1788
+ outputs: [
1789
+ {
1790
+ internalType: "string",
1791
+ name: "",
1792
+ type: "string",
1793
+ },
1794
+ ],
1795
+ stateMutability: "view",
1796
+ type: "function",
1797
+ },
1798
+ {
1799
+ inputs: [],
1800
+ name: "totalSupply",
1801
+ outputs: [
1802
+ {
1803
+ internalType: "uint256",
1804
+ name: "",
1805
+ type: "uint256",
1806
+ },
1807
+ ],
1808
+ stateMutability: "view",
1809
+ type: "function",
1810
+ },
1811
+ {
1812
+ inputs: [
1813
+ {
1814
+ internalType: "address",
1815
+ name: "from",
1816
+ type: "address",
1817
+ },
1818
+ {
1819
+ internalType: "address",
1820
+ name: "to",
1821
+ type: "address",
1822
+ },
1823
+ {
1824
+ internalType: "uint256",
1825
+ name: "tokenId",
1826
+ type: "uint256",
1827
+ },
1828
+ ],
1829
+ name: "transferFrom",
1830
+ outputs: [],
1831
+ stateMutability: "nonpayable",
1832
+ type: "function",
1833
+ },
1834
+ ];
1835
+ class ImmutableERC721Base__factory {
1836
+ static abi = _abi;
1837
+ static createInterface() {
1838
+ return new utils.Interface(_abi);
1839
+ }
1840
+ static connect(address, signerOrProvider) {
1841
+ return new Contract(address, _abi, signerOrProvider);
1842
+ }
1843
+ }
1844
+
1845
+ class ERC721Factory {
1846
+ erc721;
1847
+ constructor(contractAddress, provider) {
1848
+ this.erc721 = ImmutableERC721Base__factory.connect(contractAddress, provider);
1849
+ }
1850
+ create() {
1851
+ return new ERC721(this.erc721);
1852
+ }
1853
+ }
1854
+
1855
+ class SeaportLibFactory {
1856
+ defaultSeaportContractAddress;
1857
+ provider;
1858
+ constructor(defaultSeaportContractAddress, provider) {
1859
+ this.defaultSeaportContractAddress = defaultSeaportContractAddress;
1860
+ this.provider = provider;
1861
+ }
1862
+ create(orderSeaportVersion, orderSeaportAddress) {
1863
+ const seaportVersion = orderSeaportVersion ?? SEAPORT_CONTRACT_VERSION_V1_4;
1864
+ const seaportContractAddress = orderSeaportAddress ?? this.defaultSeaportContractAddress;
1865
+ return new Seaport$1(this.provider, {
1866
+ seaportVersion,
1867
+ balanceAndApprovalChecksOnOrderCreation: true,
1868
+ overrides: {
1869
+ contractAddress: seaportContractAddress,
1870
+ },
1871
+ });
1872
+ }
1873
+ }
1874
+
1875
+ /**
1876
+ * zkEVM orderbook SDK
1877
+ * @constructor
1878
+ * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
1879
+ */
1880
+ class Orderbook {
1881
+ apiClient;
1882
+ seaport;
1883
+ orderbookConfig;
1884
+ constructor(config, localConfig) {
1885
+ // either use preconfigured config or local config passed in
1886
+ const maybeConfig = getOrderbookConfig(config.overrides?.chainName) || localConfig;
1887
+ if (!maybeConfig) {
1888
+ throw new Error('Orderbook configuration not passed, either select one of the preseet chainNames or pass in localConfig');
1889
+ }
1890
+ this.orderbookConfig = maybeConfig;
1891
+ const { apiEndpoint } = this.orderbookConfig;
1892
+ if (!apiEndpoint) {
1893
+ throw new Error('API endpoint must be provided as an override');
1894
+ }
1895
+ // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
1896
+ const chainName = config.overrides?.chainName;
1897
+ if (!chainName) {
1898
+ throw new Error('chainName must be provided as an override');
1899
+ }
1900
+ this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.orderbookConfig.seaportContractAddress).create();
1901
+ const seaportLibFactory = new SeaportLibFactory(this.orderbookConfig.seaportContractAddress, this.orderbookConfig.provider);
1902
+ this.seaport = new Seaport(seaportLibFactory, this.orderbookConfig.provider, this.orderbookConfig.seaportContractAddress, this.orderbookConfig.zoneContractAddress);
1903
+ }
1904
+ /**
1905
+ * Get an order by ID
1906
+ * @param {string} listingId - The listingId to find.
1907
+ * @return {ListingResult} The returned order result.
1908
+ */
1909
+ getListing(listingId) {
1910
+ return this.apiClient.getListing(listingId);
1911
+ }
1912
+ /**
1913
+ * List orders. This method is used to get a list of orders filtered by conditions specified
1914
+ * in the params object.
1915
+ * @param {ListOrderParams} listOrderParams - Filtering, ordering and page parameters.
1916
+ * @return {Orders} The paged orders.
1917
+ */
1918
+ listListings(listOrderParams) {
1919
+ return this.apiClient.listListings(listOrderParams);
1920
+ }
1921
+ /**
1922
+ * Get required transactions and messages for signing prior to creating a listing
1923
+ * through the createListing method
1924
+ * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
1925
+ * @return {PrepareListingResponse} PrepareListingResponse includes
1926
+ * the unsigned approval transaction, the typed order message for signing and
1927
+ * the order components that can be submitted to `createListing` with a signature.
1928
+ */
1929
+ async prepareListing({ makerAddress, sell, buy, orderExpiry, }) {
1930
+ const erc721 = new ERC721Factory(sell.contractAddress, this.orderbookConfig.provider).create();
1931
+ const royaltyInfo = await erc721.royaltyInfo(sell.tokenId, buy.amount);
1932
+ return this.seaport.prepareSeaportOrder(makerAddress, sell, buy, royaltyInfo,
1933
+ // Default order start to now
1934
+ new Date(),
1935
+ // Default order expiry to 2 years from now
1936
+ orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
1937
+ }
1938
+ /**
1939
+ * Create an order
1940
+ * @param {CreateListingParams} createListingParams - create an order with the given params.
1941
+ * @return {ListingResult} The result of the order created in the Immutable services.
1942
+ */
1943
+ createListing(createListingParams) {
1944
+ return this.apiClient.createListing(createListingParams);
1945
+ }
1946
+ /**
1947
+ * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
1948
+ * transaction exists it must be signed and submitted to the chain before the fulfilment
1949
+ * transaction can be submitted or it will be reverted.
1950
+ * @param {string} listingId - The listingId to fulfil.
1951
+ * @param {string} fulfillerAddress - The address of the account fulfilling the order.
1952
+ * @return {FulfillOrderResponse} Approval and fulfilment transactions.
1953
+ */
1954
+ async fulfillOrder(listingId, takerAddress) {
1955
+ const orderResult = await this.apiClient.getListing(listingId);
1956
+ if (orderResult.result.status !== OrderStatus.ACTIVE) {
1957
+ throw new Error(`Cannot fulfil order that is not active. Current status: ${orderResult.result.status}`);
1958
+ }
1959
+ return this.seaport.fulfilOrder(orderResult.result, takerAddress);
1960
+ }
1961
+ /**
1962
+ * Get an unsigned cancel order transaction. Orders can only be cancelled by
1963
+ * the account that created them.
1964
+ * @param {string} listingId - The listingId to cancel.
1965
+ * @param {string} accountAddress - The address of the account cancelling the order.
1966
+ * @return {CancelOrderResponse} The unsigned cancel order transaction
1967
+ */
1968
+ async cancelOrder(listingId, accountAddress) {
1969
+ const orderResult = await this.apiClient.getListing(listingId);
1970
+ if (orderResult.result.status !== OrderStatus.ACTIVE
1971
+ && orderResult.result.status !== OrderStatus.INACTIVE
1972
+ && orderResult.result.status !== OrderStatus.PENDING) {
1973
+ throw new Error(`Cannot cancel order with status ${orderResult.result.status}`);
1974
+ }
1975
+ if (orderResult.result.account_address !== accountAddress.toLowerCase()) {
1976
+ throw new Error(`Only account ${orderResult.result.account_address} can cancel order ${listingId}`);
1977
+ }
1978
+ const cancelOrderTransaction = await this.seaport.cancelOrder(orderResult.result, accountAddress);
1979
+ return { unsignedCancelOrderTransaction: cancelOrderTransaction };
1980
+ }
1981
+ }
1982
+
1983
+ const module = 'orderbook';
1984
+
1985
+ export { Orderbook, module };