@imtbl/sdk 0.28.5-alpha.2 → 0.28.5-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -14,8 +14,6 @@ var providers = require('@ethersproject/providers');
14
14
  var events = require('events');
15
15
  var abi = require('@0xsequence/abi');
16
16
  var config$1 = require('@0xsequence/config');
17
- var FormData$2 = require('form-data');
18
- var seaportJs = require('@opensea/seaport-js');
19
17
  var units = require('@ethersproject/units');
20
18
  var bignumber = require('@ethersproject/bignumber');
21
19
  var detectEthereumProvider = require('@metamask/detect-provider');
@@ -3333,7 +3331,7 @@ const NativeItemItemTypeEnum = {
3333
3331
  * @export
3334
3332
  * @enum {string}
3335
3333
  */
3336
- const OrderStatusName$1 = {
3334
+ const OrderStatusName = {
3337
3335
  Pending: 'PENDING',
3338
3336
  Active: 'ACTIVE',
3339
3337
  Inactive: 'INACTIVE',
@@ -3474,7 +3472,7 @@ var index = /*#__PURE__*/Object.freeze({
3474
3472
  NftsApiAxiosParamCreator: NftsApiAxiosParamCreator,
3475
3473
  NftsApiFactory: NftsApiFactory,
3476
3474
  NftsApiFp: NftsApiFp,
3477
- OrderStatusName: OrderStatusName$1,
3475
+ OrderStatusName: OrderStatusName,
3478
3476
  OrdersApi: OrdersApi,
3479
3477
  OrdersApiAxiosParamCreator: OrdersApiAxiosParamCreator,
3480
3478
  OrdersApiFactory: OrdersApiFactory,
@@ -3643,7 +3641,7 @@ class MultiRollupApiClients {
3643
3641
  }
3644
3642
 
3645
3643
  // eslint-disable-next-line @typescript-eslint/naming-convention
3646
- const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.28.5-alpha.2' };
3644
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.28.5-alpha.3' };
3647
3645
  const createConfig = ({ basePath, headers, }) => {
3648
3646
  if (!basePath.trim()) {
3649
3647
  throw Error('basePath can not be empty');
@@ -3703,7 +3701,7 @@ class APIError extends Error {
3703
3701
 
3704
3702
  /* eslint-disable implicit-arrow-linebreak */
3705
3703
  const defaultHeaders = {
3706
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.28.5-alpha.2',
3704
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.28.5-alpha.3',
3707
3705
  };
3708
3706
  /**
3709
3707
  * createAPIConfiguration to create a custom Configuration
@@ -4114,7 +4112,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
4114
4112
  chainID,
4115
4113
  coreContractAddress,
4116
4114
  registrationContractAddress,
4117
- sdkVersion: 'ts-immutable-sdk-0.28.5-alpha.2',
4115
+ sdkVersion: 'ts-immutable-sdk-0.28.5-alpha.3',
4118
4116
  });
4119
4117
  /**
4120
4118
  * Sets `sdkVersion` at the time of build
@@ -4712,7 +4710,7 @@ function isArrayBufferView(val) {
4712
4710
  *
4713
4711
  * @returns {boolean} True if value is a String, otherwise false
4714
4712
  */
4715
- const isString$1 = typeOfTest('string');
4713
+ const isString = typeOfTest('string');
4716
4714
 
4717
4715
  /**
4718
4716
  * Determine if a value is a Function
@@ -4789,7 +4787,7 @@ const isFile = kindOfTest('File');
4789
4787
  *
4790
4788
  * @returns {boolean} True if value is a Blob, otherwise false
4791
4789
  */
4792
- const isBlob$1 = kindOfTest('Blob');
4790
+ const isBlob = kindOfTest('Blob');
4793
4791
 
4794
4792
  /**
4795
4793
  * Determine if a value is a FileList
@@ -4816,7 +4814,7 @@ const isStream = (val) => isObject(val) && isFunction(val.pipe);
4816
4814
  *
4817
4815
  * @returns {boolean} True if value is an FormData, otherwise false
4818
4816
  */
4819
- const isFormData$1 = (thing) => {
4817
+ const isFormData = (thing) => {
4820
4818
  let kind;
4821
4819
  return thing && (
4822
4820
  (typeof FormData === 'function' && thing instanceof FormData) || (
@@ -5300,9 +5298,9 @@ var utils = {
5300
5298
  isArray,
5301
5299
  isArrayBuffer,
5302
5300
  isBuffer,
5303
- isFormData: isFormData$1,
5301
+ isFormData,
5304
5302
  isArrayBufferView,
5305
- isString: isString$1,
5303
+ isString,
5306
5304
  isNumber,
5307
5305
  isBoolean,
5308
5306
  isObject,
@@ -5310,7 +5308,7 @@ var utils = {
5310
5308
  isUndefined,
5311
5309
  isDate,
5312
5310
  isFile,
5313
- isBlob: isBlob$1,
5311
+ isBlob,
5314
5312
  isRegExp,
5315
5313
  isFunction,
5316
5314
  isStream,
@@ -10930,1585 +10928,6 @@ var passport = /*#__PURE__*/Object.freeze({
10930
10928
  get RpcErrorCode () { return RpcErrorCode; }
10931
10929
  });
10932
10930
 
10933
- class BaseHttpRequest {
10934
- config;
10935
- constructor(config) {
10936
- this.config = config;
10937
- }
10938
- }
10939
-
10940
- class ApiError extends Error {
10941
- url;
10942
- status;
10943
- statusText;
10944
- body;
10945
- request;
10946
- constructor(request, response, message) {
10947
- super(message);
10948
- this.name = 'ApiError';
10949
- this.url = response.url;
10950
- this.status = response.status;
10951
- this.statusText = response.statusText;
10952
- this.body = response.body;
10953
- this.request = request;
10954
- }
10955
- }
10956
-
10957
- /* istanbul ignore file */
10958
- /* tslint:disable */
10959
- /* eslint-disable */
10960
- class CancelError extends Error {
10961
- constructor(message) {
10962
- super(message);
10963
- this.name = 'CancelError';
10964
- }
10965
- get isCancelled() {
10966
- return true;
10967
- }
10968
- }
10969
- class CancelablePromise {
10970
- [Symbol.toStringTag];
10971
- _isResolved;
10972
- _isRejected;
10973
- _isCancelled;
10974
- _cancelHandlers;
10975
- _promise;
10976
- _resolve;
10977
- _reject;
10978
- constructor(executor) {
10979
- this._isResolved = false;
10980
- this._isRejected = false;
10981
- this._isCancelled = false;
10982
- this._cancelHandlers = [];
10983
- this._promise = new Promise((resolve, reject) => {
10984
- this._resolve = resolve;
10985
- this._reject = reject;
10986
- const onResolve = (value) => {
10987
- if (this._isResolved || this._isRejected || this._isCancelled) {
10988
- return;
10989
- }
10990
- this._isResolved = true;
10991
- this._resolve?.(value);
10992
- };
10993
- const onReject = (reason) => {
10994
- if (this._isResolved || this._isRejected || this._isCancelled) {
10995
- return;
10996
- }
10997
- this._isRejected = true;
10998
- this._reject?.(reason);
10999
- };
11000
- const onCancel = (cancelHandler) => {
11001
- if (this._isResolved || this._isRejected || this._isCancelled) {
11002
- return;
11003
- }
11004
- this._cancelHandlers.push(cancelHandler);
11005
- };
11006
- Object.defineProperty(onCancel, 'isResolved', {
11007
- get: () => this._isResolved,
11008
- });
11009
- Object.defineProperty(onCancel, 'isRejected', {
11010
- get: () => this._isRejected,
11011
- });
11012
- Object.defineProperty(onCancel, 'isCancelled', {
11013
- get: () => this._isCancelled,
11014
- });
11015
- return executor(onResolve, onReject, onCancel);
11016
- });
11017
- }
11018
- then(onFulfilled, onRejected) {
11019
- return this._promise.then(onFulfilled, onRejected);
11020
- }
11021
- catch(onRejected) {
11022
- return this._promise.catch(onRejected);
11023
- }
11024
- finally(onFinally) {
11025
- return this._promise.finally(onFinally);
11026
- }
11027
- cancel() {
11028
- if (this._isResolved || this._isRejected || this._isCancelled) {
11029
- return;
11030
- }
11031
- this._isCancelled = true;
11032
- if (this._cancelHandlers.length) {
11033
- try {
11034
- for (const cancelHandler of this._cancelHandlers) {
11035
- cancelHandler();
11036
- }
11037
- }
11038
- catch (error) {
11039
- console.warn('Cancellation threw an error', error);
11040
- return;
11041
- }
11042
- }
11043
- this._cancelHandlers.length = 0;
11044
- this._reject?.(new CancelError('Request aborted'));
11045
- }
11046
- get isCancelled() {
11047
- return this._isCancelled;
11048
- }
11049
- }
11050
-
11051
- /* istanbul ignore file */
11052
- /* tslint:disable */
11053
- /* eslint-disable */
11054
- const isDefined = (value) => {
11055
- return value !== undefined && value !== null;
11056
- };
11057
- const isString = (value) => {
11058
- return typeof value === 'string';
11059
- };
11060
- const isStringWithValue = (value) => {
11061
- return isString(value) && value !== '';
11062
- };
11063
- const isBlob = (value) => {
11064
- return (typeof value === 'object' &&
11065
- typeof value.type === 'string' &&
11066
- typeof value.stream === 'function' &&
11067
- typeof value.arrayBuffer === 'function' &&
11068
- typeof value.constructor === 'function' &&
11069
- typeof value.constructor.name === 'string' &&
11070
- /^(Blob|File)$/.test(value.constructor.name) &&
11071
- /^(Blob|File)$/.test(value[Symbol.toStringTag]));
11072
- };
11073
- const isFormData = (value) => {
11074
- return value instanceof FormData$2;
11075
- };
11076
- const isSuccess = (status) => {
11077
- return status >= 200 && status < 300;
11078
- };
11079
- const base64 = (str) => {
11080
- try {
11081
- return btoa(str);
11082
- }
11083
- catch (err) {
11084
- // @ts-ignore
11085
- return Buffer.from(str).toString('base64');
11086
- }
11087
- };
11088
- const getQueryString = (params) => {
11089
- const qs = [];
11090
- const append = (key, value) => {
11091
- qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
11092
- };
11093
- const process = (key, value) => {
11094
- if (isDefined(value)) {
11095
- if (Array.isArray(value)) {
11096
- value.forEach(v => {
11097
- process(key, v);
11098
- });
11099
- }
11100
- else if (typeof value === 'object') {
11101
- Object.entries(value).forEach(([k, v]) => {
11102
- process(`${key}[${k}]`, v);
11103
- });
11104
- }
11105
- else {
11106
- append(key, value);
11107
- }
11108
- }
11109
- };
11110
- Object.entries(params).forEach(([key, value]) => {
11111
- process(key, value);
11112
- });
11113
- if (qs.length > 0) {
11114
- return `?${qs.join('&')}`;
11115
- }
11116
- return '';
11117
- };
11118
- const getUrl = (config, options) => {
11119
- const encoder = config.ENCODE_PATH || encodeURI;
11120
- const path = options.url
11121
- .replace('{api-version}', config.VERSION)
11122
- .replace(/{(.*?)}/g, (substring, group) => {
11123
- if (options.path?.hasOwnProperty(group)) {
11124
- return encoder(String(options.path[group]));
11125
- }
11126
- return substring;
11127
- });
11128
- const url = `${config.BASE}${path}`;
11129
- if (options.query) {
11130
- return `${url}${getQueryString(options.query)}`;
11131
- }
11132
- return url;
11133
- };
11134
- const getFormData = (options) => {
11135
- if (options.formData) {
11136
- const formData = new FormData$2();
11137
- const process = (key, value) => {
11138
- if (isString(value) || isBlob(value)) {
11139
- formData.append(key, value);
11140
- }
11141
- else {
11142
- formData.append(key, JSON.stringify(value));
11143
- }
11144
- };
11145
- Object.entries(options.formData)
11146
- .filter(([_, value]) => isDefined(value))
11147
- .forEach(([key, value]) => {
11148
- if (Array.isArray(value)) {
11149
- value.forEach(v => process(key, v));
11150
- }
11151
- else {
11152
- process(key, value);
11153
- }
11154
- });
11155
- return formData;
11156
- }
11157
- return undefined;
11158
- };
11159
- const resolve = async (options, resolver) => {
11160
- if (typeof resolver === 'function') {
11161
- return resolver(options);
11162
- }
11163
- return resolver;
11164
- };
11165
- const getHeaders = async (config, options, formData) => {
11166
- const token = await resolve(options, config.TOKEN);
11167
- const username = await resolve(options, config.USERNAME);
11168
- const password = await resolve(options, config.PASSWORD);
11169
- const additionalHeaders = await resolve(options, config.HEADERS);
11170
- const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {};
11171
- const headers = Object.entries({
11172
- Accept: 'application/json',
11173
- ...additionalHeaders,
11174
- ...options.headers,
11175
- ...formHeaders,
11176
- })
11177
- .filter(([_, value]) => isDefined(value))
11178
- .reduce((headers, [key, value]) => ({
11179
- ...headers,
11180
- [key]: String(value),
11181
- }), {});
11182
- if (isStringWithValue(token)) {
11183
- headers['Authorization'] = `Bearer ${token}`;
11184
- }
11185
- if (isStringWithValue(username) && isStringWithValue(password)) {
11186
- const credentials = base64(`${username}:${password}`);
11187
- headers['Authorization'] = `Basic ${credentials}`;
11188
- }
11189
- if (options.body) {
11190
- if (options.mediaType) {
11191
- headers['Content-Type'] = options.mediaType;
11192
- }
11193
- else if (isBlob(options.body)) {
11194
- headers['Content-Type'] = options.body.type || 'application/octet-stream';
11195
- }
11196
- else if (isString(options.body)) {
11197
- headers['Content-Type'] = 'text/plain';
11198
- }
11199
- else if (!isFormData(options.body)) {
11200
- headers['Content-Type'] = 'application/json';
11201
- }
11202
- }
11203
- return headers;
11204
- };
11205
- const getRequestBody = (options) => {
11206
- if (options.body) {
11207
- return options.body;
11208
- }
11209
- return undefined;
11210
- };
11211
- const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
11212
- const source = globalAxios$1.CancelToken.source();
11213
- const requestConfig = {
11214
- url,
11215
- headers,
11216
- data: body ?? formData,
11217
- method: options.method,
11218
- withCredentials: config.WITH_CREDENTIALS,
11219
- cancelToken: source.token,
11220
- };
11221
- onCancel(() => source.cancel('The user aborted a request.'));
11222
- try {
11223
- return await globalAxios$1.request(requestConfig);
11224
- }
11225
- catch (error) {
11226
- const axiosError = error;
11227
- if (axiosError.response) {
11228
- return axiosError.response;
11229
- }
11230
- throw error;
11231
- }
11232
- };
11233
- const getResponseHeader = (response, responseHeader) => {
11234
- if (responseHeader) {
11235
- const content = response.headers[responseHeader];
11236
- if (isString(content)) {
11237
- return content;
11238
- }
11239
- }
11240
- return undefined;
11241
- };
11242
- const getResponseBody = (response) => {
11243
- if (response.status !== 204) {
11244
- return response.data;
11245
- }
11246
- return undefined;
11247
- };
11248
- const catchErrorCodes = (options, result) => {
11249
- const errors = {
11250
- 400: 'Bad Request',
11251
- 401: 'Unauthorized',
11252
- 403: 'Forbidden',
11253
- 404: 'Not Found',
11254
- 500: 'Internal Server Error',
11255
- 502: 'Bad Gateway',
11256
- 503: 'Service Unavailable',
11257
- ...options.errors,
11258
- };
11259
- const error = errors[result.status];
11260
- if (error) {
11261
- throw new ApiError(options, result, error);
11262
- }
11263
- if (!result.ok) {
11264
- throw new ApiError(options, result, 'Generic Error');
11265
- }
11266
- };
11267
- /**
11268
- * Request method
11269
- * @param config The OpenAPI configuration object
11270
- * @param options The request options from the service
11271
- * @returns CancelablePromise<T>
11272
- * @throws ApiError
11273
- */
11274
- const request = (config, options) => {
11275
- return new CancelablePromise(async (resolve, reject, onCancel) => {
11276
- try {
11277
- const url = getUrl(config, options);
11278
- const formData = getFormData(options);
11279
- const body = getRequestBody(options);
11280
- const headers = await getHeaders(config, options, formData);
11281
- if (!onCancel.isCancelled) {
11282
- const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
11283
- const responseBody = getResponseBody(response);
11284
- const responseHeader = getResponseHeader(response, options.responseHeader);
11285
- const result = {
11286
- url,
11287
- ok: isSuccess(response.status),
11288
- status: response.status,
11289
- statusText: response.statusText,
11290
- body: responseHeader ?? responseBody,
11291
- };
11292
- catchErrorCodes(options, result);
11293
- resolve(result.body);
11294
- }
11295
- }
11296
- catch (error) {
11297
- reject(error);
11298
- }
11299
- });
11300
- };
11301
-
11302
- class AxiosHttpRequest extends BaseHttpRequest {
11303
- constructor(config) {
11304
- super(config);
11305
- }
11306
- /**
11307
- * Request method
11308
- * @param options The request options from the service
11309
- * @returns CancelablePromise<T>
11310
- * @throws ApiError
11311
- */
11312
- request(options) {
11313
- return request(this.config, options);
11314
- }
11315
- }
11316
-
11317
- class OrdersService {
11318
- httpRequest;
11319
- constructor(httpRequest) {
11320
- this.httpRequest = httpRequest;
11321
- }
11322
- /**
11323
- * Cancel one or more orders
11324
- * Cancel one or more orders
11325
- * @returns CancelOrdersResult Orders cancellation response.
11326
- * @throws ApiError
11327
- */
11328
- cancelOrders({ chainName, requestBody, }) {
11329
- return this.httpRequest.request({
11330
- method: 'POST',
11331
- url: '/v1/chains/{chain_name}/orders/cancel',
11332
- path: {
11333
- 'chain_name': chainName,
11334
- },
11335
- body: requestBody,
11336
- mediaType: 'application/json',
11337
- errors: {
11338
- 400: `Bad Request (400)`,
11339
- 401: `Unauthorised Request (401)`,
11340
- 404: `The specified resource was not found (404)`,
11341
- 429: `Too Many Requests (429)`,
11342
- 500: `Internal Server Error (500)`,
11343
- 501: `Not Implemented Error (501)`,
11344
- },
11345
- });
11346
- }
11347
- /**
11348
- * List all listings
11349
- * List all listings
11350
- * @returns ListListingsResult OK response.
11351
- * @throws ApiError
11352
- */
11353
- listListings({ chainName, status, sellItemContractAddress, buyItemContractAddress, sellItemTokenId, fromUpdatedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11354
- return this.httpRequest.request({
11355
- method: 'GET',
11356
- url: '/v1/chains/{chain_name}/orders/listings',
11357
- path: {
11358
- 'chain_name': chainName,
11359
- },
11360
- query: {
11361
- 'status': status,
11362
- 'sell_item_contract_address': sellItemContractAddress,
11363
- 'buy_item_contract_address': buyItemContractAddress,
11364
- 'sell_item_token_id': sellItemTokenId,
11365
- 'from_updated_at': fromUpdatedAt,
11366
- 'page_size': pageSize,
11367
- 'sort_by': sortBy,
11368
- 'sort_direction': sortDirection,
11369
- 'page_cursor': pageCursor,
11370
- },
11371
- errors: {
11372
- 400: `Bad Request (400)`,
11373
- 404: `The specified resource was not found (404)`,
11374
- 500: `Internal Server Error (500)`,
11375
- },
11376
- });
11377
- }
11378
- /**
11379
- * Create a listing
11380
- * Create a listing
11381
- * @returns ListingResult Created response.
11382
- * @throws ApiError
11383
- */
11384
- createListing({ chainName, requestBody, }) {
11385
- return this.httpRequest.request({
11386
- method: 'POST',
11387
- url: '/v1/chains/{chain_name}/orders/listings',
11388
- path: {
11389
- 'chain_name': chainName,
11390
- },
11391
- body: requestBody,
11392
- mediaType: 'application/json',
11393
- errors: {
11394
- 400: `Bad Request (400)`,
11395
- 404: `The specified resource was not found (404)`,
11396
- 500: `Internal Server Error (500)`,
11397
- },
11398
- });
11399
- }
11400
- /**
11401
- * Get a single listing by ID
11402
- * Get a single listing by ID
11403
- * @returns ListingResult OK response.
11404
- * @throws ApiError
11405
- */
11406
- getListing({ chainName, listingId, }) {
11407
- return this.httpRequest.request({
11408
- method: 'GET',
11409
- url: '/v1/chains/{chain_name}/orders/listings/{listing_id}',
11410
- path: {
11411
- 'chain_name': chainName,
11412
- 'listing_id': listingId,
11413
- },
11414
- errors: {
11415
- 400: `Bad Request (400)`,
11416
- 404: `The specified resource was not found (404)`,
11417
- 500: `Internal Server Error (500)`,
11418
- },
11419
- });
11420
- }
11421
- /**
11422
- * Retrieve fulfillment data for orders
11423
- * Retrieve signed fulfillment data based on the list of order IDs and corresponding fees.
11424
- * @returns any Successful response
11425
- * @throws ApiError
11426
- */
11427
- fulfillmentData({ chainName, requestBody, }) {
11428
- return this.httpRequest.request({
11429
- method: 'POST',
11430
- url: '/v1/chains/{chain_name}/orders/fulfillment-data',
11431
- path: {
11432
- 'chain_name': chainName,
11433
- },
11434
- body: requestBody,
11435
- mediaType: 'application/json',
11436
- errors: {
11437
- 400: `Bad Request (400)`,
11438
- 404: `The specified resource was not found (404)`,
11439
- 500: `Internal Server Error (500)`,
11440
- },
11441
- });
11442
- }
11443
- /**
11444
- * List all trades
11445
- * List all trades
11446
- * @returns ListTradeResult OK response.
11447
- * @throws ApiError
11448
- */
11449
- listTrades({ chainName, accountAddress, fromIndexedAt, pageSize, sortBy, sortDirection, pageCursor, }) {
11450
- return this.httpRequest.request({
11451
- method: 'GET',
11452
- url: '/v1/chains/{chain_name}/trades',
11453
- path: {
11454
- 'chain_name': chainName,
11455
- },
11456
- query: {
11457
- 'account_address': accountAddress,
11458
- 'from_indexed_at': fromIndexedAt,
11459
- 'page_size': pageSize,
11460
- 'sort_by': sortBy,
11461
- 'sort_direction': sortDirection,
11462
- 'page_cursor': pageCursor,
11463
- },
11464
- errors: {
11465
- 400: `Bad Request (400)`,
11466
- 404: `The specified resource was not found (404)`,
11467
- 500: `Internal Server Error (500)`,
11468
- },
11469
- });
11470
- }
11471
- /**
11472
- * Get a single trade by ID
11473
- * Get a single trade by ID
11474
- * @returns TradeResult OK response.
11475
- * @throws ApiError
11476
- */
11477
- getTrade({ chainName, tradeId, }) {
11478
- return this.httpRequest.request({
11479
- method: 'GET',
11480
- url: '/v1/chains/{chain_name}/trades/{trade_id}',
11481
- path: {
11482
- 'chain_name': chainName,
11483
- 'trade_id': tradeId,
11484
- },
11485
- errors: {
11486
- 400: `Bad Request (400)`,
11487
- 404: `The specified resource was not found (404)`,
11488
- 500: `Internal Server Error (500)`,
11489
- },
11490
- });
11491
- }
11492
- }
11493
-
11494
- class OrderBookClient {
11495
- orders;
11496
- request;
11497
- constructor(config, HttpRequest = AxiosHttpRequest) {
11498
- this.request = new HttpRequest({
11499
- BASE: config?.BASE ?? 'https://api.sandbox.immutable.com',
11500
- VERSION: config?.VERSION ?? '1.0.0',
11501
- WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
11502
- CREDENTIALS: config?.CREDENTIALS ?? 'include',
11503
- TOKEN: config?.TOKEN,
11504
- USERNAME: config?.USERNAME,
11505
- PASSWORD: config?.PASSWORD,
11506
- HEADERS: config?.HEADERS,
11507
- ENCODE_PATH: config?.ENCODE_PATH,
11508
- });
11509
- this.orders = new OrdersService(this.request);
11510
- }
11511
- }
11512
-
11513
- /* istanbul ignore file */
11514
- /* tslint:disable */
11515
- /* eslint-disable */
11516
- var CancelledOrderStatus;
11517
- (function (CancelledOrderStatus) {
11518
- (function (cancellation_type) {
11519
- cancellation_type["ON_CHAIN"] = "ON_CHAIN";
11520
- cancellation_type["OFF_CHAIN"] = "OFF_CHAIN";
11521
- })(CancelledOrderStatus.cancellation_type || (CancelledOrderStatus.cancellation_type = {}));
11522
- })(CancelledOrderStatus || (CancelledOrderStatus = {}));
11523
-
11524
- /* istanbul ignore file */
11525
- /* tslint:disable */
11526
- /* eslint-disable */
11527
- var FailedOrderCancellation;
11528
- (function (FailedOrderCancellation) {
11529
- (function (reason_code) {
11530
- reason_code["FILLED"] = "FILLED";
11531
- })(FailedOrderCancellation.reason_code || (FailedOrderCancellation.reason_code = {}));
11532
- })(FailedOrderCancellation || (FailedOrderCancellation = {}));
11533
-
11534
- /* istanbul ignore file */
11535
- /* tslint:disable */
11536
- /* eslint-disable */
11537
- var Fee;
11538
- (function (Fee) {
11539
- (function (fee_type) {
11540
- fee_type["ROYALTY"] = "ROYALTY";
11541
- fee_type["MAKER_ECOSYSTEM"] = "MAKER_ECOSYSTEM";
11542
- fee_type["TAKER_ECOSYSTEM"] = "TAKER_ECOSYSTEM";
11543
- fee_type["PROTOCOL"] = "PROTOCOL";
11544
- })(Fee.fee_type || (Fee.fee_type = {}));
11545
- })(Fee || (Fee = {}));
11546
-
11547
- /* istanbul ignore file */
11548
- /* tslint:disable */
11549
- /* eslint-disable */
11550
- /**
11551
- * The Order status
11552
- */
11553
- var OrderStatusName;
11554
- (function (OrderStatusName) {
11555
- OrderStatusName["PENDING"] = "PENDING";
11556
- OrderStatusName["ACTIVE"] = "ACTIVE";
11557
- OrderStatusName["INACTIVE"] = "INACTIVE";
11558
- OrderStatusName["FILLED"] = "FILLED";
11559
- OrderStatusName["EXPIRED"] = "EXPIRED";
11560
- OrderStatusName["CANCELLED"] = "CANCELLED";
11561
- })(OrderStatusName || (OrderStatusName = {}));
11562
-
11563
- /* istanbul ignore file */
11564
- /* tslint:disable */
11565
- /* eslint-disable */
11566
- var ProtocolData;
11567
- (function (ProtocolData) {
11568
- (function (order_type) {
11569
- order_type["FULL_RESTRICTED"] = "FULL_RESTRICTED";
11570
- })(ProtocolData.order_type || (ProtocolData.order_type = {}));
11571
- })(ProtocolData || (ProtocolData = {}));
11572
-
11573
- var FeeType;
11574
- (function (FeeType) {
11575
- FeeType["MAKER_ECOSYSTEM"] = "MAKER_ECOSYSTEM";
11576
- FeeType["TAKER_ECOSYSTEM"] = "TAKER_ECOSYSTEM";
11577
- FeeType["PROTOCOL"] = "PROTOCOL";
11578
- FeeType["ROYALTY"] = "ROYALTY";
11579
- })(FeeType || (FeeType = {}));
11580
- var TransactionPurpose;
11581
- (function (TransactionPurpose) {
11582
- TransactionPurpose["APPROVAL"] = "APPROVAL";
11583
- TransactionPurpose["FULFILL_ORDER"] = "FULFILL_ORDER";
11584
- TransactionPurpose["CANCEL"] = "CANCEL";
11585
- })(TransactionPurpose || (TransactionPurpose = {}));
11586
- var SignablePurpose;
11587
- (function (SignablePurpose) {
11588
- SignablePurpose["CREATE_LISTING"] = "CREATE_LISTING";
11589
- SignablePurpose["OFF_CHAIN_CANCELLATION"] = "OFF_CHAIN_CANCELLATION";
11590
- })(SignablePurpose || (SignablePurpose = {}));
11591
- var ActionType;
11592
- (function (ActionType) {
11593
- ActionType["TRANSACTION"] = "TRANSACTION";
11594
- ActionType["SIGNABLE"] = "SIGNABLE";
11595
- })(ActionType || (ActionType = {}));
11596
-
11597
- function mapFromOpenApiOrder(order) {
11598
- const buyItems = order.buy.map((item) => {
11599
- if (item.item_type === 'ERC20') {
11600
- return {
11601
- type: 'ERC20',
11602
- contractAddress: item.contract_address,
11603
- amount: item.start_amount,
11604
- };
11605
- }
11606
- if (item.item_type === 'NATIVE') {
11607
- return {
11608
- type: 'NATIVE',
11609
- amount: item.start_amount,
11610
- };
11611
- }
11612
- throw new Error('Buy items must be either ERC20 or NATIVE');
11613
- });
11614
- const sellItems = order.sell.map((item) => {
11615
- if (item.item_type === 'ERC721') {
11616
- return {
11617
- type: 'ERC721',
11618
- contractAddress: item.contract_address,
11619
- tokenId: item.token_id,
11620
- };
11621
- }
11622
- throw new Error('Sell items must ERC721');
11623
- });
11624
- return {
11625
- id: order.id,
11626
- accountAddress: order.account_address,
11627
- buy: buyItems,
11628
- sell: sellItems,
11629
- fees: order.fees.map((fee) => ({
11630
- amount: fee.amount,
11631
- recipient: fee.recipient,
11632
- type: fee.fee_type,
11633
- })),
11634
- chain: order.chain,
11635
- createdAt: order.created_at,
11636
- endAt: order.end_at,
11637
- protocolData: {
11638
- counter: order.protocol_data.counter,
11639
- orderType: order.protocol_data.order_type,
11640
- seaportAddress: order.protocol_data.seaport_address,
11641
- seaportVersion: order.protocol_data.seaport_version,
11642
- zoneAddress: order.protocol_data.zone_address,
11643
- },
11644
- salt: order.salt,
11645
- signature: order.signature,
11646
- startAt: order.start_at,
11647
- status: order.status,
11648
- updatedAt: order.updated_at,
11649
- };
11650
- }
11651
- function mapFromOpenApiTrade(trade) {
11652
- const buyItems = trade.buy.map((item) => {
11653
- if (item.item_type === 'ERC20') {
11654
- return {
11655
- type: 'ERC20',
11656
- contractAddress: item.contract_address,
11657
- amount: item.start_amount,
11658
- };
11659
- }
11660
- if (item.item_type === 'NATIVE') {
11661
- return {
11662
- type: 'NATIVE',
11663
- amount: item.start_amount,
11664
- };
11665
- }
11666
- throw new Error('Buy items must be either ERC20 or NATIVE');
11667
- });
11668
- const sellItems = trade.sell.map((item) => {
11669
- if (item.item_type === 'ERC721') {
11670
- return {
11671
- type: 'ERC721',
11672
- contractAddress: item.contract_address,
11673
- tokenId: item.token_id,
11674
- };
11675
- }
11676
- throw new Error('Sell items must ERC721');
11677
- });
11678
- return {
11679
- id: trade.id,
11680
- orderId: trade.order_id,
11681
- buy: buyItems,
11682
- sell: sellItems,
11683
- buyerFees: trade.buyer_fees.map((fee) => ({
11684
- amount: fee.amount,
11685
- recipient: fee.recipient,
11686
- type: fee.fee_type,
11687
- })),
11688
- chain: trade.chain,
11689
- indexedAt: trade.indexed_at,
11690
- blockchainMetadata: {
11691
- blockNumber: trade.blockchain_metadata.block_number,
11692
- logIndex: trade.blockchain_metadata.log_index,
11693
- transactionHash: trade.blockchain_metadata.transaction_hash,
11694
- transactionIndex: trade.blockchain_metadata.transaction_index,
11695
- },
11696
- buyerAddress: trade.buyer_address,
11697
- makerAddress: trade.maker_address,
11698
- sellerAddress: trade.seller_address,
11699
- takerAddress: trade.taker_address,
11700
- };
11701
- }
11702
- function mapFromOpenApiPage(page) {
11703
- return {
11704
- nextCursor: page.next_cursor,
11705
- previousCursor: page.previous_cursor,
11706
- };
11707
- }
11708
-
11709
- /* eslint-disable */
11710
- // TODO: Resolve these from seaport-js.
11711
- // There is some bundling issue that is preventing this from working
11712
- const SEAPORT_CONTRACT_NAME = 'ImmutableSeaport';
11713
- // export const SEAPORT_CONTRACT_VERSION_V1_4 = '1.4';
11714
- const SEAPORT_CONTRACT_VERSION_V1_5 = '1.5';
11715
- const EIP_712_ORDER_TYPE = {
11716
- OrderComponents: [
11717
- { name: 'offerer', type: 'address' },
11718
- { name: 'zone', type: 'address' },
11719
- { name: 'offer', type: 'OfferItem[]' },
11720
- { name: 'consideration', type: 'ConsiderationItem[]' },
11721
- { name: 'orderType', type: 'uint8' },
11722
- { name: 'startTime', type: 'uint256' },
11723
- { name: 'endTime', type: 'uint256' },
11724
- { name: 'zoneHash', type: 'bytes32' },
11725
- { name: 'salt', type: 'uint256' },
11726
- { name: 'conduitKey', type: 'bytes32' },
11727
- { name: 'counter', type: 'uint256' },
11728
- ],
11729
- OfferItem: [
11730
- { name: 'itemType', type: 'uint8' },
11731
- { name: 'token', type: 'address' },
11732
- { name: 'identifierOrCriteria', type: 'uint256' },
11733
- { name: 'startAmount', type: 'uint256' },
11734
- { name: 'endAmount', type: 'uint256' },
11735
- ],
11736
- ConsiderationItem: [
11737
- { name: 'itemType', type: 'uint8' },
11738
- { name: 'token', type: 'address' },
11739
- { name: 'identifierOrCriteria', type: 'uint256' },
11740
- { name: 'startAmount', type: 'uint256' },
11741
- { name: 'endAmount', type: 'uint256' },
11742
- { name: 'recipient', type: 'address' },
11743
- ],
11744
- };
11745
- var OrderType;
11746
- (function (OrderType) {
11747
- OrderType[OrderType["FULL_OPEN"] = 0] = "FULL_OPEN";
11748
- OrderType[OrderType["PARTIAL_OPEN"] = 1] = "PARTIAL_OPEN";
11749
- OrderType[OrderType["FULL_RESTRICTED"] = 2] = "FULL_RESTRICTED";
11750
- OrderType[OrderType["PARTIAL_RESTRICTED"] = 3] = "PARTIAL_RESTRICTED";
11751
- })(OrderType || (OrderType = {}));
11752
- var ItemType;
11753
- (function (ItemType) {
11754
- ItemType[ItemType["NATIVE"] = 0] = "NATIVE";
11755
- ItemType[ItemType["ERC20"] = 1] = "ERC20";
11756
- ItemType[ItemType["ERC721"] = 2] = "ERC721";
11757
- ItemType[ItemType["ERC1155"] = 3] = "ERC1155";
11758
- ItemType[ItemType["ERC721_WITH_CRITERIA"] = 4] = "ERC721_WITH_CRITERIA";
11759
- ItemType[ItemType["ERC1155_WITH_CRITERIA"] = 5] = "ERC1155_WITH_CRITERIA";
11760
- })(ItemType || (ItemType = {}));
11761
- var Side;
11762
- (function (Side) {
11763
- Side[Side["OFFER"] = 0] = "OFFER";
11764
- Side[Side["CONSIDERATION"] = 1] = "CONSIDERATION";
11765
- })(Side || (Side = {}));
11766
- var BasicOrderRouteType;
11767
- (function (BasicOrderRouteType) {
11768
- BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC721"] = 0] = "ETH_TO_ERC721";
11769
- BasicOrderRouteType[BasicOrderRouteType["ETH_TO_ERC1155"] = 1] = "ETH_TO_ERC1155";
11770
- BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC721"] = 2] = "ERC20_TO_ERC721";
11771
- BasicOrderRouteType[BasicOrderRouteType["ERC20_TO_ERC1155"] = 3] = "ERC20_TO_ERC1155";
11772
- BasicOrderRouteType[BasicOrderRouteType["ERC721_TO_ERC20"] = 4] = "ERC721_TO_ERC20";
11773
- BasicOrderRouteType[BasicOrderRouteType["ERC1155_TO_ERC20"] = 5] = "ERC1155_TO_ERC20";
11774
- })(BasicOrderRouteType || (BasicOrderRouteType = {}));
11775
-
11776
- function getOrderComponentsFromMessage(orderMessage) {
11777
- const data = JSON.parse(orderMessage);
11778
- const orderComponents = data.message;
11779
- orderComponents.salt = ethers.BigNumber.from(orderComponents.salt).toHexString();
11780
- return orderComponents;
11781
- }
11782
-
11783
- // Add 20% more gas than estimate to prevent out of gas errors
11784
- // This can always be overwritten by the user signing the transaction
11785
- function prepareTransaction(transactionMethods) {
11786
- return async () => {
11787
- const transaction = await transactionMethods.buildTransaction();
11788
- transaction.gasLimit = await transactionMethods.estimateGas();
11789
- transaction.gasLimit = transaction.gasLimit
11790
- .add(transaction.gasLimit.div(5));
11791
- return transaction;
11792
- };
11793
- }
11794
-
11795
- function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
11796
- const considerationItems = order.buy.map((buyItem) => {
11797
- switch (buyItem.item_type) {
11798
- case 'NATIVE':
11799
- return {
11800
- startAmount: buyItem.start_amount,
11801
- endAmount: buyItem.start_amount,
11802
- itemType: ItemType.NATIVE,
11803
- recipient: order.account_address,
11804
- token: ethers.constants.AddressZero,
11805
- identifierOrCriteria: '0',
11806
- };
11807
- case 'ERC20':
11808
- return {
11809
- startAmount: buyItem.start_amount,
11810
- endAmount: buyItem.start_amount,
11811
- itemType: ItemType.ERC20,
11812
- recipient: order.account_address,
11813
- token: buyItem.contract_address || ethers.constants.AddressZero,
11814
- identifierOrCriteria: '0',
11815
- };
11816
- default: // ERC721
11817
- return {
11818
- startAmount: '1',
11819
- endAmount: '1',
11820
- itemType: ItemType.ERC721,
11821
- recipient: order.account_address,
11822
- token: buyItem.contract_address || ethers.constants.AddressZero,
11823
- identifierOrCriteria: '0',
11824
- };
11825
- }
11826
- });
11827
- const fees = order.fees.map((fee) => ({
11828
- amount: fee.amount,
11829
- itemType: order.buy[0].item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
11830
- recipient: fee.recipient,
11831
- token: order.buy[0].item_type === 'ERC20'
11832
- ? order.buy[0].contract_address
11833
- : ethers.constants.AddressZero,
11834
- identifierOrCriteria: '0',
11835
- }));
11836
- return {
11837
- orderComponents: {
11838
- conduitKey: ethers.constants.HashZero,
11839
- consideration: [...considerationItems],
11840
- offer: order.sell.map((sellItem) => {
11841
- const erc721Item = sellItem;
11842
- return {
11843
- startAmount: '1',
11844
- endAmount: '1',
11845
- itemType: ItemType.ERC721,
11846
- token: erc721Item.contract_address,
11847
- identifierOrCriteria: erc721Item.token_id,
11848
- };
11849
- }),
11850
- counter,
11851
- endTime: Math.round(new Date(order.end_at).getTime() / 1000).toString(),
11852
- startTime: Math.round(new Date(order.start_at).getTime() / 1000).toString(),
11853
- salt: order.salt,
11854
- offerer: order.account_address,
11855
- zone: zoneAddress,
11856
- // this should be the fee exclusive number of items the user signed for
11857
- totalOriginalConsiderationItems: considerationItems.length,
11858
- orderType: OrderType.FULL_RESTRICTED,
11859
- zoneHash: ethers.constants.HashZero,
11860
- },
11861
- tips: fees,
11862
- };
11863
- }
11864
-
11865
- class Seaport {
11866
- seaportLibFactory;
11867
- provider;
11868
- seaportContractAddress;
11869
- zoneContractAddress;
11870
- constructor(seaportLibFactory, provider, seaportContractAddress, zoneContractAddress) {
11871
- this.seaportLibFactory = seaportLibFactory;
11872
- this.provider = provider;
11873
- this.seaportContractAddress = seaportContractAddress;
11874
- this.zoneContractAddress = zoneContractAddress;
11875
- }
11876
- async prepareSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry) {
11877
- const { actions: seaportActions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry);
11878
- const listingActions = [];
11879
- const approvalAction = seaportActions.find((action) => action.type === 'approval');
11880
- if (approvalAction) {
11881
- listingActions.push({
11882
- type: ActionType.TRANSACTION,
11883
- purpose: TransactionPurpose.APPROVAL,
11884
- buildTransaction: prepareTransaction(approvalAction.transactionMethods),
11885
- });
11886
- }
11887
- const createAction = seaportActions.find((action) => action.type === 'create');
11888
- if (!createAction) {
11889
- throw new Error('No create order action found');
11890
- }
11891
- const orderMessageToSign = await createAction.getMessageToSign();
11892
- const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
11893
- listingActions.push({
11894
- type: ActionType.SIGNABLE,
11895
- purpose: SignablePurpose.CREATE_LISTING,
11896
- message: await this.getTypedDataFromOrderComponents(orderComponents),
11897
- });
11898
- return {
11899
- actions: listingActions,
11900
- orderComponents,
11901
- orderHash: this.getSeaportLib().getOrderHash(orderComponents),
11902
- };
11903
- }
11904
- async fulfillOrder(order, account, extraData) {
11905
- const { orderComponents, tips } = this.mapImmutableOrderToSeaportOrderComponents(order);
11906
- const seaportLib = this.getSeaportLib(order);
11907
- const { actions: seaportActions } = await seaportLib.fulfillOrders({
11908
- accountAddress: account,
11909
- fulfillOrderDetails: [
11910
- {
11911
- order: {
11912
- parameters: orderComponents,
11913
- signature: order.signature,
11914
- },
11915
- extraData,
11916
- tips,
11917
- },
11918
- ],
11919
- });
11920
- const fulfillmentActions = [];
11921
- const approvalAction = seaportActions.find((action) => action.type === 'approval');
11922
- if (approvalAction) {
11923
- fulfillmentActions.push({
11924
- type: ActionType.TRANSACTION,
11925
- buildTransaction: prepareTransaction(approvalAction.transactionMethods),
11926
- purpose: TransactionPurpose.APPROVAL,
11927
- });
11928
- }
11929
- const fulfilOrderAction = seaportActions.find((action) => action.type === 'exchange');
11930
- if (!fulfilOrderAction) {
11931
- throw new Error('No exchange action found');
11932
- }
11933
- fulfillmentActions.push({
11934
- type: ActionType.TRANSACTION,
11935
- buildTransaction: prepareTransaction(fulfilOrderAction.transactionMethods),
11936
- purpose: TransactionPurpose.FULFILL_ORDER,
11937
- });
11938
- return {
11939
- actions: fulfillmentActions,
11940
- expiration: Seaport.getExpirationISOTimeFromExtraData(extraData),
11941
- order: mapFromOpenApiOrder(order),
11942
- };
11943
- }
11944
- async fulfillBulkOrders(fulfillingOrders, account) {
11945
- const fulfillOrderDetails = fulfillingOrders.map((o) => {
11946
- const { orderComponents, tips } = this.mapImmutableOrderToSeaportOrderComponents(o.order);
11947
- return {
11948
- order: {
11949
- parameters: orderComponents,
11950
- signature: o.order.signature,
11951
- },
11952
- extraData: o.extra_data,
11953
- tips,
11954
- };
11955
- });
11956
- const { actions: seaportActions } = await this.getSeaportLib().fulfillOrders({
11957
- fulfillOrderDetails,
11958
- accountAddress: account,
11959
- });
11960
- const fulfillmentActions = [];
11961
- const approvalAction = seaportActions.find((action) => action.type === 'approval');
11962
- if (approvalAction) {
11963
- fulfillmentActions.push({
11964
- type: ActionType.TRANSACTION,
11965
- buildTransaction: prepareTransaction(approvalAction.transactionMethods),
11966
- purpose: TransactionPurpose.APPROVAL,
11967
- });
11968
- }
11969
- const fulfilOrderAction = seaportActions.find((action) => action.type === 'exchange');
11970
- if (!fulfilOrderAction) {
11971
- throw new Error('No exchange action found');
11972
- }
11973
- fulfillmentActions.push({
11974
- type: ActionType.TRANSACTION,
11975
- buildTransaction: prepareTransaction(fulfilOrderAction.transactionMethods),
11976
- purpose: TransactionPurpose.FULFILL_ORDER,
11977
- });
11978
- return {
11979
- actions: fulfillmentActions,
11980
- // return the shortest expiration out of all extraData - they should be very close
11981
- expiration: fulfillOrderDetails
11982
- .map((d) => Seaport.getExpirationISOTimeFromExtraData(d.extraData))
11983
- .reduce((p, c) => (new Date(p) < new Date(c) ? p : c)),
11984
- };
11985
- }
11986
- async cancelOrders(orders, account) {
11987
- const orderComponents = orders.map((order) => this.mapImmutableOrderToSeaportOrderComponents(order).orderComponents);
11988
- const seaportLib = this.getSeaportLib(orders[0]);
11989
- const cancellationTransaction = await seaportLib.cancelOrders(orderComponents, account);
11990
- return {
11991
- type: ActionType.TRANSACTION,
11992
- buildTransaction: prepareTransaction(cancellationTransaction),
11993
- purpose: TransactionPurpose.CANCEL,
11994
- };
11995
- }
11996
- mapImmutableOrderToSeaportOrderComponents(order) {
11997
- const orderCounter = order.protocol_data.counter;
11998
- return mapImmutableOrderToSeaportOrderComponents(order, orderCounter, this.zoneContractAddress);
11999
- }
12000
- createSeaportOrder(offerer, listingItem, considerationItem, orderStart, orderExpiry) {
12001
- const seaportLib = this.getSeaportLib();
12002
- return seaportLib.createOrder({
12003
- allowPartialFills: false,
12004
- offer: [
12005
- {
12006
- itemType: ItemType.ERC721,
12007
- token: listingItem.contractAddress,
12008
- identifier: listingItem.tokenId,
12009
- },
12010
- ],
12011
- consideration: [
12012
- {
12013
- token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
12014
- amount: considerationItem.amount,
12015
- recipient: offerer,
12016
- },
12017
- ],
12018
- startTime: (orderStart.getTime() / 1000).toFixed(0),
12019
- endTime: (orderExpiry.getTime() / 1000).toFixed(0),
12020
- zone: this.zoneContractAddress,
12021
- restrictedByZone: true,
12022
- }, offerer);
12023
- }
12024
- async getTypedDataFromOrderComponents(orderComponents) {
12025
- const { chainId } = await this.provider.getNetwork();
12026
- const domainData = {
12027
- name: SEAPORT_CONTRACT_NAME,
12028
- version: SEAPORT_CONTRACT_VERSION_V1_5,
12029
- chainId,
12030
- verifyingContract: this.seaportContractAddress,
12031
- };
12032
- return {
12033
- domain: domainData,
12034
- types: EIP_712_ORDER_TYPE,
12035
- value: orderComponents,
12036
- };
12037
- }
12038
- getSeaportLib(order) {
12039
- const seaportAddress = order?.protocol_data?.seaport_address ?? this.seaportContractAddress;
12040
- const seaportVersion = SEAPORT_CONTRACT_VERSION_V1_5;
12041
- // if (order?.protocol_data?.seaport_version === SEAPORT_CONTRACT_VERSION_V1_5) {
12042
- // seaportVersion = SEAPORT_CONTRACT_VERSION_V1_5;
12043
- // }
12044
- return this.seaportLibFactory.create(seaportVersion, seaportAddress);
12045
- }
12046
- static getExpirationISOTimeFromExtraData(extraData) {
12047
- // Expirtaion bytes in SIP7 extra data [21:29]
12048
- // In hex string -> [21 * 2 + 2 (0x) : 29 * 2]
12049
- // In JS slice (start, end_inclusive), (44,60)
12050
- // 8 bytes uint64 epoch time in seconds
12051
- const expirationHex = extraData.slice(44, 60);
12052
- const expirationInSeconds = parseInt(expirationHex, 16);
12053
- return new Date(expirationInSeconds * 1000).toISOString();
12054
- }
12055
- }
12056
-
12057
- class ImmutableApiClient {
12058
- orderbookService;
12059
- chainName;
12060
- seaportAddress;
12061
- constructor(orderbookService, chainName, seaportAddress) {
12062
- this.orderbookService = orderbookService;
12063
- this.chainName = chainName;
12064
- this.seaportAddress = seaportAddress;
12065
- }
12066
- async fulfillmentData(requests) {
12067
- return this.orderbookService.fulfillmentData({
12068
- chainName: this.chainName,
12069
- requestBody: requests,
12070
- });
12071
- }
12072
- async getListing(listingId) {
12073
- return this.orderbookService.getListing({
12074
- chainName: this.chainName,
12075
- listingId,
12076
- });
12077
- }
12078
- async getTrade(tradeId) {
12079
- return this.orderbookService.getTrade({
12080
- chainName: this.chainName,
12081
- tradeId,
12082
- });
12083
- }
12084
- async listListings(listOrderParams) {
12085
- return this.orderbookService.listListings({
12086
- chainName: this.chainName,
12087
- ...listOrderParams,
12088
- });
12089
- }
12090
- async listTrades(listTradesParams) {
12091
- return this.orderbookService.listTrades({
12092
- chainName: this.chainName,
12093
- ...listTradesParams,
12094
- });
12095
- }
12096
- async cancelOrders(orderIds, accountAddress, signature) {
12097
- return this.orderbookService.cancelOrders({
12098
- chainName: this.chainName,
12099
- requestBody: {
12100
- account_address: accountAddress,
12101
- orders: orderIds,
12102
- signature,
12103
- },
12104
- });
12105
- }
12106
- async createListing({ orderHash, orderComponents, orderSignature, makerFees, }) {
12107
- if (orderComponents.offer.length !== 1) {
12108
- throw new Error('Only one item can be listed at a time');
12109
- }
12110
- if (Number(orderComponents.offer[0].itemType) !== ItemType.ERC721) {
12111
- throw new Error('Only ERC721 tokens can be listed');
12112
- }
12113
- const orderTypes = [
12114
- ...orderComponents.consideration.map((c) => c.itemType),
12115
- ];
12116
- const isSameConsiderationType = new Set(orderTypes).size === 1;
12117
- if (!isSameConsiderationType) {
12118
- throw new Error('All consideration items must be of the same type');
12119
- }
12120
- return this.orderbookService.createListing({
12121
- chainName: this.chainName,
12122
- requestBody: {
12123
- order_hash: orderHash,
12124
- account_address: orderComponents.offerer,
12125
- buy: [
12126
- {
12127
- item_type: Number(orderComponents.consideration[0].itemType)
12128
- === ItemType.NATIVE
12129
- ? 'NATIVE'
12130
- : 'ERC20',
12131
- start_amount: orderComponents.consideration[0].startAmount,
12132
- contract_address: orderComponents.consideration[0].token,
12133
- },
12134
- ],
12135
- fees: makerFees.map((x) => ({
12136
- amount: x.amount,
12137
- fee_type: FeeType.MAKER_ECOSYSTEM,
12138
- recipient: x.recipient,
12139
- })),
12140
- end_at: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
12141
- protocol_data: {
12142
- order_type: ProtocolData.order_type.FULL_RESTRICTED,
12143
- zone_address: orderComponents.zone,
12144
- seaport_address: this.seaportAddress,
12145
- seaport_version: SEAPORT_CONTRACT_VERSION_V1_5,
12146
- counter: orderComponents.counter.toString(),
12147
- },
12148
- salt: orderComponents.salt,
12149
- sell: [
12150
- {
12151
- contract_address: orderComponents.offer[0].token,
12152
- token_id: orderComponents.offer[0].identifierOrCriteria,
12153
- item_type: 'ERC721',
12154
- },
12155
- ],
12156
- signature: orderSignature,
12157
- start_at: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
12158
- },
12159
- });
12160
- }
12161
- }
12162
-
12163
- class ImmutableApiClientFactory {
12164
- chainName;
12165
- seaportAddress;
12166
- orderbookClient;
12167
- constructor(apiEndpoint, chainName, seaportAddress) {
12168
- this.chainName = chainName;
12169
- this.seaportAddress = seaportAddress;
12170
- this.orderbookClient = new OrderBookClient({
12171
- // eslint-disable-next-line @typescript-eslint/naming-convention
12172
- BASE: apiEndpoint,
12173
- });
12174
- }
12175
- create() {
12176
- return new ImmutableApiClient(this.orderbookClient.orders, this.chainName, this.seaportAddress);
12177
- }
12178
- }
12179
-
12180
- const TESTNET_CHAIN_NAME = 'imtbl-zkevm-testnet';
12181
- const MAINNET_CHAIN_NAME = 'imtbl-zkevm-mainnet';
12182
- function getOrderbookConfig(environment) {
12183
- switch (environment) {
12184
- case Environment.SANDBOX:
12185
- return {
12186
- seaportContractAddress: '0x7Fb7Da6De152597830eD16361633e362A2F59410',
12187
- zoneContractAddress: '0x63441cBfBd15Dd8f5E92598E535661Ac5aCB808E',
12188
- apiEndpoint: 'https://api.sandbox.immutable.com',
12189
- chainName: TESTNET_CHAIN_NAME,
12190
- provider: new ethers.providers.JsonRpcProvider('https://rpc.testnet.immutable.com'),
12191
- };
12192
- // not yet deployed
12193
- case Environment.PRODUCTION:
12194
- return {
12195
- seaportContractAddress: '',
12196
- zoneContractAddress: '',
12197
- apiEndpoint: 'https://api.immutable.com',
12198
- chainName: MAINNET_CHAIN_NAME,
12199
- provider: new ethers.providers.JsonRpcProvider('https://rpc.immutable.com'),
12200
- };
12201
- default:
12202
- return null;
12203
- }
12204
- }
12205
-
12206
- class SeaportLibFactory {
12207
- defaultSeaportContractAddress;
12208
- provider;
12209
- constructor(defaultSeaportContractAddress, provider) {
12210
- this.defaultSeaportContractAddress = defaultSeaportContractAddress;
12211
- this.provider = provider;
12212
- }
12213
- create(orderSeaportVersion, orderSeaportAddress) {
12214
- const seaportVersion = orderSeaportVersion ?? SEAPORT_CONTRACT_VERSION_V1_5;
12215
- const seaportContractAddress = orderSeaportAddress ?? this.defaultSeaportContractAddress;
12216
- return new seaportJs.Seaport(this.provider, {
12217
- seaportVersion,
12218
- balanceAndApprovalChecksOnOrderCreation: true,
12219
- overrides: {
12220
- contractAddress: seaportContractAddress,
12221
- },
12222
- });
12223
- }
12224
- }
12225
-
12226
- /**
12227
- * zkEVM orderbook SDK
12228
- * @constructor
12229
- * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
12230
- */
12231
- class Orderbook {
12232
- apiClient;
12233
- seaport;
12234
- orderbookConfig;
12235
- constructor(config) {
12236
- const obConfig = getOrderbookConfig(config.baseConfig.environment);
12237
- const finalConfig = {
12238
- ...obConfig,
12239
- ...config.overrides,
12240
- };
12241
- if (!finalConfig) {
12242
- throw new Error('Orderbook configuration not passed, please specify the environment under config.baseConfig.environment');
12243
- }
12244
- this.orderbookConfig = finalConfig;
12245
- const { apiEndpoint, chainName } = this.orderbookConfig;
12246
- if (!apiEndpoint) {
12247
- throw new Error('API endpoint must be provided');
12248
- }
12249
- this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.orderbookConfig.seaportContractAddress).create();
12250
- const seaportLibFactory = new SeaportLibFactory(this.orderbookConfig.seaportContractAddress, this.orderbookConfig.provider);
12251
- this.seaport = new Seaport(seaportLibFactory, this.orderbookConfig.provider, this.orderbookConfig.seaportContractAddress, this.orderbookConfig.zoneContractAddress);
12252
- }
12253
- /**
12254
- * Return the configuration for the orderbook module.
12255
- * @return {OrderbookModuleConfiguration} The configuration for the orderbook module.
12256
- */
12257
- config() {
12258
- return this.orderbookConfig;
12259
- }
12260
- /**
12261
- * Get an order by ID
12262
- * @param {string} listingId - The listingId to find.
12263
- * @return {ListingResult} The returned order result.
12264
- */
12265
- async getListing(listingId) {
12266
- const apiListing = await this.apiClient.getListing(listingId);
12267
- return {
12268
- result: mapFromOpenApiOrder(apiListing.result),
12269
- };
12270
- }
12271
- /**
12272
- * Get a trade by ID
12273
- * @param {string} tradeId - The tradeId to find.
12274
- * @return {TradeResult} The returned order result.
12275
- */
12276
- async getTrade(tradeId) {
12277
- const apiListing = await this.apiClient.getTrade(tradeId);
12278
- return {
12279
- result: mapFromOpenApiTrade(apiListing.result),
12280
- };
12281
- }
12282
- /**
12283
- * List orders. This method is used to get a list of orders filtered by conditions specified
12284
- * in the params object.
12285
- * @param {ListListingsParams} listOrderParams - Filtering, ordering and page parameters.
12286
- * @return {ListListingsResult} The paged orders.
12287
- */
12288
- async listListings(listOrderParams) {
12289
- const apiListings = await this.apiClient.listListings(listOrderParams);
12290
- return {
12291
- page: mapFromOpenApiPage(apiListings.page),
12292
- result: apiListings.result.map(mapFromOpenApiOrder),
12293
- };
12294
- }
12295
- /**
12296
- * List trades. This method is used to get a list of trades filtered by conditions specified
12297
- * in the params object
12298
- * @param {ListTradesParams} listTradesParams - Filtering, ordering and page parameters.
12299
- * @return {ListTradesResult} The paged trades.
12300
- */
12301
- async listTrades(listTradesParams) {
12302
- const apiListings = await this.apiClient.listTrades(listTradesParams);
12303
- return {
12304
- page: mapFromOpenApiPage(apiListings.page),
12305
- result: apiListings.result.map(mapFromOpenApiTrade),
12306
- };
12307
- }
12308
- /**
12309
- * Get required transactions and messages for signing prior to creating a listing
12310
- * through the createListing method
12311
- * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
12312
- * @return {PrepareListingResponse} PrepareListingResponse includes
12313
- * the unsigned approval transaction, the typed order message for signing and
12314
- * the order components that can be submitted to `createListing` with a signature.
12315
- */
12316
- async prepareListing({ makerAddress, sell, buy, orderExpiry, }) {
12317
- return this.seaport.prepareSeaportOrder(makerAddress, sell, buy,
12318
- // Default order start to now
12319
- new Date(),
12320
- // Default order expiry to 2 years from now
12321
- orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
12322
- }
12323
- /**
12324
- * Create an order
12325
- * @param {CreateListingParams} createListingParams - create an order with the given params.
12326
- * @return {ListingResult} The result of the order created in the Immutable services.
12327
- */
12328
- async createListing(createListingParams) {
12329
- const apiListingResponse = await this.apiClient.createListing({
12330
- ...createListingParams,
12331
- });
12332
- return {
12333
- result: mapFromOpenApiOrder(apiListingResponse.result),
12334
- };
12335
- }
12336
- /**
12337
- * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
12338
- * transaction exists it must be signed and submitted to the chain before the fulfilment
12339
- * transaction can be submitted or it will be reverted.
12340
- * @param {string} listingId - The listingId to fulfil.
12341
- * @param {string} fulfillerAddress - The address of the account fulfilling the order.
12342
- * @return {FulfillOrderResponse} Approval and fulfilment transactions.
12343
- */
12344
- async fulfillOrder(listingId, takerAddress, takerFees) {
12345
- const fulfillmentDataRes = await this.apiClient.fulfillmentData([
12346
- {
12347
- order_id: listingId,
12348
- fees: takerFees.map((fee) => ({
12349
- amount: fee.amount,
12350
- fee_type: FeeType.TAKER_ECOSYSTEM,
12351
- recipient: fee.recipient,
12352
- })),
12353
- },
12354
- ]);
12355
- if (fulfillmentDataRes.result.unfulfillable_orders?.length > 0) {
12356
- throw new Error(`Unable to prepare fulfillment date: ${fulfillmentDataRes.result.unfulfillable_orders[0].reason}`);
12357
- }
12358
- else if (fulfillmentDataRes.result.fulfillable_orders?.length !== 1) {
12359
- throw new Error('unexpected fulfillable order result length');
12360
- }
12361
- const extraData = fulfillmentDataRes.result.fulfillable_orders[0].extra_data;
12362
- const orderResult = fulfillmentDataRes.result.fulfillable_orders[0].order;
12363
- if (orderResult.status.name !== OrderStatusName.ACTIVE) {
12364
- throw new Error(`Cannot fulfil order that is not active. Current status: ${orderResult.status}`);
12365
- }
12366
- return this.seaport.fulfillOrder(orderResult, takerAddress, extraData);
12367
- }
12368
- async fulfillBulkOrders(listings, takerAddress) {
12369
- const fulfillmentDataRes = await this.apiClient.fulfillmentData(listings.map((listingRequest) => ({
12370
- order_id: listingRequest.listingId,
12371
- fees: listingRequest.takerFees.map((fee) => ({
12372
- amount: fee.amount,
12373
- fee_type: FeeType.TAKER_ECOSYSTEM,
12374
- recipient: fee.recipient,
12375
- })),
12376
- })));
12377
- try {
12378
- return {
12379
- ...(await this.seaport.fulfillBulkOrders(fulfillmentDataRes.result.fulfillable_orders, takerAddress)),
12380
- fulfillableOrders: fulfillmentDataRes.result.fulfillable_orders.map((o) => mapFromOpenApiOrder(o.order)),
12381
- unfulfillableOrders: fulfillmentDataRes.result.unfulfillable_orders.map((o) => ({
12382
- orderId: o.order_id,
12383
- reason: o.reason,
12384
- })),
12385
- sufficientBalance: true,
12386
- };
12387
- }
12388
- catch (e) {
12389
- // if insufficient balance error, we return FulfillBulkOrdersInsufficientBalanceResponse
12390
- if (String(e).includes('The fulfiller does not have the balances needed to fulfill.')) {
12391
- return {
12392
- fulfillableOrders: fulfillmentDataRes.result.fulfillable_orders.map((o) => mapFromOpenApiOrder(o.order)),
12393
- unfulfillableOrders: fulfillmentDataRes.result.unfulfillable_orders.map((o) => ({
12394
- orderId: o.order_id,
12395
- reason: o.reason,
12396
- })),
12397
- sufficientBalance: false,
12398
- };
12399
- }
12400
- // if some other error is thrown,
12401
- // there likely is a race condition of the original order validity
12402
- // we throw the error back out
12403
- throw e;
12404
- }
12405
- }
12406
- /**
12407
- * Cancelling orders is a gasless alternative to on-chain cancellation exposed with
12408
- * `cancelOrdersOnChain`. For the orderbook to authenticate the cancellation, the creator
12409
- * of the orders must sign an EIP712 message containing the orderIds
12410
- * @param {string} orderIds - The orderIds to attempt to cancel.
12411
- * @return {PrepareCancelOrdersResponse} The signable action to cancel the orders.
12412
- */
12413
- async prepareOrderCancellations(orderIds) {
12414
- const network = await this.orderbookConfig.provider.getNetwork();
12415
- const domain = {
12416
- name: 'imtbl-order-book',
12417
- chainId: network.chainId,
12418
- verifyingContract: this.orderbookConfig.seaportContractAddress,
12419
- };
12420
- const types = {
12421
- // eslint-disable-next-line @typescript-eslint/naming-convention
12422
- CancelPayload: [
12423
- { name: 'orders', type: 'Order[]' },
12424
- ],
12425
- // eslint-disable-next-line @typescript-eslint/naming-convention
12426
- Order: [
12427
- { name: 'id', type: 'string' },
12428
- ],
12429
- };
12430
- const cancelMessage = {
12431
- orders: orderIds.map((id) => ({ id })),
12432
- };
12433
- return {
12434
- signableAction: {
12435
- purpose: SignablePurpose.OFF_CHAIN_CANCELLATION,
12436
- type: ActionType.SIGNABLE,
12437
- message: {
12438
- domain,
12439
- types,
12440
- value: cancelMessage,
12441
- },
12442
- },
12443
- };
12444
- }
12445
- /**
12446
- * Cancelling orders is a gasless alternative to on-chain cancellation exposed with
12447
- * `cancelOrdersOnChain`. Orders cancelled this way cannot be fulfilled and will be removed
12448
- * from the orderbook. If there is pending fulfillment data outstanding for the order, its
12449
- * cancellation will be pending until the fulfillment window has passed.
12450
- * `prepareOffchainOrderCancellations` can be used to get the signable action that is signed
12451
- * to get the signature required for this call.
12452
- * @param {string[]} orderIds - The orderIds to attempt to cancel.
12453
- * @param {string} accountAddress - The address of the account cancelling the orders.
12454
- * @param {string} accountAddress - The address of the account cancelling the orders.
12455
- * @return {CancelOrdersResult} The result of the off-chain cancellation request
12456
- */
12457
- async cancelOrders(orderIds, accountAddress, signature) {
12458
- return this.apiClient.cancelOrders(orderIds, accountAddress, signature);
12459
- }
12460
- /**
12461
- * Get an unsigned order cancellation transaction. Orders can only be cancelled by
12462
- * the account that created them. All of the orders must be from the same seaport contract.
12463
- * If trying to cancel orders from multiple seaport contracts, group the orderIds by seaport
12464
- * contract and call this method for each group.
12465
- * @param {string[]} orderIds - The orderIds to cancel.
12466
- * @param {string} accountAddress - The address of the account cancelling the order.
12467
- * @return {CancelOrdersOnChainResponse} The unsigned cancel order action
12468
- */
12469
- async cancelOrdersOnChain(orderIds, accountAddress) {
12470
- const orderResults = await Promise.all(orderIds.map((id) => this.apiClient.getListing(id)));
12471
- // eslint-disable-next-line no-restricted-syntax
12472
- for (const orderResult of orderResults) {
12473
- if (orderResult.result.status.name !== OrderStatusName.ACTIVE
12474
- && orderResult.result.status.name !== OrderStatusName.INACTIVE
12475
- && orderResult.result.status.name !== OrderStatusName.PENDING) {
12476
- throw new Error(`Cannot cancel order with status ${orderResult.result.status}`);
12477
- }
12478
- if (orderResult.result.account_address !== accountAddress.toLowerCase()) {
12479
- throw new Error(`Only account ${orderResult.result.account_address} can cancel order ${orderResult.result.id}`);
12480
- }
12481
- }
12482
- const orders = orderResults.map((orderResult) => orderResult.result);
12483
- const seaportAddresses = orders.map((o) => o.protocol_data.seaport_address);
12484
- const distinctSeaportAddresses = new Set(...[seaportAddresses]);
12485
- if (distinctSeaportAddresses.size !== 1) {
12486
- throw new Error('Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly');
12487
- }
12488
- const cancellationAction = await this.seaport.cancelOrders(orders, accountAddress);
12489
- return { cancellationAction };
12490
- }
12491
- }
12492
-
12493
- // Consumers might want an estimated gas limit for fulfilling an order
12494
- // without calling the transaction builder. This is an estimate that
12495
- // should work for all fulfillment scenarios.
12496
- const ESTIMATED_FULFILLMENT_GAS_GWEI = 400000;
12497
- const constants = {
12498
- estimatedFulfillmentGasGwei: ESTIMATED_FULFILLMENT_GAS_GWEI,
12499
- };
12500
-
12501
- var orderbook = /*#__PURE__*/Object.freeze({
12502
- __proto__: null,
12503
- get ActionType () { return ActionType; },
12504
- get FeeType () { return FeeType; },
12505
- get OrderStatusName () { return OrderStatusName; },
12506
- Orderbook: Orderbook,
12507
- get SignablePurpose () { return SignablePurpose; },
12508
- get TransactionPurpose () { return TransactionPurpose; },
12509
- constants: constants
12510
- });
12511
-
12512
10931
  function isChainValid(chainID, config) {
12513
10932
  return chainID === config.ethConfiguration.chainID;
12514
10933
  }
@@ -13596,6 +12015,5 @@ var provider = /*#__PURE__*/Object.freeze({
13596
12015
  exports.blockchainData = blockchain_data;
13597
12016
  exports.config = config;
13598
12017
  exports.immutablexClient = immutablex_client;
13599
- exports.orderbook = orderbook;
13600
12018
  exports.passport = passport;
13601
12019
  exports.provider = provider;