@imtbl/sdk 0.1.7 → 0.1.8-alpha

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