@imtbl/sdk 1.35.2-alpha → 1.35.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.
Files changed (40) hide show
  1. package/dist/blockchain_data.js +2 -2
  2. package/dist/browser/checkout/{BridgeWidget-22c8b08d.js → BridgeWidget-b9e736eb.js} +1 -1
  3. package/dist/browser/checkout/{OnRampWidget-aeb5d57c.js → OnRampWidget-08bfa49c.js} +1 -1
  4. package/dist/browser/checkout/{SaleWidget-93a4fffd.js → SaleWidget-62cda384.js} +1 -1
  5. package/dist/browser/checkout/{SpendingCapHero-8459b91d.js → SpendingCapHero-341cfc38.js} +1 -1
  6. package/dist/browser/checkout/{SwapWidget-11ecb4ae.js → SwapWidget-40adbff0.js} +1 -1
  7. package/dist/browser/checkout/{TopUpView-ad058510.js → TopUpView-17d237f3.js} +1 -1
  8. package/dist/browser/checkout/{WalletWidget-920b03b4.js → WalletWidget-a19ab89c.js} +1 -1
  9. package/dist/browser/checkout/{auto-track-469b3ba5.js → auto-track-ffcab507.js} +1 -1
  10. package/dist/browser/checkout/{balance-c9c03af5.js → balance-4d6f9b6f.js} +1 -1
  11. package/dist/browser/checkout/{index-06896b92.js → index-11eefc56.js} +1 -1
  12. package/dist/browser/checkout/{index-09b1efac.js → index-317dcefc.js} +1 -1
  13. package/dist/browser/checkout/{index-9997f064.js → index-4fb1863d.js} +1 -1
  14. package/dist/browser/checkout/{index-e5f07d9e.js → index-7a9fdf09.js} +2 -2
  15. package/dist/browser/checkout/{index-cbf7168d.js → index-9a663258.js} +1 -1
  16. package/dist/browser/checkout/{index-37c4003a.js → index-ab21662b.js} +1 -1
  17. package/dist/browser/checkout/index-bafd7f6d.js +1 -0
  18. package/dist/browser/checkout/{index-c53e5321.js → index-be2f6fa5.js} +1 -1
  19. package/dist/browser/checkout/{index.umd-e783a603.js → index.umd-cb823fd6.js} +1 -1
  20. package/dist/browser/checkout/{retry-10de11e8.js → retry-0002f89a.js} +1 -1
  21. package/dist/browser/checkout/sdk.js +4 -4
  22. package/dist/browser/checkout/widgets-esm.js +1 -1
  23. package/dist/browser/checkout/widgets.js +1 -1
  24. package/dist/checkout.d.ts +14 -2
  25. package/dist/checkout.js +18 -13
  26. package/dist/config.js +1 -1
  27. package/dist/index.browser.js +4 -4
  28. package/dist/index.browser.js.map +1 -1
  29. package/dist/index.cjs +89 -578
  30. package/dist/index.d.ts +21 -114
  31. package/dist/index.js +90 -577
  32. package/dist/orderbook.js +1 -1
  33. package/dist/passport.js +64 -55
  34. package/dist/x.js +3 -3
  35. package/package.json +1 -9
  36. package/dist/browser/checkout/index-1b8b7ce9.js +0 -1
  37. package/dist/minting_backend.d.ts +0 -3506
  38. package/dist/minting_backend.js +0 -447
  39. package/dist/webhook.d.ts +0 -11
  40. package/dist/webhook.js +0 -388
package/dist/index.js CHANGED
@@ -33,7 +33,6 @@ import { keccak256 as keccak256$3 } from '@ethersproject/solidity';
33
33
  import { SwapRouter, PaymentsExtended } from '@uniswap/router-sdk';
34
34
  import { parseUnits as parseUnits$1 } from '@ethersproject/units';
35
35
  import { BigNumber as BigNumber$2 } from '@ethersproject/bignumber';
36
- import MessageValidator from 'sns-validator';
37
36
 
38
37
  const isNode$1 = () => typeof window === 'undefined';
39
38
  const isBrowser$1 = () => !isNode$1();
@@ -161,7 +160,7 @@ const flattenProperties$1 = (properties) => {
161
160
  };
162
161
 
