@imtbl/sdk 0.1.8 → 0.1.9-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,2020 @@
1
+ import axios from 'axios';
2
+ import FormData from 'form-data';
3
+ import { utils, Contract, BigNumber, constants } 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 ListingsService {
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 OrdersService {
471
+ httpRequest;
472
+ constructor(httpRequest) {
473
+ this.httpRequest = httpRequest;
474
+ }
475
+ /**
476
+ * List all listings
477
+ * List all listings
478
+ * @returns ListListingsResult OK response.
479
+ * @throws ApiError
480
+ */
481
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, pageSize, sortBy, sortDirection, pageCursor, }) {
482
+ return this.httpRequest.request({
483
+ method: 'GET',
484
+ url: '/v1/chains/{chain_name}/orders/listings',
485
+ path: {
486
+ 'chain_name': chainName,
487
+ },
488
+ query: {
489
+ 'status': status,
490
+ 'sell_item_contract_address': sellItemContractAddress,
491
+ 'buy_item_contract_address': buyItemContractAddress,
492
+ 'sell_item_token_id': sellItemTokenId,
493
+ 'page_size': pageSize,
494
+ 'sort_by': sortBy,
495
+ 'sort_direction': sortDirection,
496
+ 'page_cursor': pageCursor,
497
+ },
498
+ errors: {
499
+ 400: `Bad Request (400)`,
500
+ 404: `The specified resource was not found (404)`,
501
+ 500: `Internal Server Error (500)`,
502
+ },
503
+ });
504
+ }
505
+ /**
506
+ * Create a listing
507
+ * Create a listing
508
+ * @returns ListingResult Created response.
509
+ * @throws ApiError
510
+ */
511
+ createListing({ chainName, requestBody, }) {
512
+ return this.httpRequest.request({
513
+ method: 'POST',
514
+ url: '/v1/chains/{chain_name}/orders/listings',
515
+ path: {
516
+ 'chain_name': chainName,
517
+ },
518
+ body: requestBody,
519
+ mediaType: 'application/json',
520
+ errors: {
521
+ 400: `Bad Request (400)`,
522
+ 404: `The specified resource was not found (404)`,
523
+ 500: `Internal Server Error (500)`,
524
+ },
525
+ });
526
+ }
527
+ /**
528
+ * Get a single listing by ID
529
+ * Get a single listing by ID
530
+ * @returns ListingResult OK response.
531
+ * @throws ApiError
532
+ */
533
+ getListing({ chainName, listingId, }) {
534
+ return this.httpRequest.request({
535
+ method: 'GET',
536
+ url: '/v1/chains/{chain_name}/orders/listings/{listing_id}',
537
+ path: {
538
+ 'chain_name': chainName,
539
+ 'listing_id': listingId,
540
+ },
541
+ errors: {
542
+ 400: `Bad Request (400)`,
543
+ 404: `The specified resource was not found (404)`,
544
+ 500: `Internal Server Error (500)`,
545
+ },
546
+ });
547
+ }
548
+ }
549
+
550
+ class OrderBookClient {
551
+ listings;
552
+ orders;
553
+ request;
554
+ constructor(config, HttpRequest = AxiosHttpRequest) {
555
+ this.request = new HttpRequest({
556
+ BASE: config?.BASE ?? 'https://order-book-mr.dev.imtbl.com',
557
+ VERSION: config?.VERSION ?? '1.0.0',
558
+ WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
559
+ CREDENTIALS: config?.CREDENTIALS ?? 'include',
560
+ TOKEN: config?.TOKEN,
561
+ USERNAME: config?.USERNAME,
562
+ PASSWORD: config?.PASSWORD,
563
+ HEADERS: config?.HEADERS,
564
+ ENCODE_PATH: config?.ENCODE_PATH,
565
+ });
566
+ this.listings = new ListingsService(this.request);
567
+ this.orders = new OrdersService(this.request);
568
+ }
569
+ }
570
+
571
+ /* istanbul ignore file */
572
+ /* tslint:disable */
573
+ /* eslint-disable */
574
+ var CreateOrderProtocolData;
575
+ (function (CreateOrderProtocolData) {
576
+ (function (order_type) {
577
+ order_type["FULL_RESTRICTED"] = "FULL_RESTRICTED";
578
+ })(CreateOrderProtocolData.order_type || (CreateOrderProtocolData.order_type = {}));
579
+ })(CreateOrderProtocolData || (CreateOrderProtocolData = {}));
580
+
581
+ /* istanbul ignore file */
582
+ /* tslint:disable */
583
+ /* eslint-disable */
584
+ var Fee;
585
+ (function (Fee) {
586
+ (function (fee_type) {
587
+ fee_type["ROYALTY"] = "ROYALTY";
588
+ })(Fee.fee_type || (Fee.fee_type = {}));
589
+ })(Fee || (Fee = {}));
590
+
591
+ /* istanbul ignore file */
592
+ /* tslint:disable */
593
+ /* eslint-disable */
594
+ /**
595
+ * The Order status
596
+ */
597
+ var OrderStatus;
598
+ (function (OrderStatus) {
599
+ OrderStatus["PENDING"] = "PENDING";
600
+ OrderStatus["ACTIVE"] = "ACTIVE";
601
+ OrderStatus["INACTIVE"] = "INACTIVE";
602
+ OrderStatus["FILLED"] = "FILLED";
603
+ OrderStatus["CANCELLED"] = "CANCELLED";
604
+ OrderStatus["EXPIRED"] = "EXPIRED";
605
+ })(OrderStatus || (OrderStatus = {}));
606
+
607
+ /* eslint-disable */
608
+ // TODO: Resolve these from seaport-js.
609
+ // There is some bundling issue that is preventing this from working
610
+ const SEAPORT_CONTRACT_NAME = 'ImmutableSeaport';
611
+ const SEAPORT_CONTRACT_VERSION_V1_4 = '1.4';
612
+ const EIP_712_ORDER_TYPE = {
613
+ OrderComponents: [
614
+ { name: 'offerer', type: 'address' },
615
+ { name: 'zone', type: 'address' },
616
+ { name: 'offer', type: 'OfferItem[]' },
617
+ { name: 'consideration', type: 'ConsiderationItem[]' },
618
+ { name: 'orderType', type: 'uint8' },
619
+ { name: 'startTime', type: 'uint256' },
620
+ { name: 'endTime', type: 'uint256' },
621
+ { name: 'zoneHash', type: 'bytes32' },
622
+ { name: 'salt', type: 'uint256' },
623
+ { name: 'conduitKey', type: 'bytes32' },
624
+ { name: 'counter', type: 'uint256' },
625
+ ],
626
+ OfferItem: [
627
+ { name: 'itemType', type: 'uint8' },
628
+ { name: 'token', type: 'address' },
629
+ { name: 'identifierOrCriteria', type: 'uint256' },
630
+ { name: 'startAmount', type: 'uint256' },
631
+ { name: 'endAmount', type: 'uint256' },
632
+ ],
633
+ ConsiderationItem: [
634
+ { name: 'itemType', type: 'uint8' },
635
+ { name: 'token', type: 'address' },
636
+ { name: 'identifierOrCriteria', type: 'uint256' },
637
+ { name: 'startAmount', type: 'uint256' },
638
+ { name: 'endAmount', type: 'uint256' },
639
+ { name: 'recipient', type: 'address' },
640
+ ],
641
+ };
642
+ var OrderType;
643
+ (function (OrderType) {
644
+ OrderType[OrderType["FULL_OPEN"] = 0] = "FULL_OPEN";
645
+ OrderType[OrderType["PARTIAL_OPEN"] = 1] = "PARTIAL_OPEN";
646
+ OrderType[OrderType["FULL_RESTRICTED"] = 2] = "FULL_RESTRICTED";
647
+ OrderType[OrderType["PARTIAL_RESTRICTED"] = 3] = "PARTIAL_RESTRICTED";
648
+ })(OrderType || (OrderType = {}));
649
+ var ItemType;
650
+ (function (ItemType) {
651
+ ItemType[ItemType["NATIVE"] = 0] = "NATIVE";
652
+ ItemType[ItemType["ERC20"] = 1] = "ERC20";
653
+ ItemType[ItemType["ERC721"] = 2] = "ERC721";
654
+ ItemType[ItemType["ERC1155"] = 3] = "ERC1155";
655
+ ItemType[ItemType["ERC721_WITH_CRITERIA"] = 4] = "ERC721_WITH_CRITERIA";
656
+ ItemType[ItemType["ERC1155_WITH_CRITERIA"] = 5] = "ERC1155_WITH_CRITERIA";
657
+ })(ItemType || (ItemType = {}));
658
+ var Side;
659
+ (function (Side) {
660
+ Side[Side["OFFER"] = 0] = "OFFER";
661
+ Side[Side["CONSIDERATION"] = 1] = "CONSIDERATION";
662
+ })(Side || (Side = {}));
663
+ var BasicOrderRouteType;
664
+ (function (BasicOrderRouteType) {
665
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC721"] = 0] = "ETH_TO_ERC721";
666
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC1155"] = 1] = "ETH_TO_ERC1155";
667
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC721"] = 2] = "ERC20_TO_ERC721";
668
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC1155"] = 3] = "ERC20_TO_ERC1155";
669
+ BasicOrderRouteType[BasicOrderRouteType["ERC721_TO_ERC20"] = 4] = "ERC721_TO_ERC20";
670
+ BasicOrderRouteType[BasicOrderRouteType["ERC1155_TO_ERC20"] = 5] = "ERC1155_TO_ERC20";
671
+ })(BasicOrderRouteType || (BasicOrderRouteType = {}));
672
+
673
+ function getOrderComponentsFromMessage(orderMessage) {
674
+ const data = JSON.parse(orderMessage);
675
+ const orderComponents = data.message;
676
+ orderComponents.salt = BigNumber.from(orderComponents.salt).toHexString();
677
+ return orderComponents;
678
+ }
679
+
680
+ // Add 20% more gas than estimate to prevent out of gas errors
681
+ // This can always be overwritten by the user signing the transaction
682
+ async function prepareTransaction(transactionMethods) {
683
+ const transaction = await transactionMethods.buildTransaction();
684
+ transaction.gasLimit = await transactionMethods.estimateGas();
685
+ transaction.gasLimit = transaction.gasLimit
686
+ .add(transaction.gasLimit.div(5));
687
+ return transaction;
688
+ }
689
+
690
+ function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
691
+ const considerationItems = order.buy.map((buyItem) => {
692
+ switch (buyItem.item_type) {
693
+ case 'NATIVE':
694
+ return {
695
+ startAmount: buyItem.start_amount,
696
+ endAmount: buyItem.start_amount,
697
+ itemType: ItemType.NATIVE,
698
+ recipient: order.account_address,
699
+ token: constants.AddressZero,
700
+ identifierOrCriteria: '0',
701
+ };
702
+ case 'ERC20':
703
+ return {
704
+ startAmount: buyItem.start_amount,
705
+ endAmount: buyItem.start_amount,
706
+ itemType: ItemType.ERC20,
707
+ recipient: order.account_address,
708
+ token: buyItem.contract_address || constants.AddressZero,
709
+ identifierOrCriteria: '0',
710
+ };
711
+ default: // ERC721
712
+ return {
713
+ startAmount: '1',
714
+ endAmount: '1',
715
+ itemType: ItemType.ERC721,
716
+ recipient: order.account_address,
717
+ token: buyItem.contract_address || constants.AddressZero,
718
+ identifierOrCriteria: '0',
719
+ };
720
+ }
721
+ });
722
+ const fees = order.buy_fees.map((fee) => ({
723
+ startAmount: fee.amount,
724
+ endAmount: fee.amount,
725
+ itemType: order.buy[0].item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
726
+ recipient: fee.recipient,
727
+ token: order.buy[0].item_type === 'ERC20'
728
+ ? order.buy[0].contract_address
729
+ : constants.AddressZero,
730
+ identifierOrCriteria: '0',
731
+ }));
732
+ return {
733
+ conduitKey: constants.HashZero,
734
+ consideration: [...considerationItems, ...fees],
735
+ offer: order.sell.map((sellItem) => {
736
+ const erc721Item = sellItem;
737
+ return {
738
+ startAmount: '1',
739
+ endAmount: '1',
740
+ itemType: ItemType.ERC721,
741
+ token: erc721Item.contract_address,
742
+ identifierOrCriteria: erc721Item.token_id,
743
+ };
744
+ }),
745
+ counter,
746
+ endTime: Math.round(new Date(order.end_time).getTime() / 1000).toString(),
747
+ startTime: Math.round(new Date(order.start_time).getTime() / 1000).toString(),
748
+ salt: order.salt,
749
+ offerer: order.account_address,
750
+ zone: zoneAddress,
751
+ totalOriginalConsiderationItems: 2,
752
+ orderType: OrderType.FULL_RESTRICTED,
753
+ zoneHash: constants.HashZero,
754
+ };
755
+ }
756
+
757
+ class Seaport {
758
+ seaport;
759
+ provider;
760
+ seaportContractAddress;
761
+ zoneContractAddress;
762
+ constructor(seaport, provider, seaportContractAddress, zoneContractAddress) {
763
+ this.seaport = seaport;
764
+ this.provider = provider;
765
+ this.seaportContractAddress = seaportContractAddress;
766
+ this.zoneContractAddress = zoneContractAddress;
767
+ }
768
+ async prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
769
+ const { actions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry);
770
+ let approvalTransaction;
771
+ const approvalAction = actions
772
+ .find((action) => action.type === 'approval');
773
+ if (approvalAction) {
774
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
775
+ }
776
+ const createAction = actions
777
+ .find((action) => action.type === 'create');
778
+ if (!createAction) {
779
+ throw new Error('No create order action found');
780
+ }
781
+ const orderMessageToSign = await createAction.getMessageToSign();
782
+ const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
783
+ return {
784
+ unsignedApprovalTransaction: approvalTransaction,
785
+ typedOrderMessageForSigning: await this.getTypedDataFromOrderComponents(orderComponents),
786
+ orderComponents,
787
+ orderHash: await this.seaport.getOrderHash(orderComponents),
788
+ };
789
+ }
790
+ async fulfilOrder(order, account) {
791
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
792
+ const { actions } = await this.seaport.fulfillOrders({
793
+ accountAddress: account,
794
+ fulfillOrderDetails: [{
795
+ order: {
796
+ parameters: orderComponents,
797
+ signature: order.signature,
798
+ },
799
+ extraData: order.protocol_data.operator_signature,
800
+ }],
801
+ });
802
+ let approvalTransaction;
803
+ const approvalAction = actions
804
+ .find((action) => action.type === 'approval');
805
+ if (approvalAction) {
806
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
807
+ }
808
+ const fulfillmentAction = actions
809
+ .find((action) => action.type === 'exchange');
810
+ if (!fulfillmentAction) {
811
+ throw new Error('No exchange action found');
812
+ }
813
+ const fulfillmentTransaction = await prepareTransaction(fulfillmentAction.transactionMethods);
814
+ return {
815
+ unsignedApprovalTransaction: approvalTransaction,
816
+ unsignedFulfillmentTransaction: fulfillmentTransaction,
817
+ };
818
+ }
819
+ async cancelOrder(order, account) {
820
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
821
+ const cancellationTransaction = await this.seaport.cancelOrders([orderComponents], account);
822
+ return prepareTransaction(cancellationTransaction);
823
+ }
824
+ async mapImmutableOrderToSeaportOrderComponents(order) {
825
+ const counterForOfferer = await this.seaport.getCounter(order.account_address);
826
+ return mapImmutableOrderToSeaportOrderComponents(order, counterForOfferer.toString(), this.zoneContractAddress);
827
+ }
828
+ createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
829
+ return this.seaport.createOrder({
830
+ allowPartialFills: false,
831
+ offer: [
832
+ {
833
+ itemType: ItemType.ERC721,
834
+ token: listingItem.contractAddress,
835
+ identifier: listingItem.tokenId,
836
+ },
837
+ ],
838
+ consideration: [
839
+ {
840
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
841
+ amount: considerationItem.amount,
842
+ recipient: offerer,
843
+ },
844
+ {
845
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
846
+ amount: royaltyInfo.amountRequired,
847
+ recipient: royaltyInfo.recipient,
848
+ },
849
+ ],
850
+ startTime: (orderStart.getTime() / 1000).toFixed(0),
851
+ endTime: (orderExpiry.getTime() / 1000).toFixed(0),
852
+ zone: this.zoneContractAddress,
853
+ restrictedByZone: true,
854
+ }, offerer);
855
+ }
856
+ async getTypedDataFromOrderComponents(orderComponents) {
857
+ const { chainId } = await this.provider.getNetwork();
858
+ const domainData = {
859
+ name: SEAPORT_CONTRACT_NAME,
860
+ version: SEAPORT_CONTRACT_VERSION_V1_4,
861
+ chainId,
862
+ verifyingContract: this.seaportContractAddress,
863
+ };
864
+ return {
865
+ domain: domainData,
866
+ types: EIP_712_ORDER_TYPE,
867
+ value: orderComponents,
868
+ };
869
+ }
870
+ }
871
+
872
+ class SeaportFactory {
873
+ seaportContractAddress;
874
+ zoneContractAddress;
875
+ provider;
876
+ seaport;
877
+ constructor(seaportContractAddress, zoneContractAddress, provider) {
878
+ this.seaportContractAddress = seaportContractAddress;
879
+ this.zoneContractAddress = zoneContractAddress;
880
+ this.provider = provider;
881
+ this.seaport = new Seaport$1(provider, {
882
+ seaportVersion: '1.4',
883
+ balanceAndApprovalChecksOnOrderCreation: true,
884
+ overrides: {
885
+ contractAddress: seaportContractAddress,
886
+ },
887
+ });
888
+ }
889
+ create() {
890
+ return new Seaport(this.seaport, this.provider, this.seaportContractAddress, this.zoneContractAddress);
891
+ }
892
+ }
893
+
894
+ class ImmutableApiClient {
895
+ orderbookService;
896
+ chainName;
897
+ seaportAddress;
898
+ constructor(orderbookService, chainName, seaportAddress) {
899
+ this.orderbookService = orderbookService;
900
+ this.chainName = chainName;
901
+ this.seaportAddress = seaportAddress;
902
+ }
903
+ async getListing(listingId) {
904
+ return this.orderbookService.getListing({
905
+ chainName: this.chainName,
906
+ listingId,
907
+ });
908
+ }
909
+ async listListings(listOrderParams) {
910
+ return this.orderbookService.listListings({
911
+ chainName: this.chainName,
912
+ ...listOrderParams,
913
+ });
914
+ }
915
+ async createListing({ orderHash, orderComponents, offerer, orderSignature, }) {
916
+ if (orderComponents.offer.length !== 1) {
917
+ throw new Error('Only one item can be listed at a time');
918
+ }
919
+ if (Number(orderComponents.offer[0].itemType) !== ItemType.ERC721) {
920
+ throw new Error('Only ERC721 tokens can be listed');
921
+ }
922
+ const orderTypes = [
923
+ ...orderComponents.consideration.map((c) => c.itemType),
924
+ ];
925
+ const isSameConsiderationType = new Set(orderTypes).size === 1;
926
+ if (!isSameConsiderationType) {
927
+ throw new Error('All consideration items must be of the same type');
928
+ }
929
+ return this.orderbookService.createListing({
930
+ chainName: this.chainName,
931
+ requestBody: {
932
+ order_hash: orderHash,
933
+ account_address: offerer,
934
+ buy: [
935
+ {
936
+ item_type: Number(orderComponents.consideration[0].itemType)
937
+ === ItemType.NATIVE
938
+ ? 'NATIVE'
939
+ : 'ERC20',
940
+ start_amount: orderComponents.consideration[0].startAmount,
941
+ contract_address: orderComponents.consideration[0].token,
942
+ },
943
+ ],
944
+ buy_fees: orderComponents.consideration.length > 1
945
+ ? [
946
+ {
947
+ amount: orderComponents.consideration[1].startAmount,
948
+ recipient: orderComponents.consideration[1].recipient,
949
+ fee_type: Fee.fee_type.ROYALTY,
950
+ },
951
+ ]
952
+ : [],
953
+ end_time: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
954
+ protocol_data: {
955
+ order_type: CreateOrderProtocolData.order_type.FULL_RESTRICTED,
956
+ zone_address: orderComponents.zone,
957
+ seaport_address: this.seaportAddress,
958
+ seaport_version: SEAPORT_CONTRACT_VERSION_V1_4,
959
+ counter: orderComponents.counter.toString(),
960
+ },
961
+ salt: orderComponents.salt,
962
+ sell: [
963
+ {
964
+ contract_address: orderComponents.offer[0].token,
965
+ token_id: orderComponents.offer[0].identifierOrCriteria,
966
+ item_type: 'ERC721',
967
+ },
968
+ ],
969
+ signature: orderSignature,
970
+ start_time: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
971
+ },
972
+ });
973
+ }
974
+ }
975
+
976
+ class ImmutableApiClientFactory {
977
+ chainName;
978
+ seaportAddress;
979
+ orderbookClient;
980
+ constructor(apiEndpoint, chainName, seaportAddress) {
981
+ this.chainName = chainName;
982
+ this.seaportAddress = seaportAddress;
983
+ this.orderbookClient = new OrderBookClient({
984
+ // eslint-disable-next-line @typescript-eslint/naming-convention
985
+ BASE: apiEndpoint,
986
+ });
987
+ }
988
+ create() {
989
+ return new ImmutableApiClient(this.orderbookClient.orders, this.chainName, this.seaportAddress);
990
+ }
991
+ }
992
+
993
+ class ERC721 {
994
+ erc721;
995
+ constructor(erc721) {
996
+ this.erc721 = erc721;
997
+ }
998
+ async royaltyInfo(tokenId, salePrice) {
999
+ const [recipient, royaltyRequired] = await this.erc721.royaltyInfo(tokenId, salePrice);
1000
+ return { recipient, amountRequired: royaltyRequired.toString() };
1001
+ }
1002
+ }
1003
+
1004
+ /* Autogenerated file. Do not edit manually. */
1005
+ /* tslint:disable */
1006
+ /* eslint-disable */
1007
+ const _abi = [
1008
+ {
1009
+ inputs: [
1010
+ {
1011
+ internalType: "address",
1012
+ name: "owner_",
1013
+ type: "address",
1014
+ },
1015
+ {
1016
+ internalType: "string",
1017
+ name: "name_",
1018
+ type: "string",
1019
+ },
1020
+ {
1021
+ internalType: "string",
1022
+ name: "symbol_",
1023
+ type: "string",
1024
+ },
1025
+ {
1026
+ internalType: "string",
1027
+ name: "baseURI_",
1028
+ type: "string",
1029
+ },
1030
+ {
1031
+ internalType: "string",
1032
+ name: "contractURI_",
1033
+ type: "string",
1034
+ },
1035
+ {
1036
+ internalType: "address",
1037
+ name: "_receiver",
1038
+ type: "address",
1039
+ },
1040
+ {
1041
+ internalType: "uint96",
1042
+ name: "_feeNumerator",
1043
+ type: "uint96",
1044
+ },
1045
+ ],
1046
+ stateMutability: "nonpayable",
1047
+ type: "constructor",
1048
+ },
1049
+ {
1050
+ inputs: [
1051
+ {
1052
+ internalType: "address",
1053
+ name: "target",
1054
+ type: "address",
1055
+ },
1056
+ ],
1057
+ name: "ApproveTargetNotInAllowlist",
1058
+ type: "error",
1059
+ },
1060
+ {
1061
+ inputs: [
1062
+ {
1063
+ internalType: "address",
1064
+ name: "caller",
1065
+ type: "address",
1066
+ },
1067
+ ],
1068
+ name: "CallerNotInAllowlist",
1069
+ type: "error",
1070
+ },
1071
+ {
1072
+ anonymous: false,
1073
+ inputs: [
1074
+ {
1075
+ indexed: true,
1076
+ internalType: "address",
1077
+ name: "owner",
1078
+ type: "address",
1079
+ },
1080
+ {
1081
+ indexed: true,
1082
+ internalType: "address",
1083
+ name: "approved",
1084
+ type: "address",
1085
+ },
1086
+ {
1087
+ indexed: true,
1088
+ internalType: "uint256",
1089
+ name: "tokenId",
1090
+ type: "uint256",
1091
+ },
1092
+ ],
1093
+ name: "Approval",
1094
+ type: "event",
1095
+ },
1096
+ {
1097
+ anonymous: false,
1098
+ inputs: [
1099
+ {
1100
+ indexed: true,
1101
+ internalType: "address",
1102
+ name: "owner",
1103
+ type: "address",
1104
+ },
1105
+ {
1106
+ indexed: true,
1107
+ internalType: "address",
1108
+ name: "operator",
1109
+ type: "address",
1110
+ },
1111
+ {
1112
+ indexed: false,
1113
+ internalType: "bool",
1114
+ name: "approved",
1115
+ type: "bool",
1116
+ },
1117
+ ],
1118
+ name: "ApprovalForAll",
1119
+ type: "event",
1120
+ },
1121
+ {
1122
+ anonymous: false,
1123
+ inputs: [
1124
+ {
1125
+ indexed: true,
1126
+ internalType: "bytes32",
1127
+ name: "role",
1128
+ type: "bytes32",
1129
+ },
1130
+ {
1131
+ indexed: true,
1132
+ internalType: "bytes32",
1133
+ name: "previousAdminRole",
1134
+ type: "bytes32",
1135
+ },
1136
+ {
1137
+ indexed: true,
1138
+ internalType: "bytes32",
1139
+ name: "newAdminRole",
1140
+ type: "bytes32",
1141
+ },
1142
+ ],
1143
+ name: "RoleAdminChanged",
1144
+ type: "event",
1145
+ },
1146
+ {
1147
+ anonymous: false,
1148
+ inputs: [
1149
+ {
1150
+ indexed: true,
1151
+ internalType: "bytes32",
1152
+ name: "role",
1153
+ type: "bytes32",
1154
+ },
1155
+ {
1156
+ indexed: true,
1157
+ internalType: "address",
1158
+ name: "account",
1159
+ type: "address",
1160
+ },
1161
+ {
1162
+ indexed: true,
1163
+ internalType: "address",
1164
+ name: "sender",
1165
+ type: "address",
1166
+ },
1167
+ ],
1168
+ name: "RoleGranted",
1169
+ type: "event",
1170
+ },
1171
+ {
1172
+ anonymous: false,
1173
+ inputs: [
1174
+ {
1175
+ indexed: true,
1176
+ internalType: "bytes32",
1177
+ name: "role",
1178
+ type: "bytes32",
1179
+ },
1180
+ {
1181
+ indexed: true,
1182
+ internalType: "address",
1183
+ name: "account",
1184
+ type: "address",
1185
+ },
1186
+ {
1187
+ indexed: true,
1188
+ internalType: "address",
1189
+ name: "sender",
1190
+ type: "address",
1191
+ },
1192
+ ],
1193
+ name: "RoleRevoked",
1194
+ type: "event",
1195
+ },
1196
+ {
1197
+ anonymous: false,
1198
+ inputs: [
1199
+ {
1200
+ indexed: false,
1201
+ internalType: "address",
1202
+ name: "oldRegistry",
1203
+ type: "address",
1204
+ },
1205
+ {
1206
+ indexed: false,
1207
+ internalType: "address",
1208
+ name: "newRegistry",
1209
+ type: "address",
1210
+ },
1211
+ ],
1212
+ name: "RoyaltytAllowlistRegistryUpdated",
1213
+ type: "event",
1214
+ },
1215
+ {
1216
+ anonymous: false,
1217
+ inputs: [
1218
+ {
1219
+ indexed: true,
1220
+ internalType: "address",
1221
+ name: "from",
1222
+ type: "address",
1223
+ },
1224
+ {
1225
+ indexed: true,
1226
+ internalType: "address",
1227
+ name: "to",
1228
+ type: "address",
1229
+ },
1230
+ {
1231
+ indexed: true,
1232
+ internalType: "uint256",
1233
+ name: "tokenId",
1234
+ type: "uint256",
1235
+ },
1236
+ ],
1237
+ name: "Transfer",
1238
+ type: "event",
1239
+ },
1240
+ {
1241
+ inputs: [],
1242
+ name: "DEFAULT_ADMIN_ROLE",
1243
+ outputs: [
1244
+ {
1245
+ internalType: "bytes32",
1246
+ name: "",
1247
+ type: "bytes32",
1248
+ },
1249
+ ],
1250
+ stateMutability: "view",
1251
+ type: "function",
1252
+ },
1253
+ {
1254
+ inputs: [],
1255
+ name: "MINTER_ROLE",
1256
+ outputs: [
1257
+ {
1258
+ internalType: "bytes32",
1259
+ name: "",
1260
+ type: "bytes32",
1261
+ },
1262
+ ],
1263
+ stateMutability: "view",
1264
+ type: "function",
1265
+ },
1266
+ {
1267
+ inputs: [
1268
+ {
1269
+ internalType: "address",
1270
+ name: "to",
1271
+ type: "address",
1272
+ },
1273
+ {
1274
+ internalType: "uint256",
1275
+ name: "tokenId",
1276
+ type: "uint256",
1277
+ },
1278
+ ],
1279
+ name: "approve",
1280
+ outputs: [],
1281
+ stateMutability: "nonpayable",
1282
+ type: "function",
1283
+ },
1284
+ {
1285
+ inputs: [
1286
+ {
1287
+ internalType: "address",
1288
+ name: "owner",
1289
+ type: "address",
1290
+ },
1291
+ ],
1292
+ name: "balanceOf",
1293
+ outputs: [
1294
+ {
1295
+ internalType: "uint256",
1296
+ name: "",
1297
+ type: "uint256",
1298
+ },
1299
+ ],
1300
+ stateMutability: "view",
1301
+ type: "function",
1302
+ },
1303
+ {
1304
+ inputs: [],
1305
+ name: "baseURI",
1306
+ outputs: [
1307
+ {
1308
+ internalType: "string",
1309
+ name: "",
1310
+ type: "string",
1311
+ },
1312
+ ],
1313
+ stateMutability: "view",
1314
+ type: "function",
1315
+ },
1316
+ {
1317
+ inputs: [
1318
+ {
1319
+ internalType: "uint256",
1320
+ name: "tokenId",
1321
+ type: "uint256",
1322
+ },
1323
+ ],
1324
+ name: "burn",
1325
+ outputs: [],
1326
+ stateMutability: "nonpayable",
1327
+ type: "function",
1328
+ },
1329
+ {
1330
+ inputs: [],
1331
+ name: "contractURI",
1332
+ outputs: [
1333
+ {
1334
+ internalType: "string",
1335
+ name: "",
1336
+ type: "string",
1337
+ },
1338
+ ],
1339
+ stateMutability: "view",
1340
+ type: "function",
1341
+ },
1342
+ {
1343
+ inputs: [],
1344
+ name: "getAdmins",
1345
+ outputs: [
1346
+ {
1347
+ internalType: "address[]",
1348
+ name: "",
1349
+ type: "address[]",
1350
+ },
1351
+ ],
1352
+ stateMutability: "view",
1353
+ type: "function",
1354
+ },
1355
+ {
1356
+ inputs: [
1357
+ {
1358
+ internalType: "uint256",
1359
+ name: "tokenId",
1360
+ type: "uint256",
1361
+ },
1362
+ ],
1363
+ name: "getApproved",
1364
+ outputs: [
1365
+ {
1366
+ internalType: "address",
1367
+ name: "",
1368
+ type: "address",
1369
+ },
1370
+ ],
1371
+ stateMutability: "view",
1372
+ type: "function",
1373
+ },
1374
+ {
1375
+ inputs: [
1376
+ {
1377
+ internalType: "bytes32",
1378
+ name: "role",
1379
+ type: "bytes32",
1380
+ },
1381
+ ],
1382
+ name: "getRoleAdmin",
1383
+ outputs: [
1384
+ {
1385
+ internalType: "bytes32",
1386
+ name: "",
1387
+ type: "bytes32",
1388
+ },
1389
+ ],
1390
+ stateMutability: "view",
1391
+ type: "function",
1392
+ },
1393
+ {
1394
+ inputs: [
1395
+ {
1396
+ internalType: "bytes32",
1397
+ name: "role",
1398
+ type: "bytes32",
1399
+ },
1400
+ {
1401
+ internalType: "uint256",
1402
+ name: "index",
1403
+ type: "uint256",
1404
+ },
1405
+ ],
1406
+ name: "getRoleMember",
1407
+ outputs: [
1408
+ {
1409
+ internalType: "address",
1410
+ name: "",
1411
+ type: "address",
1412
+ },
1413
+ ],
1414
+ stateMutability: "view",
1415
+ type: "function",
1416
+ },
1417
+ {
1418
+ inputs: [
1419
+ {
1420
+ internalType: "bytes32",
1421
+ name: "role",
1422
+ type: "bytes32",
1423
+ },
1424
+ ],
1425
+ name: "getRoleMemberCount",
1426
+ outputs: [
1427
+ {
1428
+ internalType: "uint256",
1429
+ name: "",
1430
+ type: "uint256",
1431
+ },
1432
+ ],
1433
+ stateMutability: "view",
1434
+ type: "function",
1435
+ },
1436
+ {
1437
+ inputs: [
1438
+ {
1439
+ internalType: "address",
1440
+ name: "user",
1441
+ type: "address",
1442
+ },
1443
+ ],
1444
+ name: "grantMinterRole",
1445
+ outputs: [],
1446
+ stateMutability: "nonpayable",
1447
+ type: "function",
1448
+ },
1449
+ {
1450
+ inputs: [
1451
+ {
1452
+ internalType: "bytes32",
1453
+ name: "role",
1454
+ type: "bytes32",
1455
+ },
1456
+ {
1457
+ internalType: "address",
1458
+ name: "account",
1459
+ type: "address",
1460
+ },
1461
+ ],
1462
+ name: "grantRole",
1463
+ outputs: [],
1464
+ stateMutability: "nonpayable",
1465
+ type: "function",
1466
+ },
1467
+ {
1468
+ inputs: [
1469
+ {
1470
+ internalType: "bytes32",
1471
+ name: "role",
1472
+ type: "bytes32",
1473
+ },
1474
+ {
1475
+ internalType: "address",
1476
+ name: "account",
1477
+ type: "address",
1478
+ },
1479
+ ],
1480
+ name: "hasRole",
1481
+ outputs: [
1482
+ {
1483
+ internalType: "bool",
1484
+ name: "",
1485
+ type: "bool",
1486
+ },
1487
+ ],
1488
+ stateMutability: "view",
1489
+ type: "function",
1490
+ },
1491
+ {
1492
+ inputs: [
1493
+ {
1494
+ internalType: "address",
1495
+ name: "owner",
1496
+ type: "address",
1497
+ },
1498
+ {
1499
+ internalType: "address",
1500
+ name: "operator",
1501
+ type: "address",
1502
+ },
1503
+ ],
1504
+ name: "isApprovedForAll",
1505
+ outputs: [
1506
+ {
1507
+ internalType: "bool",
1508
+ name: "",
1509
+ type: "bool",
1510
+ },
1511
+ ],
1512
+ stateMutability: "view",
1513
+ type: "function",
1514
+ },
1515
+ {
1516
+ inputs: [
1517
+ {
1518
+ internalType: "address",
1519
+ name: "to",
1520
+ type: "address",
1521
+ },
1522
+ {
1523
+ internalType: "uint256",
1524
+ name: "amount",
1525
+ type: "uint256",
1526
+ },
1527
+ ],
1528
+ name: "mint",
1529
+ outputs: [],
1530
+ stateMutability: "nonpayable",
1531
+ type: "function",
1532
+ },
1533
+ {
1534
+ inputs: [],
1535
+ name: "name",
1536
+ outputs: [
1537
+ {
1538
+ internalType: "string",
1539
+ name: "",
1540
+ type: "string",
1541
+ },
1542
+ ],
1543
+ stateMutability: "view",
1544
+ type: "function",
1545
+ },
1546
+ {
1547
+ inputs: [
1548
+ {
1549
+ internalType: "uint256",
1550
+ name: "tokenId",
1551
+ type: "uint256",
1552
+ },
1553
+ ],
1554
+ name: "ownerOf",
1555
+ outputs: [
1556
+ {
1557
+ internalType: "address",
1558
+ name: "",
1559
+ type: "address",
1560
+ },
1561
+ ],
1562
+ stateMutability: "view",
1563
+ type: "function",
1564
+ },
1565
+ {
1566
+ inputs: [
1567
+ {
1568
+ internalType: "bytes32",
1569
+ name: "role",
1570
+ type: "bytes32",
1571
+ },
1572
+ {
1573
+ internalType: "address",
1574
+ name: "account",
1575
+ type: "address",
1576
+ },
1577
+ ],
1578
+ name: "renounceRole",
1579
+ outputs: [],
1580
+ stateMutability: "nonpayable",
1581
+ type: "function",
1582
+ },
1583
+ {
1584
+ inputs: [
1585
+ {
1586
+ internalType: "address",
1587
+ name: "user",
1588
+ type: "address",
1589
+ },
1590
+ ],
1591
+ name: "revokeMinterRole",
1592
+ outputs: [],
1593
+ stateMutability: "nonpayable",
1594
+ type: "function",
1595
+ },
1596
+ {
1597
+ inputs: [
1598
+ {
1599
+ internalType: "bytes32",
1600
+ name: "role",
1601
+ type: "bytes32",
1602
+ },
1603
+ {
1604
+ internalType: "address",
1605
+ name: "account",
1606
+ type: "address",
1607
+ },
1608
+ ],
1609
+ name: "revokeRole",
1610
+ outputs: [],
1611
+ stateMutability: "nonpayable",
1612
+ type: "function",
1613
+ },
1614
+ {
1615
+ inputs: [],
1616
+ name: "royaltyAllowlist",
1617
+ outputs: [
1618
+ {
1619
+ internalType: "contract IRoyaltyAllowlist",
1620
+ name: "",
1621
+ type: "address",
1622
+ },
1623
+ ],
1624
+ stateMutability: "view",
1625
+ type: "function",
1626
+ },
1627
+ {
1628
+ inputs: [
1629
+ {
1630
+ internalType: "uint256",
1631
+ name: "_tokenId",
1632
+ type: "uint256",
1633
+ },
1634
+ {
1635
+ internalType: "uint256",
1636
+ name: "_salePrice",
1637
+ type: "uint256",
1638
+ },
1639
+ ],
1640
+ name: "royaltyInfo",
1641
+ outputs: [
1642
+ {
1643
+ internalType: "address",
1644
+ name: "",
1645
+ type: "address",
1646
+ },
1647
+ {
1648
+ internalType: "uint256",
1649
+ name: "",
1650
+ type: "uint256",
1651
+ },
1652
+ ],
1653
+ stateMutability: "view",
1654
+ type: "function",
1655
+ },
1656
+ {
1657
+ inputs: [
1658
+ {
1659
+ internalType: "address",
1660
+ name: "from",
1661
+ type: "address",
1662
+ },
1663
+ {
1664
+ internalType: "address",
1665
+ name: "to",
1666
+ type: "address",
1667
+ },
1668
+ {
1669
+ internalType: "uint256",
1670
+ name: "tokenId",
1671
+ type: "uint256",
1672
+ },
1673
+ ],
1674
+ name: "safeTransferFrom",
1675
+ outputs: [],
1676
+ stateMutability: "nonpayable",
1677
+ type: "function",
1678
+ },
1679
+ {
1680
+ inputs: [
1681
+ {
1682
+ internalType: "address",
1683
+ name: "from",
1684
+ type: "address",
1685
+ },
1686
+ {
1687
+ internalType: "address",
1688
+ name: "to",
1689
+ type: "address",
1690
+ },
1691
+ {
1692
+ internalType: "uint256",
1693
+ name: "tokenId",
1694
+ type: "uint256",
1695
+ },
1696
+ {
1697
+ internalType: "bytes",
1698
+ name: "data",
1699
+ type: "bytes",
1700
+ },
1701
+ ],
1702
+ name: "safeTransferFrom",
1703
+ outputs: [],
1704
+ stateMutability: "nonpayable",
1705
+ type: "function",
1706
+ },
1707
+ {
1708
+ inputs: [
1709
+ {
1710
+ internalType: "address",
1711
+ name: "operator",
1712
+ type: "address",
1713
+ },
1714
+ {
1715
+ internalType: "bool",
1716
+ name: "approved",
1717
+ type: "bool",
1718
+ },
1719
+ ],
1720
+ name: "setApprovalForAll",
1721
+ outputs: [],
1722
+ stateMutability: "nonpayable",
1723
+ type: "function",
1724
+ },
1725
+ {
1726
+ inputs: [
1727
+ {
1728
+ internalType: "string",
1729
+ name: "baseURI_",
1730
+ type: "string",
1731
+ },
1732
+ ],
1733
+ name: "setBaseURI",
1734
+ outputs: [],
1735
+ stateMutability: "nonpayable",
1736
+ type: "function",
1737
+ },
1738
+ {
1739
+ inputs: [
1740
+ {
1741
+ internalType: "string",
1742
+ name: "_contractURI",
1743
+ type: "string",
1744
+ },
1745
+ ],
1746
+ name: "setContractURI",
1747
+ outputs: [],
1748
+ stateMutability: "nonpayable",
1749
+ type: "function",
1750
+ },
1751
+ {
1752
+ inputs: [
1753
+ {
1754
+ internalType: "address",
1755
+ name: "_royaltyAllowlist",
1756
+ type: "address",
1757
+ },
1758
+ ],
1759
+ name: "setRoyaltyAllowlistRegistry",
1760
+ outputs: [],
1761
+ stateMutability: "nonpayable",
1762
+ type: "function",
1763
+ },
1764
+ {
1765
+ inputs: [
1766
+ {
1767
+ internalType: "bytes4",
1768
+ name: "interfaceId",
1769
+ type: "bytes4",
1770
+ },
1771
+ ],
1772
+ name: "supportsInterface",
1773
+ outputs: [
1774
+ {
1775
+ internalType: "bool",
1776
+ name: "",
1777
+ type: "bool",
1778
+ },
1779
+ ],
1780
+ stateMutability: "view",
1781
+ type: "function",
1782
+ },
1783
+ {
1784
+ inputs: [],
1785
+ name: "symbol",
1786
+ outputs: [
1787
+ {
1788
+ internalType: "string",
1789
+ name: "",
1790
+ type: "string",
1791
+ },
1792
+ ],
1793
+ stateMutability: "view",
1794
+ type: "function",
1795
+ },
1796
+ {
1797
+ inputs: [
1798
+ {
1799
+ internalType: "uint256",
1800
+ name: "index",
1801
+ type: "uint256",
1802
+ },
1803
+ ],
1804
+ name: "tokenByIndex",
1805
+ outputs: [
1806
+ {
1807
+ internalType: "uint256",
1808
+ name: "",
1809
+ type: "uint256",
1810
+ },
1811
+ ],
1812
+ stateMutability: "view",
1813
+ type: "function",
1814
+ },
1815
+ {
1816
+ inputs: [
1817
+ {
1818
+ internalType: "address",
1819
+ name: "owner",
1820
+ type: "address",
1821
+ },
1822
+ {
1823
+ internalType: "uint256",
1824
+ name: "index",
1825
+ type: "uint256",
1826
+ },
1827
+ ],
1828
+ name: "tokenOfOwnerByIndex",
1829
+ outputs: [
1830
+ {
1831
+ internalType: "uint256",
1832
+ name: "",
1833
+ type: "uint256",
1834
+ },
1835
+ ],
1836
+ stateMutability: "view",
1837
+ type: "function",
1838
+ },
1839
+ {
1840
+ inputs: [
1841
+ {
1842
+ internalType: "uint256",
1843
+ name: "tokenId",
1844
+ type: "uint256",
1845
+ },
1846
+ ],
1847
+ name: "tokenURI",
1848
+ outputs: [
1849
+ {
1850
+ internalType: "string",
1851
+ name: "",
1852
+ type: "string",
1853
+ },
1854
+ ],
1855
+ stateMutability: "view",
1856
+ type: "function",
1857
+ },
1858
+ {
1859
+ inputs: [],
1860
+ name: "totalSupply",
1861
+ outputs: [
1862
+ {
1863
+ internalType: "uint256",
1864
+ name: "",
1865
+ type: "uint256",
1866
+ },
1867
+ ],
1868
+ stateMutability: "view",
1869
+ type: "function",
1870
+ },
1871
+ {
1872
+ inputs: [
1873
+ {
1874
+ internalType: "address",
1875
+ name: "from",
1876
+ type: "address",
1877
+ },
1878
+ {
1879
+ internalType: "address",
1880
+ name: "to",
1881
+ type: "address",
1882
+ },
1883
+ {
1884
+ internalType: "uint256",
1885
+ name: "tokenId",
1886
+ type: "uint256",
1887
+ },
1888
+ ],
1889
+ name: "transferFrom",
1890
+ outputs: [],
1891
+ stateMutability: "nonpayable",
1892
+ type: "function",
1893
+ },
1894
+ ];
1895
+ class ImmutableERC721Base__factory {
1896
+ static abi = _abi;
1897
+ static createInterface() {
1898
+ return new utils.Interface(_abi);
1899
+ }
1900
+ static connect(address, signerOrProvider) {
1901
+ return new Contract(address, _abi, signerOrProvider);
1902
+ }
1903
+ }
1904
+
1905
+ class ERC721Factory {
1906
+ erc721;
1907
+ constructor(contractAddress, provider) {
1908
+ this.erc721 = ImmutableERC721Base__factory.connect(contractAddress, provider);
1909
+ }
1910
+ create() {
1911
+ return new ERC721(this.erc721);
1912
+ }
1913
+ }
1914
+
1915
+ /**
1916
+ * zkEVM orderbook SDK
1917
+ * @constructor
1918
+ * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
1919
+ */
1920
+ class Orderbook {
1921
+ config;
1922
+ apiClient;
1923
+ seaport;
1924
+ constructor(config) {
1925
+ this.config = config;
1926
+ // TODO: Move endpoint lookup to a map based on env. Just using override to get dev started
1927
+ const apiEndpoint = config.overrides?.apiEndpoint;
1928
+ if (!apiEndpoint) {
1929
+ throw new Error('API endpoint must be provided as an override');
1930
+ }
1931
+ // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
1932
+ const chainName = config.overrides?.chainName;
1933
+ if (!chainName) {
1934
+ throw new Error('chainName must be provided as an override');
1935
+ }
1936
+ this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.config.seaportContractAddress).create();
1937
+ this.seaport = new SeaportFactory(this.config.seaportContractAddress, this.config.zoneContractAddress, this.config.provider).create();
1938
+ }
1939
+ /**
1940
+ * Get an order by ID
1941
+ * @param {string} listingId - The listingId to find.
1942
+ * @return {ListingResult} The returned order result.
1943
+ */
1944
+ getListing(listingId) {
1945
+ return this.apiClient.getListing(listingId);
1946
+ }
1947
+ /**
1948
+ * List orders. This method is used to get a list of orders filtered by conditions specified
1949
+ * in the params object.
1950
+ * @param {ListOrderParams} listOrderParams - Filtering, ordering and page parameters.
1951
+ * @return {Orders} The paged orders.
1952
+ */
1953
+ listListings(listOrderParams) {
1954
+ return this.apiClient.listListings(listOrderParams);
1955
+ }
1956
+ /**
1957
+ * Get required transactions and messages for signing prior to creating a listing
1958
+ * through the createListing method
1959
+ * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
1960
+ * @return {PrepareListingResponse} PrepareListingResponse includes
1961
+ * the unsigned approval transaction, the typed order message for signing and
1962
+ * the order components that can be submitted to `createListing` with a signature.
1963
+ */
1964
+ async prepareListing({ offerer, listingItem, considerationItem, orderExpiry, }) {
1965
+ const erc721 = new ERC721Factory(listingItem.contractAddress, this.config.provider).create();
1966
+ const royaltyInfo = await erc721.royaltyInfo(listingItem.tokenId, considerationItem.amount);
1967
+ return this.seaport.prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo,
1968
+ // Default order start to now
1969
+ new Date(),
1970
+ // Default order expiry to 2 years from now
1971
+ orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
1972
+ }
1973
+ /**
1974
+ * Create an order
1975
+ * @param {CreateListingParams} createListingParams - create an order with the given params.
1976
+ * @return {ListingResult} The result of the order created in the Immutable services.
1977
+ */
1978
+ createListing(createListingParams) {
1979
+ return this.apiClient.createListing(createListingParams);
1980
+ }
1981
+ /**
1982
+ * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
1983
+ * transaction exists it must be signed and submitted to the chain before the fulfilment
1984
+ * transaction can be submitted or it will be reverted.
1985
+ * @param {string} listingId - The listingId to fulfil.
1986
+ * @param {string} fulfillerAddress - The address of the account fulfilling the order.
1987
+ * @return {FulfillOrderResponse} Approval and fulfilment transactions.
1988
+ */
1989
+ async fulfillOrder(listingId, fulfillerAddress) {
1990
+ const orderResult = await this.apiClient.getListing(listingId);
1991
+ if (orderResult.result.status !== OrderStatus.ACTIVE) {
1992
+ throw new Error(`Cannot fulfil order that is not active. Current status: ${orderResult.result.status}`);
1993
+ }
1994
+ return this.seaport.fulfilOrder(orderResult.result, fulfillerAddress);
1995
+ }
1996
+ /**
1997
+ * Get an unsigned cancel order transaction. Orders can only be cancelled by
1998
+ * the account that created them.
1999
+ * @param {string} listingId - The listingId to cancel.
2000
+ * @param {string} accountAddress - The address of the account cancelling the order.
2001
+ * @return {CancelOrderResponse} The unsigned cancel order transaction
2002
+ */
2003
+ async cancelOrder(listingId, accountAddress) {
2004
+ const orderResult = await this.apiClient.getListing(listingId);
2005
+ if (orderResult.result.status !== OrderStatus.ACTIVE
2006
+ && orderResult.result.status !== OrderStatus.INACTIVE
2007
+ && orderResult.result.status !== OrderStatus.PENDING) {
2008
+ throw new Error(`Cannot cancel order with status ${orderResult.result.status}`);
2009
+ }
2010
+ if (orderResult.result.account_address !== accountAddress.toLowerCase()) {
2011
+ throw new Error(`Only account ${orderResult.result.account_address} can cancel order ${listingId}`);
2012
+ }
2013
+ const cancelOrderTransaction = await this.seaport.cancelOrder(orderResult.result, accountAddress);
2014
+ return { unsignedCancelOrderTransaction: cancelOrderTransaction };
2015
+ }
2016
+ }
2017
+
2018
+ const module = 'orderbook';
2019
+
2020
+ export { Orderbook, module };