@imtbl/sdk 0.9.0 → 0.12.0-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,1134 @@
1
+ import axios from 'axios';
2
+ import FormData from 'form-data';
3
+ import { providers, BigNumber, constants as constants$1 } from 'ethers';
4
+ import { Seaport as Seaport$1 } from '@opensea/seaport-js';
5
+
6
+ var Environment;
7
+ (function (Environment) {
8
+ Environment["PRODUCTION"] = "production";
9
+ Environment["SANDBOX"] = "sandbox";
10
+ })(Environment || (Environment = {}));
11
+
12
+ class BaseHttpRequest {
13
+ config;
14
+ constructor(config) {
15
+ this.config = config;
16
+ }
17
+ }
18
+
19
+ class ApiError extends Error {
20
+ url;
21
+ status;
22
+ statusText;
23
+ body;
24
+ request;
25
+ constructor(request, response, message) {
26
+ super(message);
27
+ this.name = 'ApiError';
28
+ this.url = response.url;
29
+ this.status = response.status;
30
+ this.statusText = response.statusText;
31
+ this.body = response.body;
32
+ this.request = request;
33
+ }
34
+ }
35
+
36
+ /* istanbul ignore file */
37
+ /* tslint:disable */
38
+ /* eslint-disable */
39
+ class CancelError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = 'CancelError';
43
+ }
44
+ get isCancelled() {
45
+ return true;
46
+ }
47
+ }
48
+ class CancelablePromise {
49
+ [Symbol.toStringTag];
50
+ _isResolved;
51
+ _isRejected;
52
+ _isCancelled;
53
+ _cancelHandlers;
54
+ _promise;
55
+ _resolve;
56
+ _reject;
57
+ constructor(executor) {
58
+ this._isResolved = false;
59
+ this._isRejected = false;
60
+ this._isCancelled = false;
61
+ this._cancelHandlers = [];
62
+ this._promise = new Promise((resolve, reject) => {
63
+ this._resolve = resolve;
64
+ this._reject = reject;
65
+ const onResolve = (value) => {
66
+ if (this._isResolved || this._isRejected || this._isCancelled) {
67
+ return;
68
+ }
69
+ this._isResolved = true;
70
+ this._resolve?.(value);
71
+ };
72
+ const onReject = (reason) => {
73
+ if (this._isResolved || this._isRejected || this._isCancelled) {
74
+ return;
75
+ }
76
+ this._isRejected = true;
77
+ this._reject?.(reason);
78
+ };
79
+ const onCancel = (cancelHandler) => {
80
+ if (this._isResolved || this._isRejected || this._isCancelled) {
81
+ return;
82
+ }
83
+ this._cancelHandlers.push(cancelHandler);
84
+ };
85
+ Object.defineProperty(onCancel, 'isResolved', {
86
+ get: () => this._isResolved,
87
+ });
88
+ Object.defineProperty(onCancel, 'isRejected', {
89
+ get: () => this._isRejected,
90
+ });
91
+ Object.defineProperty(onCancel, 'isCancelled', {
92
+ get: () => this._isCancelled,
93
+ });
94
+ return executor(onResolve, onReject, onCancel);
95
+ });
96
+ }
97
+ then(onFulfilled, onRejected) {
98
+ return this._promise.then(onFulfilled, onRejected);
99
+ }
100
+ catch(onRejected) {
101
+ return this._promise.catch(onRejected);
102
+ }
103
+ finally(onFinally) {
104
+ return this._promise.finally(onFinally);
105
+ }
106
+ cancel() {
107
+ if (this._isResolved || this._isRejected || this._isCancelled) {
108
+ return;
109
+ }
110
+ this._isCancelled = true;
111
+ if (this._cancelHandlers.length) {
112
+ try {
113
+ for (const cancelHandler of this._cancelHandlers) {
114
+ cancelHandler();
115
+ }
116
+ }
117
+ catch (error) {
118
+ console.warn('Cancellation threw an error', error);
119
+ return;
120
+ }
121
+ }
122
+ this._cancelHandlers.length = 0;
123
+ this._reject?.(new CancelError('Request aborted'));
124
+ }
125
+ get isCancelled() {
126
+ return this._isCancelled;
127
+ }
128
+ }
129
+
130
+ /* istanbul ignore file */
131
+ /* tslint:disable */
132
+ /* eslint-disable */
133
+ const isDefined = (value) => {
134
+ return value !== undefined && value !== null;
135
+ };
136
+ const isString = (value) => {
137
+ return typeof value === 'string';
138
+ };
139
+ const isStringWithValue = (value) => {
140
+ return isString(value) && value !== '';
141
+ };
142
+ const isBlob = (value) => {
143
+ return (typeof value === 'object' &&
144
+ typeof value.type === 'string' &&
145
+ typeof value.stream === 'function' &&
146
+ typeof value.arrayBuffer === 'function' &&
147
+ typeof value.constructor === 'function' &&
148
+ typeof value.constructor.name === 'string' &&
149
+ /^(Blob|File)$/.test(value.constructor.name) &&
150
+ /^(Blob|File)$/.test(value[Symbol.toStringTag]));
151
+ };
152
+ const isFormData = (value) => {
153
+ return value instanceof FormData;
154
+ };
155
+ const isSuccess = (status) => {
156
+ return status >= 200 && status < 300;
157
+ };
158
+ const base64 = (str) => {
159
+ try {
160
+ return btoa(str);
161
+ }
162
+ catch (err) {
163
+ // @ts-ignore
164
+ return Buffer.from(str).toString('base64');
165
+ }
166
+ };
167
+ const getQueryString = (params) => {
168
+ const qs = [];
169
+ const append = (key, value) => {
170
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
171
+ };
172
+ const process = (key, value) => {
173
+ if (isDefined(value)) {
174
+ if (Array.isArray(value)) {
175
+ value.forEach(v => {
176
+ process(key, v);
177
+ });
178
+ }
179
+ else if (typeof value === 'object') {
180
+ Object.entries(value).forEach(([k, v]) => {
181
+ process(`${key}[${k}]`, v);
182
+ });
183
+ }
184
+ else {
185
+ append(key, value);
186
+ }
187
+ }
188
+ };
189
+ Object.entries(params).forEach(([key, value]) => {
190
+ process(key, value);
191
+ });
192
+ if (qs.length > 0) {
193
+ return `?${qs.join('&')}`;
194
+ }
195
+ return '';
196
+ };
197
+ const getUrl = (config, options) => {
198
+ const encoder = config.ENCODE_PATH || encodeURI;
199
+ const path = options.url
200
+ .replace('{api-version}', config.VERSION)
201
+ .replace(/{(.*?)}/g, (substring, group) => {
202
+ if (options.path?.hasOwnProperty(group)) {
203
+ return encoder(String(options.path[group]));
204
+ }
205
+ return substring;
206
+ });
207
+ const url = `${config.BASE}${path}`;
208
+ if (options.query) {
209
+ return `${url}${getQueryString(options.query)}`;
210
+ }
211
+ return url;
212
+ };
213
+ const getFormData = (options) => {
214
+ if (options.formData) {
215
+ const formData = new FormData();
216
+ const process = (key, value) => {
217
+ if (isString(value) || isBlob(value)) {
218
+ formData.append(key, value);
219
+ }
220
+ else {
221
+ formData.append(key, JSON.stringify(value));
222
+ }
223
+ };
224
+ Object.entries(options.formData)
225
+ .filter(([_, value]) => isDefined(value))
226
+ .forEach(([key, value]) => {
227
+ if (Array.isArray(value)) {
228
+ value.forEach(v => process(key, v));
229
+ }
230
+ else {
231
+ process(key, value);
232
+ }
233
+ });
234
+ return formData;
235
+ }
236
+ return undefined;
237
+ };
238
+ const resolve = async (options, resolver) => {
239
+ if (typeof resolver === 'function') {
240
+ return resolver(options);
241
+ }
242
+ return resolver;
243
+ };
244
+ const getHeaders = async (config, options, formData) => {
245
+ const token = await resolve(options, config.TOKEN);
246
+ const username = await resolve(options, config.USERNAME);
247
+ const password = await resolve(options, config.PASSWORD);
248
+ const additionalHeaders = await resolve(options, config.HEADERS);
249
+ const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {};
250
+ const headers = Object.entries({
251
+ Accept: 'application/json',
252
+ ...additionalHeaders,
253
+ ...options.headers,
254
+ ...formHeaders,
255
+ })
256
+ .filter(([_, value]) => isDefined(value))
257
+ .reduce((headers, [key, value]) => ({
258
+ ...headers,
259
+ [key]: String(value),
260
+ }), {});
261
+ if (isStringWithValue(token)) {
262
+ headers['Authorization'] = `Bearer ${token}`;
263
+ }
264
+ if (isStringWithValue(username) && isStringWithValue(password)) {
265
+ const credentials = base64(`${username}:${password}`);
266
+ headers['Authorization'] = `Basic ${credentials}`;
267
+ }
268
+ if (options.body) {
269
+ if (options.mediaType) {
270
+ headers['Content-Type'] = options.mediaType;
271
+ }
272
+ else if (isBlob(options.body)) {
273
+ headers['Content-Type'] = options.body.type || 'application/octet-stream';
274
+ }
275
+ else if (isString(options.body)) {
276
+ headers['Content-Type'] = 'text/plain';
277
+ }
278
+ else if (!isFormData(options.body)) {
279
+ headers['Content-Type'] = 'application/json';
280
+ }
281
+ }
282
+ return headers;
283
+ };
284
+ const getRequestBody = (options) => {
285
+ if (options.body) {
286
+ return options.body;
287
+ }
288
+ return undefined;
289
+ };
290
+ const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
291
+ const source = axios.CancelToken.source();
292
+ const requestConfig = {
293
+ url,
294
+ headers,
295
+ data: body ?? formData,
296
+ method: options.method,
297
+ withCredentials: config.WITH_CREDENTIALS,
298
+ cancelToken: source.token,
299
+ };
300
+ onCancel(() => source.cancel('The user aborted a request.'));
301
+ try {
302
+ return await axios.request(requestConfig);
303
+ }
304
+ catch (error) {
305
+ const axiosError = error;
306
+ if (axiosError.response) {
307
+ return axiosError.response;
308
+ }
309
+ throw error;
310
+ }
311
+ };
312
+ const getResponseHeader = (response, responseHeader) => {
313
+ if (responseHeader) {
314
+ const content = response.headers[responseHeader];
315
+ if (isString(content)) {
316
+ return content;
317
+ }
318
+ }
319
+ return undefined;
320
+ };
321
+ const getResponseBody = (response) => {
322
+ if (response.status !== 204) {
323
+ return response.data;
324
+ }
325
+ return undefined;
326
+ };
327
+ const catchErrorCodes = (options, result) => {
328
+ const errors = {
329
+ 400: 'Bad Request',
330
+ 401: 'Unauthorized',
331
+ 403: 'Forbidden',
332
+ 404: 'Not Found',
333
+ 500: 'Internal Server Error',
334
+ 502: 'Bad Gateway',
335
+ 503: 'Service Unavailable',
336
+ ...options.errors,
337
+ };
338
+ const error = errors[result.status];
339
+ if (error) {
340
+ throw new ApiError(options, result, error);
341
+ }
342
+ if (!result.ok) {
343
+ throw new ApiError(options, result, 'Generic Error');
344
+ }
345
+ };
346
+ /**
347
+ * Request method
348
+ * @param config The OpenAPI configuration object
349
+ * @param options The request options from the service
350
+ * @returns CancelablePromise<T>
351
+ * @throws ApiError
352
+ */
353
+ const request = (config, options) => {
354
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
355
+ try {
356
+ const url = getUrl(config, options);
357
+ const formData = getFormData(options);
358
+ const body = getRequestBody(options);
359
+ const headers = await getHeaders(config, options, formData);
360
+ if (!onCancel.isCancelled) {
361
+ const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
362
+ const responseBody = getResponseBody(response);
363
+ const responseHeader = getResponseHeader(response, options.responseHeader);
364
+ const result = {
365
+ url,
366
+ ok: isSuccess(response.status),
367
+ status: response.status,
368
+ statusText: response.statusText,
369
+ body: responseHeader ?? responseBody,
370
+ };
371
+ catchErrorCodes(options, result);
372
+ resolve(result.body);
373
+ }
374
+ }
375
+ catch (error) {
376
+ reject(error);
377
+ }
378
+ });
379
+ };
380
+
381
+ class AxiosHttpRequest extends BaseHttpRequest {
382
+ constructor(config) {
383
+ super(config);
384
+ }
385
+ /**
386
+ * Request method
387
+ * @param options The request options from the service
388
+ * @returns CancelablePromise<T>
389
+ * @throws ApiError
390
+ */
391
+ request(options) {
392
+ return request(this.config, options);
393
+ }
394
+ }
395
+
396
+ class OrdersService {
397
+ httpRequest;
398
+ constructor(httpRequest) {
399
+ this.httpRequest = httpRequest;
400
+ }
401
+ /**
402
+ * List all listings
403
+ * List all listings
404
+ * @returns ListListingsResult OK response.
405
+ * @throws ApiError
406
+ */
407
+ listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, pageSize, sortBy, sortDirection, pageCursor, }) {
408
+ return this.httpRequest.request({
409
+ method: 'GET',
410
+ url: '/v1/chains/{chain_name}/orders/listings',
411
+ path: {
412
+ 'chain_name': chainName,
413
+ },
414
+ query: {
415
+ 'status': status,
416
+ 'sell_item_contract_address': sellItemContractAddress,
417
+ 'buy_item_contract_address': buyItemContractAddress,
418
+ 'sell_item_token_id': sellItemTokenId,
419
+ 'page_size': pageSize,
420
+ 'sort_by': sortBy,
421
+ 'sort_direction': sortDirection,
422
+ 'page_cursor': pageCursor,
423
+ },
424
+ errors: {
425
+ 400: `Bad Request (400)`,
426
+ 404: `The specified resource was not found (404)`,
427
+ 500: `Internal Server Error (500)`,
428
+ },
429
+ });
430
+ }
431
+ /**
432
+ * Create a listing
433
+ * Create a listing
434
+ * @returns ListingResult Created response.
435
+ * @throws ApiError
436
+ */
437
+ createListing({ chainName, requestBody, }) {
438
+ return this.httpRequest.request({
439
+ method: 'POST',
440
+ url: '/v1/chains/{chain_name}/orders/listings',
441
+ path: {
442
+ 'chain_name': chainName,
443
+ },
444
+ body: requestBody,
445
+ mediaType: 'application/json',
446
+ errors: {
447
+ 400: `Bad Request (400)`,
448
+ 404: `The specified resource was not found (404)`,
449
+ 500: `Internal Server Error (500)`,
450
+ },
451
+ });
452
+ }
453
+ /**
454
+ * Get a single listing by ID
455
+ * Get a single listing by ID
456
+ * @returns ListingResult OK response.
457
+ * @throws ApiError
458
+ */
459
+ getListing({ chainName, listingId, }) {
460
+ return this.httpRequest.request({
461
+ method: 'GET',
462
+ url: '/v1/chains/{chain_name}/orders/listings/{listing_id}',
463
+ path: {
464
+ 'chain_name': chainName,
465
+ 'listing_id': listingId,
466
+ },
467
+ errors: {
468
+ 400: `Bad Request (400)`,
469
+ 404: `The specified resource was not found (404)`,
470
+ 500: `Internal Server Error (500)`,
471
+ },
472
+ });
473
+ }
474
+ /**
475
+ * Retrieve fulfillment data for orders
476
+ * Retrieve signed fulfillment data based on the list of order IDs and corresponding fees.
477
+ * @returns any Successful response
478
+ * @throws ApiError
479
+ */
480
+ fulfillmentData({ chainName, requestBody, }) {
481
+ return this.httpRequest.request({
482
+ method: 'POST',
483
+ url: '/v1/chains/{chain_name}/orders/fulfillment-data',
484
+ path: {
485
+ 'chain_name': chainName,
486
+ },
487
+ body: requestBody,
488
+ mediaType: 'application/json',
489
+ errors: {
490
+ 400: `Bad Request (400)`,
491
+ 404: `The specified resource was not found (404)`,
492
+ 500: `Internal Server Error (500)`,
493
+ },
494
+ });
495
+ }
496
+ }
497
+
498
+ class OrderBookClient {
499
+ orders;
500
+ request;
501
+ constructor(config, HttpRequest = AxiosHttpRequest) {
502
+ this.request = new HttpRequest({
503
+ BASE: config?.BASE ?? 'https://api.sandbox.immutable.com',
504
+ VERSION: config?.VERSION ?? '1.0.0',
505
+ WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
506
+ CREDENTIALS: config?.CREDENTIALS ?? 'include',
507
+ TOKEN: config?.TOKEN,
508
+ USERNAME: config?.USERNAME,
509
+ PASSWORD: config?.PASSWORD,
510
+ HEADERS: config?.HEADERS,
511
+ ENCODE_PATH: config?.ENCODE_PATH,
512
+ });
513
+ this.orders = new OrdersService(this.request);
514
+ }
515
+ }
516
+
517
+ /* istanbul ignore file */
518
+ /* tslint:disable */
519
+ /* eslint-disable */
520
+ var CreateOrderProtocolData;
521
+ (function (CreateOrderProtocolData) {
522
+ (function (order_type) {
523
+ order_type["FULL_RESTRICTED"] = "FULL_RESTRICTED";
524
+ })(CreateOrderProtocolData.order_type || (CreateOrderProtocolData.order_type = {}));
525
+ })(CreateOrderProtocolData || (CreateOrderProtocolData = {}));
526
+
527
+ /* istanbul ignore file */
528
+ /* tslint:disable */
529
+ /* eslint-disable */
530
+ var Fee;
531
+ (function (Fee) {
532
+ (function (fee_type) {
533
+ fee_type["ROYALTY"] = "ROYALTY";
534
+ fee_type["MAKER_MARKETPLACE"] = "MAKER_MARKETPLACE";
535
+ fee_type["TAKER_MARKETPLACE"] = "TAKER_MARKETPLACE";
536
+ fee_type["PROTOCOL"] = "PROTOCOL";
537
+ })(Fee.fee_type || (Fee.fee_type = {}));
538
+ })(Fee || (Fee = {}));
539
+
540
+ /* istanbul ignore file */
541
+ /* tslint:disable */
542
+ /* eslint-disable */
543
+ /**
544
+ * The Order status
545
+ */
546
+ var OrderStatus;
547
+ (function (OrderStatus) {
548
+ OrderStatus["PENDING"] = "PENDING";
549
+ OrderStatus["ACTIVE"] = "ACTIVE";
550
+ OrderStatus["INACTIVE"] = "INACTIVE";
551
+ OrderStatus["FILLED"] = "FILLED";
552
+ OrderStatus["CANCELLED"] = "CANCELLED";
553
+ OrderStatus["EXPIRED"] = "EXPIRED";
554
+ })(OrderStatus || (OrderStatus = {}));
555
+
556
+ var TransactionPurpose;
557
+ (function (TransactionPurpose) {
558
+ TransactionPurpose["APPROVAL"] = "APPROVAL";
559
+ TransactionPurpose["FULFILL_ORDER"] = "FULFILL_ORDER";
560
+ })(TransactionPurpose || (TransactionPurpose = {}));
561
+ var SignablePurpose;
562
+ (function (SignablePurpose) {
563
+ SignablePurpose["CREATE_LISTING"] = "CREATE_LISTING";
564
+ })(SignablePurpose || (SignablePurpose = {}));
565
+ var ActionType;
566
+ (function (ActionType) {
567
+ ActionType["TRANSACTION"] = "TRANSACTION";
568
+ ActionType["SIGNABLE"] = "SIGNABLE";
569
+ })(ActionType || (ActionType = {}));
570
+
571
+ /* eslint-disable */
572
+ // TODO: Resolve these from seaport-js.
573
+ // There is some bundling issue that is preventing this from working
574
+ const SEAPORT_CONTRACT_NAME = 'ImmutableSeaport';
575
+ // export const SEAPORT_CONTRACT_VERSION_V1_4 = '1.4';
576
+ const SEAPORT_CONTRACT_VERSION_V1_5 = '1.5';
577
+ const EIP_712_ORDER_TYPE = {
578
+ OrderComponents: [
579
+ { name: 'offerer', type: 'address' },
580
+ { name: 'zone', type: 'address' },
581
+ { name: 'offer', type: 'OfferItem[]' },
582
+ { name: 'consideration', type: 'ConsiderationItem[]' },
583
+ { name: 'orderType', type: 'uint8' },
584
+ { name: 'startTime', type: 'uint256' },
585
+ { name: 'endTime', type: 'uint256' },
586
+ { name: 'zoneHash', type: 'bytes32' },
587
+ { name: 'salt', type: 'uint256' },
588
+ { name: 'conduitKey', type: 'bytes32' },
589
+ { name: 'counter', type: 'uint256' },
590
+ ],
591
+ OfferItem: [
592
+ { name: 'itemType', type: 'uint8' },
593
+ { name: 'token', type: 'address' },
594
+ { name: 'identifierOrCriteria', type: 'uint256' },
595
+ { name: 'startAmount', type: 'uint256' },
596
+ { name: 'endAmount', type: 'uint256' },
597
+ ],
598
+ ConsiderationItem: [
599
+ { name: 'itemType', type: 'uint8' },
600
+ { name: 'token', type: 'address' },
601
+ { name: 'identifierOrCriteria', type: 'uint256' },
602
+ { name: 'startAmount', type: 'uint256' },
603
+ { name: 'endAmount', type: 'uint256' },
604
+ { name: 'recipient', type: 'address' },
605
+ ],
606
+ };
607
+ var OrderType;
608
+ (function (OrderType) {
609
+ OrderType[OrderType["FULL_OPEN"] = 0] = "FULL_OPEN";
610
+ OrderType[OrderType["PARTIAL_OPEN"] = 1] = "PARTIAL_OPEN";
611
+ OrderType[OrderType["FULL_RESTRICTED"] = 2] = "FULL_RESTRICTED";
612
+ OrderType[OrderType["PARTIAL_RESTRICTED"] = 3] = "PARTIAL_RESTRICTED";
613
+ })(OrderType || (OrderType = {}));
614
+ var ItemType;
615
+ (function (ItemType) {
616
+ ItemType[ItemType["NATIVE"] = 0] = "NATIVE";
617
+ ItemType[ItemType["ERC20"] = 1] = "ERC20";
618
+ ItemType[ItemType["ERC721"] = 2] = "ERC721";
619
+ ItemType[ItemType["ERC1155"] = 3] = "ERC1155";
620
+ ItemType[ItemType["ERC721_WITH_CRITERIA"] = 4] = "ERC721_WITH_CRITERIA";
621
+ ItemType[ItemType["ERC1155_WITH_CRITERIA"] = 5] = "ERC1155_WITH_CRITERIA";
622
+ })(ItemType || (ItemType = {}));
623
+ var Side;
624
+ (function (Side) {
625
+ Side[Side["OFFER"] = 0] = "OFFER";
626
+ Side[Side["CONSIDERATION"] = 1] = "CONSIDERATION";
627
+ })(Side || (Side = {}));
628
+ var BasicOrderRouteType;
629
+ (function (BasicOrderRouteType) {
630
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC721"] = 0] = "ETH_TO_ERC721";
631
+ BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC1155"] = 1] = "ETH_TO_ERC1155";
632
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC721"] = 2] = "ERC20_TO_ERC721";
633
+ BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC1155"] = 3] = "ERC20_TO_ERC1155";
634
+ BasicOrderRouteType[BasicOrderRouteType["ERC721_TO_ERC20"] = 4] = "ERC721_TO_ERC20";
635
+ BasicOrderRouteType[BasicOrderRouteType["ERC1155_TO_ERC20"] = 5] = "ERC1155_TO_ERC20";
636
+ })(BasicOrderRouteType || (BasicOrderRouteType = {}));
637
+
638
+ function getOrderComponentsFromMessage(orderMessage) {
639
+ const data = JSON.parse(orderMessage);
640
+ const orderComponents = data.message;
641
+ orderComponents.salt = BigNumber.from(orderComponents.salt).toHexString();
642
+ return orderComponents;
643
+ }
644
+
645
+ // Add 20% more gas than estimate to prevent out of gas errors
646
+ // This can always be overwritten by the user signing the transaction
647
+ function prepareTransaction(transactionMethods) {
648
+ return async () => {
649
+ const transaction = await transactionMethods.buildTransaction();
650
+ transaction.gasLimit = await transactionMethods.estimateGas();
651
+ transaction.gasLimit = transaction.gasLimit
652
+ .add(transaction.gasLimit.div(5));
653
+ return transaction;
654
+ };
655
+ }
656
+
657
+ function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
658
+ const considerationItems = order.buy.map((buyItem) => {
659
+ switch (buyItem.item_type) {
660
+ case 'NATIVE':
661
+ return {
662
+ startAmount: buyItem.start_amount,
663
+ endAmount: buyItem.start_amount,
664
+ itemType: ItemType.NATIVE,
665
+ recipient: order.account_address,
666
+ token: constants$1.AddressZero,
667
+ identifierOrCriteria: '0',
668
+ };
669
+ case 'ERC20':
670
+ return {
671
+ startAmount: buyItem.start_amount,
672
+ endAmount: buyItem.start_amount,
673
+ itemType: ItemType.ERC20,
674
+ recipient: order.account_address,
675
+ token: buyItem.contract_address || constants$1.AddressZero,
676
+ identifierOrCriteria: '0',
677
+ };
678
+ default: // ERC721
679
+ return {
680
+ startAmount: '1',
681
+ endAmount: '1',
682
+ itemType: ItemType.ERC721,
683
+ recipient: order.account_address,
684
+ token: buyItem.contract_address || constants$1.AddressZero,
685
+ identifierOrCriteria: '0',
686
+ };
687
+ }
688
+ });
689
+ const fees = order.fees.map((fee) => ({
690
+ amount: fee.amount,
691
+ itemType: order.buy[0].item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
692
+ recipient: fee.recipient,
693
+ token: order.buy[0].item_type === 'ERC20'
694
+ ? order.buy[0].contract_address
695
+ : constants$1.AddressZero,
696
+ identifierOrCriteria: '0',
697
+ }));
698
+ return {
699
+ orderComponents: {
700
+ conduitKey: constants$1.HashZero,
701
+ consideration: [...considerationItems],
702
+ offer: order.sell.map((sellItem) => {
703
+ const erc721Item = sellItem;
704
+ return {
705
+ startAmount: '1',
706
+ endAmount: '1',
707
+ itemType: ItemType.ERC721,
708
+ token: erc721Item.contract_address,
709
+ identifierOrCriteria: erc721Item.token_id,
710
+ };
711
+ }),
712
+ counter,
713
+ endTime: Math.round(new Date(order.end_time).getTime() / 1000).toString(),
714
+ startTime: Math.round(new Date(order.start_time).getTime() / 1000).toString(),
715
+ salt: order.salt,
716
+ offerer: order.account_address,
717
+ zone: zoneAddress,
718
+ // this should be the fee exclusive number of items the user signed for
719
+ totalOriginalConsiderationItems: considerationItems.length,
720
+ orderType: OrderType.FULL_RESTRICTED,
721
+ zoneHash: constants$1.HashZero,
722
+ },
723
+ tips: fees,
724
+ };
725
+ }
726
+
727
+ class Seaport {
728
+ seaportLibFactory;
729
+ provider;
730
+ seaportContractAddress;
731
+ zoneContractAddress;
732
+ constructor(seaportLibFactory, provider, seaportContractAddress, zoneContractAddress) {
733
+ this.seaportLibFactory = seaportLibFactory;
734
+ this.provider = provider;
735
+ this.seaportContractAddress = seaportContractAddress;
736
+ this.zoneContractAddress = zoneContractAddress;
737
+ }
738
+ async prepareSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry) {
739
+ const { actions: seaportActions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry);
740
+ const listingActions = [];
741
+ const approvalAction = seaportActions.find((action) => action.type === 'approval');
742
+ if (approvalAction) {
743
+ listingActions.push({
744
+ type: ActionType.TRANSACTION,
745
+ purpose: TransactionPurpose.APPROVAL,
746
+ buildTransaction: prepareTransaction(approvalAction.transactionMethods),
747
+ });
748
+ }
749
+ const createAction = seaportActions.find((action) => action.type === 'create');
750
+ if (!createAction) {
751
+ throw new Error('No create order action found');
752
+ }
753
+ const orderMessageToSign = await createAction.getMessageToSign();
754
+ const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
755
+ listingActions.push({
756
+ type: ActionType.SIGNABLE,
757
+ purpose: SignablePurpose.CREATE_LISTING,
758
+ message: await this.getTypedDataFromOrderComponents(orderComponents),
759
+ });
760
+ return {
761
+ actions: listingActions,
762
+ orderComponents,
763
+ orderHash: this.getSeaportLib().getOrderHash(orderComponents),
764
+ };
765
+ }
766
+ async fulfillOrder(order, account, extraData) {
767
+ const { orderComponents, tips } = this.mapImmutableOrderToSeaportOrderComponents(order);
768
+ const seaportLib = this.getSeaportLib(order);
769
+ const { actions: seaportActions } = await seaportLib.fulfillOrders({
770
+ accountAddress: account,
771
+ fulfillOrderDetails: [
772
+ {
773
+ order: {
774
+ parameters: orderComponents,
775
+ signature: order.signature,
776
+ },
777
+ extraData,
778
+ tips,
779
+ },
780
+ ],
781
+ });
782
+ const fulfillmentActions = [];
783
+ const approvalAction = seaportActions.find((action) => action.type === 'approval');
784
+ if (approvalAction) {
785
+ fulfillmentActions.push({
786
+ type: ActionType.TRANSACTION,
787
+ buildTransaction: prepareTransaction(approvalAction.transactionMethods),
788
+ purpose: TransactionPurpose.APPROVAL,
789
+ });
790
+ }
791
+ const fulfilOrderAction = seaportActions.find((action) => action.type === 'exchange');
792
+ if (!fulfilOrderAction) {
793
+ throw new Error('No exchange action found');
794
+ }
795
+ fulfillmentActions.push({
796
+ type: ActionType.TRANSACTION,
797
+ buildTransaction: prepareTransaction(fulfilOrderAction.transactionMethods),
798
+ purpose: TransactionPurpose.FULFILL_ORDER,
799
+ });
800
+ return { actions: fulfillmentActions };
801
+ }
802
+ async cancelOrder(order, account) {
803
+ const { orderComponents } = this.mapImmutableOrderToSeaportOrderComponents(order);
804
+ const seaportLib = this.getSeaportLib(order);
805
+ const cancellationTransaction = await seaportLib.cancelOrders([orderComponents], account);
806
+ return prepareTransaction(cancellationTransaction)();
807
+ }
808
+ mapImmutableOrderToSeaportOrderComponents(order) {
809
+ const orderCounter = order.protocol_data.counter;
810
+ return mapImmutableOrderToSeaportOrderComponents(order, orderCounter, this.zoneContractAddress);
811
+ }
812
+ createSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry) {
813
+ const seaportLib = this.getSeaportLib();
814
+ return seaportLib.createOrder({
815
+ allowPartialFills: false,
816
+ offer: [
817
+ {
818
+ itemType: ItemType.ERC721,
819
+ token: listingItem.contractAddress,
820
+ identifier: listingItem.tokenId,
821
+ },
822
+ ],
823
+ consideration: [
824
+ {
825
+ token: considerationItem.type === 'ERC20'
826
+ ? considerationItem.contractAddress
827
+ : undefined,
828
+ amount: considerationItem.amount,
829
+ recipient: offerer,
830
+ },
831
+ ],
832
+ startTime: (orderStart.getTime() / 1000).toFixed(0),
833
+ endTime: (orderExpiry.getTime() / 1000).toFixed(0),
834
+ zone: this.zoneContractAddress,
835
+ restrictedByZone: true,
836
+ }, offerer);
837
+ }
838
+ async getTypedDataFromOrderComponents(orderComponents) {
839
+ const { chainId } = await this.provider.getNetwork();
840
+ const domainData = {
841
+ name: SEAPORT_CONTRACT_NAME,
842
+ version: SEAPORT_CONTRACT_VERSION_V1_5,
843
+ chainId,
844
+ verifyingContract: this.seaportContractAddress,
845
+ };
846
+ return {
847
+ domain: domainData,
848
+ types: EIP_712_ORDER_TYPE,
849
+ value: orderComponents,
850
+ };
851
+ }
852
+ getSeaportLib(order) {
853
+ const seaportAddress = order?.protocol_data?.seaport_address ?? this.seaportContractAddress;
854
+ const seaportVersion = SEAPORT_CONTRACT_VERSION_V1_5;
855
+ // if (order?.protocol_data?.seaport_version === SEAPORT_CONTRACT_VERSION_V1_5) {
856
+ // seaportVersion = SEAPORT_CONTRACT_VERSION_V1_5;
857
+ // }
858
+ return this.seaportLibFactory.create(seaportVersion, seaportAddress);
859
+ }
860
+ }
861
+
862
+ class ImmutableApiClient {
863
+ orderbookService;
864
+ chainName;
865
+ seaportAddress;
866
+ constructor(orderbookService, chainName, seaportAddress) {
867
+ this.orderbookService = orderbookService;
868
+ this.chainName = chainName;
869
+ this.seaportAddress = seaportAddress;
870
+ }
871
+ async fulfillmentData(requests) {
872
+ return this.orderbookService.fulfillmentData({
873
+ chainName: this.chainName,
874
+ requestBody: requests,
875
+ });
876
+ }
877
+ async getListing(listingId) {
878
+ return this.orderbookService.getListing({
879
+ chainName: this.chainName,
880
+ listingId,
881
+ });
882
+ }
883
+ async listListings(listOrderParams) {
884
+ return this.orderbookService.listListings({
885
+ chainName: this.chainName,
886
+ ...listOrderParams,
887
+ });
888
+ }
889
+ async createListing({ orderHash, orderComponents, orderSignature, makerFee, }) {
890
+ if (orderComponents.offer.length !== 1) {
891
+ throw new Error('Only one item can be listed at a time');
892
+ }
893
+ if (Number(orderComponents.offer[0].itemType) !== ItemType.ERC721) {
894
+ throw new Error('Only ERC721 tokens can be listed');
895
+ }
896
+ const orderTypes = [
897
+ ...orderComponents.consideration.map((c) => c.itemType),
898
+ ];
899
+ const isSameConsiderationType = new Set(orderTypes).size === 1;
900
+ if (!isSameConsiderationType) {
901
+ throw new Error('All consideration items must be of the same type');
902
+ }
903
+ return this.orderbookService.createListing({
904
+ chainName: this.chainName,
905
+ requestBody: {
906
+ order_hash: orderHash,
907
+ account_address: orderComponents.offerer,
908
+ buy: [
909
+ {
910
+ item_type: Number(orderComponents.consideration[0].itemType)
911
+ === ItemType.NATIVE
912
+ ? 'NATIVE'
913
+ : 'ERC20',
914
+ start_amount: orderComponents.consideration[0].startAmount,
915
+ contract_address: orderComponents.consideration[0].token,
916
+ },
917
+ ],
918
+ fees: makerFee ? [makerFee] : [],
919
+ end_time: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
920
+ protocol_data: {
921
+ order_type: CreateOrderProtocolData.order_type.FULL_RESTRICTED,
922
+ zone_address: orderComponents.zone,
923
+ seaport_address: this.seaportAddress,
924
+ seaport_version: SEAPORT_CONTRACT_VERSION_V1_5,
925
+ counter: orderComponents.counter.toString(),
926
+ },
927
+ salt: orderComponents.salt,
928
+ sell: [
929
+ {
930
+ contract_address: orderComponents.offer[0].token,
931
+ token_id: orderComponents.offer[0].identifierOrCriteria,
932
+ item_type: 'ERC721',
933
+ },
934
+ ],
935
+ signature: orderSignature,
936
+ start_time: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
937
+ },
938
+ });
939
+ }
940
+ }
941
+
942
+ class ImmutableApiClientFactory {
943
+ chainName;
944
+ seaportAddress;
945
+ orderbookClient;
946
+ constructor(apiEndpoint, chainName, seaportAddress) {
947
+ this.chainName = chainName;
948
+ this.seaportAddress = seaportAddress;
949
+ this.orderbookClient = new OrderBookClient({
950
+ // eslint-disable-next-line @typescript-eslint/naming-convention
951
+ BASE: apiEndpoint,
952
+ });
953
+ }
954
+ create() {
955
+ return new ImmutableApiClient(this.orderbookClient.orders, this.chainName, this.seaportAddress);
956
+ }
957
+ }
958
+
959
+ const TESTNET_CHAIN_NAME = 'imtbl-zkevm-testnet';
960
+ const MAINNET_CHAIN_NAME = 'imtbl-zkevm-mainnet';
961
+ function getOrderbookConfig(environment) {
962
+ switch (environment) {
963
+ case Environment.SANDBOX:
964
+ return {
965
+ seaportContractAddress: '0x7Fb7Da6De152597830eD16361633e362A2F59410',
966
+ zoneContractAddress: '0x63441cBfBd15Dd8f5E92598E535661Ac5aCB808E',
967
+ apiEndpoint: 'https://api.sandbox.immutable.com',
968
+ chainName: TESTNET_CHAIN_NAME,
969
+ provider: new providers.JsonRpcProvider('https://rpc.testnet.immutable.com'),
970
+ };
971
+ // not yet deployed
972
+ case Environment.PRODUCTION:
973
+ return {
974
+ seaportContractAddress: '',
975
+ zoneContractAddress: '',
976
+ apiEndpoint: 'https://api.immutable.com',
977
+ chainName: MAINNET_CHAIN_NAME,
978
+ provider: new providers.JsonRpcProvider('https://rpc.immutable.com'),
979
+ };
980
+ default:
981
+ return null;
982
+ }
983
+ }
984
+
985
+ class SeaportLibFactory {
986
+ defaultSeaportContractAddress;
987
+ provider;
988
+ constructor(defaultSeaportContractAddress, provider) {
989
+ this.defaultSeaportContractAddress = defaultSeaportContractAddress;
990
+ this.provider = provider;
991
+ }
992
+ create(orderSeaportVersion, orderSeaportAddress) {
993
+ const seaportVersion = orderSeaportVersion ?? SEAPORT_CONTRACT_VERSION_V1_5;
994
+ const seaportContractAddress = orderSeaportAddress ?? this.defaultSeaportContractAddress;
995
+ return new Seaport$1(this.provider, {
996
+ seaportVersion,
997
+ balanceAndApprovalChecksOnOrderCreation: true,
998
+ overrides: {
999
+ contractAddress: seaportContractAddress,
1000
+ },
1001
+ });
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * zkEVM orderbook SDK
1007
+ * @constructor
1008
+ * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
1009
+ */
1010
+ class Orderbook {
1011
+ apiClient;
1012
+ seaport;
1013
+ orderbookConfig;
1014
+ constructor(config) {
1015
+ const obConfig = getOrderbookConfig(config.baseConfig.environment);
1016
+ const finalConfig = {
1017
+ ...obConfig,
1018
+ ...config.overrides,
1019
+ };
1020
+ if (!finalConfig) {
1021
+ throw new Error('Orderbook configuration not passed, please specify the environment under config.baseConfig.environment');
1022
+ }
1023
+ this.orderbookConfig = finalConfig;
1024
+ const { apiEndpoint, chainName } = this.orderbookConfig;
1025
+ if (!apiEndpoint) {
1026
+ throw new Error('API endpoint must be provided');
1027
+ }
1028
+ this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.orderbookConfig.seaportContractAddress).create();
1029
+ const seaportLibFactory = new SeaportLibFactory(this.orderbookConfig.seaportContractAddress, this.orderbookConfig.provider);
1030
+ this.seaport = new Seaport(seaportLibFactory, this.orderbookConfig.provider, this.orderbookConfig.seaportContractAddress, this.orderbookConfig.zoneContractAddress);
1031
+ }
1032
+ /**
1033
+ * Return the configuration for the orderbook module.
1034
+ * @return {OrderbookModuleConfiguration} The configuration for the orderbook module.
1035
+ */
1036
+ config() {
1037
+ return this.orderbookConfig;
1038
+ }
1039
+ /**
1040
+ * Get an order by ID
1041
+ * @param {string} listingId - The listingId to find.
1042
+ * @return {ListingResult} The returned order result.
1043
+ */
1044
+ getListing(listingId) {
1045
+ return this.apiClient.getListing(listingId);
1046
+ }
1047
+ /**
1048
+ * List orders. This method is used to get a list of orders filtered by conditions specified
1049
+ * in the params object.
1050
+ * @param {ListListingsParams} listOrderParams - Filtering, ordering and page parameters.
1051
+ * @return {ListListingsResult} The paged orders.
1052
+ */
1053
+ listListings(listOrderParams) {
1054
+ return this.apiClient.listListings(listOrderParams);
1055
+ }
1056
+ /**
1057
+ * Get required transactions and messages for signing prior to creating a listing
1058
+ * through the createListing method
1059
+ * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
1060
+ * @return {PrepareListingResponse} PrepareListingResponse includes
1061
+ * the unsigned approval transaction, the typed order message for signing and
1062
+ * the order components that can be submitted to `createListing` with a signature.
1063
+ */
1064
+ async prepareListing({ makerAddress, sell, buy, orderExpiry, }) {
1065
+ return this.seaport.prepareSeaportOrder(makerAddress, sell, buy,
1066
+ // Default order start to now
1067
+ new Date(),
1068
+ // Default order expiry to 2 years from now
1069
+ orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
1070
+ }
1071
+ /**
1072
+ * Create an order
1073
+ * @param {CreateListingParams} createListingParams - create an order with the given params.
1074
+ * @return {ListingResult} The result of the order created in the Immutable services.
1075
+ */
1076
+ createListing(createListingParams) {
1077
+ return this.apiClient.createListing(createListingParams);
1078
+ }
1079
+ /**
1080
+ * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
1081
+ * transaction exists it must be signed and submitted to the chain before the fulfilment
1082
+ * transaction can be submitted or it will be reverted.
1083
+ * @param {string} listingId - The listingId to fulfil.
1084
+ * @param {string} fulfillerAddress - The address of the account fulfilling the order.
1085
+ * @return {FulfillOrderResponse} Approval and fulfilment transactions.
1086
+ */
1087
+ async fulfillOrder(listingId, takerAddress, takerFee) {
1088
+ const fulfillmentDataRes = await this.apiClient.fulfillmentData([
1089
+ {
1090
+ order_id: listingId,
1091
+ fee: takerFee,
1092
+ },
1093
+ ]);
1094
+ if (fulfillmentDataRes.result.length !== 1) {
1095
+ throw new Error('unexpected fulfillment data result length');
1096
+ }
1097
+ const extraData = fulfillmentDataRes.result[0].extra_data;
1098
+ const orderResult = fulfillmentDataRes.result[0].order;
1099
+ if (orderResult.status !== OrderStatus.ACTIVE) {
1100
+ throw new Error(`Cannot fulfil order that is not active. Current status: ${orderResult.status}`);
1101
+ }
1102
+ return this.seaport.fulfillOrder(orderResult, takerAddress, extraData);
1103
+ }
1104
+ /**
1105
+ * Get an unsigned cancel order transaction. Orders can only be cancelled by
1106
+ * the account that created them.
1107
+ * @param {string} listingId - The listingId to cancel.
1108
+ * @param {string} accountAddress - The address of the account cancelling the order.
1109
+ * @return {CancelOrderResponse} The unsigned cancel order transaction
1110
+ */
1111
+ async cancelOrder(listingId, accountAddress) {
1112
+ const orderResult = await this.apiClient.getListing(listingId);
1113
+ if (orderResult.result.status !== OrderStatus.ACTIVE
1114
+ && orderResult.result.status !== OrderStatus.INACTIVE
1115
+ && orderResult.result.status !== OrderStatus.PENDING) {
1116
+ throw new Error(`Cannot cancel order with status ${orderResult.result.status}`);
1117
+ }
1118
+ if (orderResult.result.account_address !== accountAddress.toLowerCase()) {
1119
+ throw new Error(`Only account ${orderResult.result.account_address} can cancel order ${listingId}`);
1120
+ }
1121
+ const cancelOrderTransaction = await this.seaport.cancelOrder(orderResult.result, accountAddress);
1122
+ return { unsignedCancelOrderTransaction: cancelOrderTransaction };
1123
+ }
1124
+ }
1125
+
1126
+ // Consumers might want an estimated gas limit for fulfilling an order
1127
+ // without calling the transaction builder. This is an estimate that
1128
+ // should work for all fulfillment scenarios.
1129
+ const ESTIMATED_FULFILLMENT_GAS_GWEI = 400000;
1130
+ const constants = {
1131
+ estimatedFulfillmentGasGwei: ESTIMATED_FULFILLMENT_GAS_GWEI,
1132
+ };
1133
+
1134
+ export { ActionType, Orderbook, SignablePurpose, TransactionPurpose, constants };