163
162
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
164
- const SDK_VERSION$1 = '1.35.2-alpha';
163
+ const SDK_VERSION$1 = '1.35.3';
165
164
  const getFrameParentDomain$1 = () => {
166
165
  if (isNode$1()) {
167
166
  return '';
@@ -14188,7 +14187,7 @@ class MultiRollupApiClients {
14188
14187
  }
14189
14188
 
14190
14189
  // eslint-disable-next-line @typescript-eslint/naming-convention
14191
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.35.2-alpha' };
14190
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.35.3' };
14192
14191
  const createConfig$1 = ({ basePath, headers, }) => {
14193
14192
  if (!basePath.trim()) {
14194
14193
  throw Error('basePath can not be empty');
@@ -14260,7 +14259,7 @@ class APIError extends Error {
14260
14259
 
14261
14260
  /* eslint-disable implicit-arrow-linebreak */
14262
14261
  const defaultHeaders$1 = {
14263
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.35.2-alpha',
14262
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.35.3',
14264
14263
  };
14265
14264
  /**
14266
14265
  * createAPIConfiguration to create a custom Configuration
@@ -14734,7 +14733,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
14734
14733
  /* eslint-disable @typescript-eslint/naming-convention */
14735
14734
  class ApiConfiguration extends index$2.Configuration {
14736
14735
  }
14737
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.35.2-alpha' };
14736
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.35.3' };
14738
14737
  /**
14739
14738
  * @dev use createImmutableXConfiguration instead
14740
14739
  */
@@ -14773,7 +14772,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
14773
14772
  chainID,
14774
14773
  coreContractAddress,
14775
14774
  registrationContractAddress,
14776
- sdkVersion: 'ts-immutable-sdk-1.35.2-alpha',
14775
+ sdkVersion: 'ts-immutable-sdk-1.35.3',
14777
14776
  baseConfig,
14778
14777
  });
14779
14778
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -23595,12 +23594,12 @@ function assertOptions$1(options, schema, allowUnknown) {
23595
23594
  }
23596
23595
  }
23597
23596
 
23598
- var validator$2 = {
23597
+ var validator$1 = {
23599
23598
  assertOptions: assertOptions$1,
23600
23599
  validators: validators$1$1
23601
23600
  };
23602
23601
 
23603
- const validators$2 = validator$2.validators;
23602
+ const validators$2 = validator$1.validators;
23604
23603
 
23605
23604
  /**
23606
23605
  * Create a new instance of Axios
@@ -23641,7 +23640,7 @@ let Axios$2 = class Axios {
23641
23640
  const {transitional, paramsSerializer, headers} = config;
23642
23641
 
23643
23642
  if (transitional !== undefined) {
23644
- validator$2.assertOptions(transitional, {
23643
+ validator$1.assertOptions(transitional, {
23645
23644
  silentJSONParsing: validators$2.transitional(validators$2.boolean),
23646
23645
  forcedJSONParsing: validators$2.transitional(validators$2.boolean),
23647
23646
  clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
@@ -23654,7 +23653,7 @@ let Axios$2 = class Axios {
23654
23653
  serialize: paramsSerializer
23655
23654
  };
23656
23655
  } else {
23657
- validator$2.assertOptions(paramsSerializer, {
23656
+ validator$1.assertOptions(paramsSerializer, {
23658
23657
  encode: validators$2.function,
23659
23658
  serialize: validators$2.function
23660
23659
  }, true);
@@ -25388,7 +25387,7 @@ async function exchangeTransfer$1({ user, starkSigner, request, exchangesApi, })
25388
25387
 
25389
25388
  const ERC721$1 = 'ERC721';
25390
25389
  async function createOrder$1({ starkSigner, user, request, ordersApi, guardianClient, }) {
25391
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
25390
+ return withPassportError(async () => {
25392
25391
  const { ethAddress } = user.imx;
25393
25392
  const amountSell = request.sell.type === ERC721$1 ? '1' : request.sell.amount;
25394
25393
  const amountBuy = request.buy.type === ERC721$1 ? '1' : request.buy.amount;
@@ -25434,10 +25433,10 @@ async function createOrder$1({ starkSigner, user, request, ordersApi, guardianCl
25434
25433
  return {
25435
25434
  ...createOrderResponse.data,
25436
25435
  };
25437
- }), PassportErrorType.CREATE_ORDER_ERROR);
25436
+ }, PassportErrorType.CREATE_ORDER_ERROR);
25438
25437
  }
25439
25438
  async function cancelOrder$1({ user, starkSigner, request, ordersApi, guardianClient, }) {
25440
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
25439
+ return withPassportError(async () => {
25441
25440
  const getSignableCancelOrderRequest = {
25442
25441
  order_id: request.order_id,
25443
25442
  };
@@ -25464,7 +25463,7 @@ async function cancelOrder$1({ user, starkSigner, request, ordersApi, guardianCl
25464
25463
  order_id: cancelOrderResponse.data.order_id,
25465
25464
  status: cancelOrderResponse.data.status,
25466
25465
  };
25467
- }), PassportErrorType.CANCEL_ORDER_ERROR);
25466
+ }, PassportErrorType.CANCEL_ORDER_ERROR);
25468
25467
  }
25469
25468
 
25470
25469
  async function registerPassport({ ethSigner, starkSigner, imxApiClients }, authorization) {
@@ -25496,7 +25495,7 @@ async function registerPassport({ ethSigner, starkSigner, imxApiClients }, autho
25496
25495
  }
25497
25496
 
25498
25497
  async function createTrade$1({ request, tradesApi, user, starkSigner, guardianClient, }) {
25499
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
25498
+ return withPassportError(async () => {
25500
25499
  const { ethAddress } = user.imx;
25501
25500
  const getSignableTradeRequest = {
25502
25501
  expiration_timestamp: request.expiration_timestamp,
@@ -25537,12 +25536,12 @@ async function createTrade$1({ request, tradesApi, user, starkSigner, guardianCl
25537
25536
  headers,
25538
25537
  });
25539
25538
  return createTradeResponse;
25540
- }), PassportErrorType.CREATE_TRADE_ERROR);
25539
+ }, PassportErrorType.CREATE_TRADE_ERROR);
25541
25540
  }
25542
25541
 
25543
25542
  const ERC721 = 'ERC721';
25544
25543
  async function transfer$1({ request, transfersApi, starkSigner, user, guardianClient, }) {
25545
- return withPassportError(guardianClient.withDefaultConfirmationScreenTask(async () => {
25544
+ return withPassportError(async () => {
25546
25545
  const transferAmount = request.type === ERC721 ? '1' : request.amount;
25547
25546
  const getSignableTransferRequest = {
25548
25547
  sender: user.imx.ethAddress,
@@ -25584,11 +25583,10 @@ async function transfer$1({ request, transfersApi, starkSigner, user, guardianCl
25584
25583
  time: responseData.time,
25585
25584
  transfer_id: responseData.transfer_id,
25586
25585
  };
25587
- }), PassportErrorType.TRANSFER_ERROR);
25586
+ }, PassportErrorType.TRANSFER_ERROR);
25588
25587
  }
25589
25588
  async function batchNftTransfer({ user, starkSigner, request, transfersApi, guardianClient, }) {
25590
- // eslint-disable-next-line function-paren-newline
25591
- return withPassportError(guardianClient.withConfirmationScreenTask({ width: 480, height: 784 })(async () => {
25589
+ return withPassportError(async () => {
25592
25590
  const { ethAddress } = user.imx;
25593
25591
  const signableRequests = request.map((nftTransfer) => ({
25594
25592
  amount: '1',
@@ -25632,7 +25630,7 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, guar
25632
25630
  return {
25633
25631
  transfer_ids: response?.data.transfer_ids,
25634
25632
  };
25635
- }), PassportErrorType.TRANSFER_ERROR);
25633
+ }, PassportErrorType.TRANSFER_ERROR);
25636
25634
  }
25637
25635
 
25638
25636
  const POLL_INTERVAL = 1 * 1000; // every 1 second
@@ -25783,14 +25781,16 @@ class PassportImxProvider {
25783
25781
  };
25784
25782
  }
25785
25783
  async transfer(request) {
25786
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25787
- return transfer$1({
25788
- request,
25789
- user,
25790
- starkSigner,
25791
- transfersApi: this.immutableXClient.transfersApi,
25792
- guardianClient: this.guardianClient,
25793
- });
25784
+ return (this.guardianClient.withDefaultConfirmationScreenTask(async () => {
25785
+ const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25786
+ return transfer$1({
25787
+ request,
25788
+ user,
25789
+ starkSigner,
25790
+ transfersApi: this.immutableXClient.transfersApi,
25791
+ guardianClient: this.guardianClient,
25792
+ });
25793
+ })());
25794
25794
  }
25795
25795
  async registerOffchain() {
25796
25796
  const [user, signers] = await Promise.all([
@@ -25808,44 +25808,52 @@ class PassportImxProvider {
25808
25808
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
25809
25809
  }
25810
25810
  async createOrder(request) {
25811
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25812
- return createOrder$1({
25813
- request,
25814
- user,
25815
- starkSigner,
25816
- ordersApi: this.immutableXClient.ordersApi,
25817
- guardianClient: this.guardianClient,
25818
- });
25811
+ return this.guardianClient.withDefaultConfirmationScreenTask(async () => {
25812
+ const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25813
+ return createOrder$1({
25814
+ request,
25815
+ user,
25816
+ starkSigner,
25817
+ ordersApi: this.immutableXClient.ordersApi,
25818
+ guardianClient: this.guardianClient,
25819
+ });
25820
+ })();
25819
25821
  }
25820
25822
  async cancelOrder(request) {
25821
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25822
- return cancelOrder$1({
25823
- request,
25824
- user,
25825
- starkSigner,
25826
- ordersApi: this.immutableXClient.ordersApi,
25827
- guardianClient: this.guardianClient,
25828
- });
25823
+ return this.guardianClient.withDefaultConfirmationScreenTask(async () => {
25824
+ const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25825
+ return cancelOrder$1({
25826
+ request,
25827
+ user,
25828
+ starkSigner,
25829
+ ordersApi: this.immutableXClient.ordersApi,
25830
+ guardianClient: this.guardianClient,
25831
+ });
25832
+ })();
25829
25833
  }
25830
25834
  async createTrade(request) {
25831
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25832
- return createTrade$1({
25833
- request,
25834
- user,
25835
- starkSigner,
25836
- tradesApi: this.immutableXClient.tradesApi,
25837
- guardianClient: this.guardianClient,
25838
- });
25835
+ return this.guardianClient.withDefaultConfirmationScreenTask(async () => {
25836
+ const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25837
+ return createTrade$1({
25838
+ request,
25839
+ user,
25840
+ starkSigner,
25841
+ tradesApi: this.immutableXClient.tradesApi,
25842
+ guardianClient: this.guardianClient,
25843
+ });
25844
+ })();
25839
25845
  }
25840
25846
  async batchNftTransfer(request) {
25841
- const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25842
- return batchNftTransfer({
25843
- request,
25844
- user,
25845
- starkSigner,
25846
- transfersApi: this.immutableXClient.transfersApi,
25847
- guardianClient: this.guardianClient,
25848
- });
25847
+ return this.guardianClient.withConfirmationScreenTask({ width: 480, height: 784 })(async () => {
25848
+ const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
25849
+ return batchNftTransfer({
25850
+ request,
25851
+ user,
25852
+ starkSigner,
25853
+ transfersApi: this.immutableXClient.transfersApi,
25854
+ guardianClient: this.guardianClient,
25855
+ });
25856
+ })();
25849
25857
  }
25850
25858
  async exchangeTransfer(request) {
25851
25859
  const { user, starkSigner } = await this.#getRegisteredImxUserAndSigners();
@@ -32307,12 +32315,12 @@ function assertOptions(options, schema, allowUnknown) {
32307
32315
  }
32308
32316
  }
32309
32317
 
32310
- var validator$1 = {
32318
+ var validator = {
32311
32319
  assertOptions,
32312
32320
  validators: validators$1
32313
32321
  };
32314
32322
 
32315
- const validators = validator$1.validators;
32323
+ const validators = validator.validators;
32316
32324
 
32317
32325
  /**
32318
32326
  * Create a new instance of Axios
@@ -32353,7 +32361,7 @@ class Axios {
32353
32361
  const {transitional, paramsSerializer, headers} = config;
32354
32362
 
32355
32363
  if (transitional !== undefined) {
32356
- validator$1.assertOptions(transitional, {
32364
+ validator.assertOptions(transitional, {
32357
32365
  silentJSONParsing: validators.transitional(validators.boolean),
32358
32366
  forcedJSONParsing: validators.transitional(validators.boolean),
32359
32367
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -32366,7 +32374,7 @@ class Axios {
32366
32374
  serialize: paramsSerializer
32367
32375
  };
32368
32376
  } else {
32369
- validator$1.assertOptions(paramsSerializer, {
32377
+ validator.assertOptions(paramsSerializer, {
32370
32378
  encode: validators.function,
32371
32379
  serialize: validators.function
32372
32380
  }, true);
@@ -58091,7 +58099,7 @@ const flattenProperties = (properties) => {
58091
58099
  };
58092
58100
 
58093
58101
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
58094
- const SDK_VERSION = '1.35.2-alpha';
58102
+ const SDK_VERSION = '1.35.3';
58095
58103
  const getFrameParentDomain = () => {
58096
58104
  if (isNode()) {
58097
58105
  return '';
@@ -63384,7 +63392,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
63384
63392
  maxPriorityFeePerGas: BigNumber$1.from(10e9),
63385
63393
  };
63386
63394
 
63387
- const SDK_VERSION_MARKER = '1.35.2-alpha';
63395
+ const SDK_VERSION_MARKER = '1.35.3';
63388
63396
  // This SDK version is replaced by the `yarn build` command ran on the root level
63389
63397
  const globalPackageVersion = () => SDK_VERSION_MARKER;
63390
63398
 
@@ -67131,22 +67139,23 @@ const sell = async (config, provider, orders) => {
67131
67139
  decimals = await measureAsyncExecution(config, 'Time to get decimals of token contract for the buy token', buyTokenContract.decimals());
67132
67140
  }
67133
67141
  const buyTokenOrNative = getBuyToken(buyToken, decimals);
67142
+ const sellTokenHasType = 'type' in sellToken;
67134
67143
  try {
67135
67144
  const walletAddress = await measureAsyncExecution(config, 'Time to get the address from the provider', provider.getSigner().getAddress());
67136
67145
  orderbook = createOrderbookInstance(config);
67137
67146
  const { seaportContractAddress } = orderbook.config();
67138
67147
  spenderAddress = seaportContractAddress;
67139
- const sellItem = sellToken.type === ItemType.ERC721
67148
+ const sellItem = sellTokenHasType && sellToken.type === ItemType.ERC1155
67140
67149
  ? {
67141
- type: sellToken.type,
67150
+ type: ItemType.ERC1155,
67142
67151
  contractAddress: sellToken.collectionAddress,
67143
67152
  tokenId: sellToken.id,
67153
+ amount: sellToken.amount,
67144
67154
  }
67145
67155
  : {
67146
- type: sellToken.type,
67156
+ type: ItemType.ERC721,
67147
67157
  contractAddress: sellToken.collectionAddress,
67148
67158
  tokenId: sellToken.id,
67149
- amount: sellToken.amount,
67150
67159
  };
67151
67160
  listing = await measureAsyncExecution(config, 'Time to prepare the listing from the orderbook', orderbook.prepareListing({
67152
67161
  makerAddress: walletAddress,
@@ -67162,11 +67171,15 @@ const sell = async (config, provider, orders) => {
67162
67171
  collectionAddress: sellToken.collectionAddress,
67163
67172
  });
67164
67173
  }
67165
- const itemRequirements = [
67166
- sellToken.type === ItemType.ERC721
67167
- ? getERC721Requirement(sellToken.id, sellToken.collectionAddress, spenderAddress)
67168
- : getERC1155Requirement(sellToken.id, sellToken.collectionAddress, spenderAddress, sellToken.amount),
67169
- ];
67174
+ const itemRequirements = [];
67175
+ if (sellTokenHasType && sellToken.type === ItemType.ERC1155) {
67176
+ const erc1155ItemRequirement = getERC1155Requirement(sellToken.id, sellToken.collectionAddress, spenderAddress, sellToken.amount);
67177
+ itemRequirements.push(erc1155ItemRequirement);
67178
+ }
67179
+ else {
67180
+ const erc721ItemRequirement = getERC721Requirement(sellToken.id, sellToken.collectionAddress, spenderAddress);
67181
+ itemRequirements.push(erc721ItemRequirement);
67182
+ }
67170
67183
  let smartCheckoutResult;
67171
67184
  const isPassport = provider.provider?.isPassport;
67172
67185
  if (!isPassport) {
@@ -69045,504 +69058,4 @@ var x = /*#__PURE__*/Object.freeze({
69045
69058
  sandbox: sandbox
69046
69059
  });
69047
69060
 
69048
- const validator = new MessageValidator();
69049
- const allowedTopicArnPrefix = {
69050
- [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
69051
- [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
69052
- };
69053
- const init = async (body, env, handlers) => {
69054
- const msg = await new Promise((resolve, reject) => {
69055
- validator.validate(body, (err, message) => {
69056
- if (err) {
69057
- return reject(err);
69058
- }
69059
- // check for topic arn prefix
69060
- if (!message.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
69061
- throw new Error('Invalid topic arn');
69062
- }
69063
- if (message?.Type === 'SubscriptionConfirmation') {
69064
- fetch(message.SubscribeURL).then(() => {
69065
- resolve(message);
69066
- }).catch((e) => {
69067
- reject(e);
69068
- });
69069
- }
69070
- return resolve(message);
69071
- });
69072
- });
69073
- if (msg.Type === 'Notification') {
69074
- const event = JSON.parse(msg.Message);
69075
- switch (event.event_name) {
69076
- case 'imtbl_zkevm_mint_request_updated':
69077
- await handlers.zkevmMintRequestUpdated(event);
69078
- break;
69079
- default:
69080
- if (handlers.others) {
69081
- await handlers.others(event);
69082
- }
69083
- break;
69084
- }
69085
- }
69086
- };
69087
-
69088
- var webhook = /*#__PURE__*/Object.freeze({
69089
- __proto__: null,
69090
- init: init
69091
- });
69092
-
69093
- const mintingPersistence$1 = (client) => ({
69094
- recordMint: async (request) => {
69095
- const r = await client.query(`
69096
- INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata)
69097
- VALUES ($1, $2, $3, $4) ON CONFLICT (asset_id) DO NOTHING;
69098
- `, [request.asset_id, request.contract_address, request.owner_address, request.metadata]);
69099
- if (r.rowCount === 0) {
69100
- throw new Error('Duplicated mint');
69101
- }
69102
- },
69103
- getNextBatchForSubmission: async (limit) => {
69104
- const res = await client.query(`
69105
- UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
69106
- select id from im_assets where minting_status is null limit $1 for update skip locked
69107
- ) returning *;
69108
- `, [limit]);
69109
- return res.rows;
69110
- },
69111
- updateMintingStatusToSubmitted: async (ids) => {
69112
- await client.query(`
69113
- UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
69114
- `, [ids, 'submitted']);
69115
- },
69116
- syncMintingStatus: async (submittedMintRequest) => {
69117
- // doing a upsert just in case the row has not been created yet
69118
- await client.query(`
69119
- INSERT INTO im_assets (
69120
- asset_id,
69121
- contract_address,
69122
- owner_address,
69123
- token_id,
69124
- minting_status,
69125
- metadata_id,
69126
- last_imtbl_zkevm_mint_request_updated_id,
69127
- error
69128
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (asset_id, contract_address)
69129
- DO UPDATE SET
69130
- owner_address = $3,
69131
- token_id = $4,
69132
- minting_status = $5,
69133
- metadata_id = $6,
69134
- last_imtbl_zkevm_mint_request_updated_id = $7,
69135
- error = $8
69136
- where (
69137
- im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
69138
- im_assets.last_imtbl_zkevm_mint_request_updated_id is null
69139
- );
69140
- `, [
69141
- submittedMintRequest.assetId,
69142
- submittedMintRequest.contractAddress,
69143
- submittedMintRequest.ownerAddress,
69144
- submittedMintRequest.tokenId,
69145
- submittedMintRequest.status,
69146
- submittedMintRequest.metadataId,
69147
- submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69148
- submittedMintRequest.error
69149
- ]);
69150
- },
69151
- markAsConflict: async (assetIds, contractAddress) => {
69152
- await client.query(`
69153
- UPDATE im_assets
69154
- SET minting_status = 'conflicting'
69155
- WHERE asset_id = ANY($1)
69156
- AND contract_address = $2;
69157
- `, [assetIds, contractAddress]);
69158
- },
69159
- resetMintingStatus: async (ids) => {
69160
- await client.query(`
69161
- UPDATE im_assets SET minting_status = null WHERE id = ANY($1);
69162
- `, [ids]);
69163
- },
69164
- markForRetry: async (ids) => {
69165
- await client.query(`
69166
- UPDATE im_assets
69167
- SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
69168
- `, [ids]);
69169
- },
69170
- updateMintingStatusToSubmissionFailed: async (ids) => {
69171
- await client.query(`
69172
- UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
69173
- `, [ids]);
69174
- },
69175
- getMintingRequest: async (contractAddress, referenceId) => {
69176
- const res = await client.query(`
69177
- SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
69178
- `, [contractAddress, referenceId]);
69179
- return res.rows[0] || null;
69180
- }
69181
- });
69182
-
69183
- // client is a PrismaClient instance. it needs to be generated with
69184
- // additional schema defined inside (TODO: point to repo) file.
69185
- const mintingPersistence = (client) => ({
69186
- recordMint: async (request) => {
69187
- const result = await client.imAssets.upsert({
69188
- where: {
69189
- im_assets_uindex: {
69190
- assetId: request.asset_id, contractAddress: request.contract_address
69191
- }
69192
- },
69193
- update: {},
69194
- create: {
69195
- assetId: request.asset_id,
69196
- contractAddress: request.contract_address,
69197
- ownerAddress: request.owner_address,
69198
- metadata: JSON.stringify(request.metadata), // Serialize JSON metadata
69199
- },
69200
- });
69201
- // Since upsert does not throw on update and does not tell directly if it updated or inserted,
69202
- // we need to add additional logic to handle this if "result" does not provide enough info.
69203
- if (!result) {
69204
- throw new Error('Duplicated mint');
69205
- }
69206
- },
69207
- // WARNING: this is NOT concurrency safe. Please only call this method one at a time.
69208
- getNextBatchForSubmission: async (limit) => {
69209
- const assets = await client.imAssets.findMany({
69210
- where: {
69211
- mintingStatus: null
69212
- },
69213
- take: limit
69214
- });
69215
- const assetIds = assets.map((asset) => asset.id);
69216
- await client.imAssets.updateMany({
69217
- where: {
69218
- id: {
69219
- in: assetIds
69220
- }
69221
- },
69222
- data: {
69223
- mintingStatus: 'submitting'
69224
- }
69225
- });
69226
- const updatedAssets = await client.imAssets.findMany({
69227
- where: {
69228
- id: {
69229
- in: assetIds
69230
- }
69231
- }
69232
- });
69233
- return updatedAssets.map((asset) => ({
69234
- id: asset.id,
69235
- contract_address: asset.contractAddress,
69236
- wallet_address: asset.ownerAddress,
69237
- asset_id: asset.assetId,
69238
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
69239
- owner_address: asset.ownerAddress,
69240
- tried_count: asset.triedCount,
69241
- }));
69242
- },
69243
- updateMintingStatusToSubmitted: async (ids) => {
69244
- await client.imAssets.updateMany({
69245
- where: {
69246
- id: {
69247
- in: ids
69248
- }
69249
- },
69250
- data: {
69251
- mintingStatus: 'submitted'
69252
- }
69253
- });
69254
- },
69255
- syncMintingStatus: async (submittedMintRequest) => {
69256
- // First, attempt to retrieve the existing asset
69257
- const existingAsset = await client.imAssets.findUnique({
69258
- where: {
69259
- im_assets_uindex: {
69260
- assetId: submittedMintRequest.assetId,
69261
- contractAddress: submittedMintRequest.contractAddress,
69262
- },
69263
- }
69264
- });
69265
- // Check if the asset exists and the condition for updating is met
69266
- if (existingAsset && (existingAsset.lastImtblZkevmMintRequestUpdatedId === null
69267
- || existingAsset.lastImtblZkevmMintRequestUpdatedId < submittedMintRequest.imtblZkevmMintRequestUpdatedId)) {
69268
- // Perform update if the existing record's lastImtblZkevmMintRequestUpdatedId is less than the new one or is null
69269
- await client.imAssets.update({
69270
- where: {
69271
- im_assets_uindex: {
69272
- assetId: submittedMintRequest.assetId,
69273
- contractAddress: submittedMintRequest.contractAddress,
69274
- },
69275
- },
69276
- data: {
69277
- ownerAddress: submittedMintRequest.ownerAddress,
69278
- tokenId: submittedMintRequest.tokenId,
69279
- mintingStatus: submittedMintRequest.status,
69280
- metadataId: submittedMintRequest.metadataId,
69281
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69282
- error: submittedMintRequest.error,
69283
- }
69284
- });
69285
- }
69286
- else if (!existingAsset) {
69287
- // Perform insert if no existing record is found
69288
- await client.imAssets.create({
69289
- data: {
69290
- assetId: submittedMintRequest.assetId,
69291
- contractAddress: submittedMintRequest.contractAddress,
69292
- ownerAddress: submittedMintRequest.ownerAddress,
69293
- tokenId: submittedMintRequest.tokenId,
69294
- mintingStatus: submittedMintRequest.status,
69295
- metadataId: submittedMintRequest.metadataId,
69296
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69297
- error: submittedMintRequest.error,
69298
- }
69299
- });
69300
- }
69301
- // If existing asset does not meet the update condition, do nothing
69302
- },
69303
- updateMintingStatusToSubmissionFailed: async (ids) => {
69304
- await client.imAssets.updateMany({
69305
- where: {
69306
- id: {
69307
- in: ids
69308
- }
69309
- },
69310
- data: {
69311
- mintingStatus: 'submission_failed'
69312
- }
69313
- });
69314
- },
69315
- markAsConflict: async (assetIds, contractAddress) => {
69316
- await client.imAssets.updateMany({
69317
- where: {
69318
- assetId: {
69319
- in: assetIds // Targets assets where assetId is in the provided list
69320
- },
69321
- contractAddress // Additional condition for contract address
69322
- },
69323
- data: {
69324
- mintingStatus: 'conflicting' // Set the new status
69325
- }
69326
- });
69327
- },
69328
- resetMintingStatus: async (ids) => {
69329
- await client.imAssets.updateMany({
69330
- where: {
69331
- id: {
69332
- in: ids // Condition to match ids
69333
- }
69334
- },
69335
- data: {
69336
- mintingStatus: null // Setting minting_status to null
69337
- }
69338
- });
69339
- },
69340
- // this method is not concurrency safe
69341
- markForRetry: async (ids) => {
69342
- // Retrieve the current values of tried_count for the specified ids
69343
- const assets = await client.imAssets.findMany({
69344
- where: {
69345
- id: {
69346
- in: ids
69347
- }
69348
- },
69349
- select: {
69350
- id: true,
69351
- triedCount: true // Assuming the field is named triedCount
69352
- }
69353
- });
69354
- // Update each asset with the new tried_count and nullify minting_status
69355
- for (const asset of assets) {
69356
- await client.imAssets.update({
69357
- where: {
69358
- id: asset.id
69359
- },
69360
- data: {
69361
- mintingStatus: null,
69362
- triedCount: asset.triedCount + 1
69363
- }
69364
- });
69365
- }
69366
- },
69367
- getMintingRequest: async (contractAddress, referenceId) => {
69368
- // Retrieve the asset from the database based on contract_address and asset_id
69369
- const asset = await client.imAssets.findFirst({
69370
- where: {
69371
- contractAddress,
69372
- assetId: referenceId
69373
- }
69374
- });
69375
- if (!asset) {
69376
- return null;
69377
- }
69378
- return {
69379
- asset_id: asset.assetId,
69380
- contract_address: asset.contractAddress,
69381
- id: asset.id,
69382
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
69383
- owner_address: asset.ownerAddress,
69384
- tried_count: asset.triedCount,
69385
- wallet_address: asset.ownerAddress
69386
- };
69387
- }
69388
- });
69389
-
69390
- // TODO: expose metrics
69391
- // - submitting status count, conflicting status count
69392
- // - failed events count
69393
- const recordMint = async (mintingPersistence, mintRequest) => {
69394
- mintingPersistence.recordMint(mintRequest);
69395
- };
69396
- const defaultMintingDelay = 1000;
69397
- // This function can be called in different node process and will run in parallel to mint assets.
69398
- // Each process will NOT mint the same asset.
69399
- // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
69400
- // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
69401
- const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
69402
- let mintingResponse;
69403
- // eslint-disable-next-line no-constant-condition
69404
- while (true) {
69405
- await new Promise((resolve) => {
69406
- setTimeout(resolve, defaultMintingDelay);
69407
- });
69408
- let batchSize = Math.min(mintingResponse?.imx_remaining_mint_requests
69409
- ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
69410
- : defaultBatchSize, defaultBatchSize);
69411
- if (batchSize === 0
69412
- && mintingResponse
69413
- && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
69414
- logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
69415
- continue;
69416
- }
69417
- if (batchSize === 0) {
69418
- logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
69419
- mintingResponse = undefined;
69420
- batchSize = defaultBatchSize;
69421
- }
69422
- // get mints to be submitted
69423
- const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
69424
- if (pendingMints.length === 0) {
69425
- logger.info('no assets to mint');
69426
- continue;
69427
- }
69428
- // chunk assets by every 100 assets. every chunk should all be for the same contract address.
69429
- const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
69430
- if (acc.length === 0) {
69431
- return [{ contractAddress: row.contract_address, assets: [row] }];
69432
- }
69433
- const lastBatch = acc[acc.length - 1];
69434
- if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
69435
- return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
69436
- }
69437
- return [...acc, { contractAddress: row.contract_address, assets: [row] }];
69438
- }, []);
69439
- // submit minting request for each contract address in parallel
69440
- const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
69441
- const mintingRequest = {
69442
- chainName,
69443
- contractAddress,
69444
- createMintRequestRequest: {
69445
- assets: assets.map((row) => ({
69446
- reference_id: row.asset_id,
69447
- owner_address: row.owner_address,
69448
- metadata: row.metadata,
69449
- })),
69450
- },
69451
- };
69452
- try {
69453
- const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
69454
- logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
69455
- // update minting status to submitted
69456
- await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
69457
- return response;
69458
- }
69459
- catch (e) {
69460
- logger.error(e);
69461
- if (e.code === 'CONFLICT_ERROR'
69462
- && e.details?.id === 'reference_id') {
69463
- try {
69464
- // mark the assets as conflicting, so that we don't send them again.
69465
- await mintingPersistence.markAsConflict(e.details.values, contractAddress);
69466
- // remove non conflicting assets status so that they can be retried.
69467
- await mintingPersistence.resetMintingStatus(assets
69468
- .map(({ id }) => id)
69469
- .filter((id) => !e.details.values.includes(id)));
69470
- }
69471
- catch (e2) {
69472
- logger.error(e2);
69473
- }
69474
- }
69475
- else {
69476
- // separate assets into "need to be retied" and "exceeded max number of tries."
69477
- const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
69478
- if (tried_count < maxNumberOfTries) {
69479
- acc.assetsToRetry.push(id);
69480
- }
69481
- else {
69482
- acc.assetsExceededMaxNumberOfTries.push(id);
69483
- }
69484
- return acc;
69485
- }, {
69486
- assetsToRetry: [],
69487
- assetsExceededMaxNumberOfTries: [],
69488
- });
69489
- // remove all assets status so that they can be retried.
69490
- await mintingPersistence.markForRetry(assetsToRetry);
69491
- // mark assets that have exceeded the max number of tries as submission_failed
69492
- await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
69493
- }
69494
- return e;
69495
- }
69496
- }));
69497
- mintingResponse = mintingResults
69498
- .reverse()
69499
- .find((r) => r.status === 'fulfilled')?.value;
69500
- }
69501
- };
69502
- const processMint = async (mintingPersistence, event, logger = console) => {
69503
- if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
69504
- logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
69505
- return;
69506
- }
69507
- const referenceId = event.data.reference_id;
69508
- if (!referenceId) {
69509
- throw new Error('reference_id not found in webhook event');
69510
- }
69511
- const contractAddress = event.data.contract_address;
69512
- if (!contractAddress) {
69513
- throw new Error('contract_address not found in webhook event');
69514
- }
69515
- if (event.data.status === 'failed') {
69516
- logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
69517
- }
69518
- const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
69519
- if (!mintReq) {
69520
- logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
69521
- }
69522
- const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
69523
- if (!ownerAddress) {
69524
- logger.error('owner_address missing');
69525
- throw new Error('owner_address missing');
69526
- }
69527
- await mintingPersistence.syncMintingStatus({
69528
- tokenId: event.data.token_id,
69529
- status: event.data.status,
69530
- assetId: referenceId,
69531
- contractAddress,
69532
- ownerAddress,
69533
- metadataId: event.data.metadata_id,
69534
- imtblZkevmMintRequestUpdatedId: event.event_id,
69535
- error: event.data.error ? JSON.stringify(event.data.error) : null,
69536
- });
69537
- };
69538
-
69539
- var minting_backend = /*#__PURE__*/Object.freeze({
69540
- __proto__: null,
69541
- mintingPersistencePg: mintingPersistence$1,
69542
- mintingPersistencePrismaSqlite: mintingPersistence,
69543
- processMint: processMint,
69544
- recordMint: recordMint,
69545
- submitMintingRequests: submitMintingRequests
69546
- });
69547
-
69548
- export { blockchain_data as blockchainData, checkout, config, minting_backend as mintingBackend, orderbook, passport, webhook, x };
69061
+ export { blockchain_data as blockchainData, checkout, config, orderbook, passport, x };