@imtbl/sdk 1.39.1-alpha.1 → 1.39.2

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
@@ -35,7 +35,6 @@ var solidity = require('@ethersproject/solidity');
35
35
  var routerSdk = require('@uniswap/router-sdk');
36
36
  var units = require('@ethersproject/units');
37
37
  var bignumber = require('@ethersproject/bignumber');
38
- var MessageValidator = require('sns-validator');
39
38
 
40
39
  function _interopNamespaceDefault(e) {
41
40
  var n = Object.create(null);
@@ -185,7 +184,7 @@ const flattenProperties$1 = (properties) => {
185
184
  };
186
185
 
187
186
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
188
- const SDK_VERSION$1 = '1.39.1-alpha.1';
187
+ const SDK_VERSION$1 = '1.39.2';
189
188
  const getFrameParentDomain$1 = () => {
190
189
  if (isNode$1()) {
191
190
  return '';
@@ -14212,7 +14211,7 @@ class MultiRollupApiClients {
14212
14211
  }
14213
14212
 
14214
14213
  // eslint-disable-next-line @typescript-eslint/naming-convention
14215
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha.1' };
14214
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.2' };
14216
14215
  const createConfig$1 = ({ basePath, headers, }) => {
14217
14216
  if (!basePath.trim()) {
14218
14217
  throw Error('basePath can not be empty');
@@ -14284,7 +14283,7 @@ class APIError extends Error {
14284
14283
 
14285
14284
  /* eslint-disable implicit-arrow-linebreak */
14286
14285
  const defaultHeaders$1 = {
14287
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.1-alpha.1',
14286
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.2',
14288
14287
  };
14289
14288
  /**
14290
14289
  * createAPIConfiguration to create a custom Configuration
@@ -14758,7 +14757,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
14758
14757
  /* eslint-disable @typescript-eslint/naming-convention */
14759
14758
  class ApiConfiguration extends index$2.Configuration {
14760
14759
  }
14761
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha.1' };
14760
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.2' };
14762
14761
  /**
14763
14762
  * @dev use createImmutableXConfiguration instead
14764
14763
  */
@@ -14799,7 +14798,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
14799
14798
  coreContractAddress,
14800
14799
  registrationContractAddress,
14801
14800
  registrationV4ContractAddress,
14802
- sdkVersion: 'ts-immutable-sdk-1.39.1-alpha.1',
14801
+ sdkVersion: 'ts-immutable-sdk-1.39.2',
14803
14802
  baseConfig,
14804
14803
  });
14805
14804
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -26302,12 +26301,12 @@ function assertOptions$1(options, schema, allowUnknown) {
26302
26301
  }
26303
26302
  }
26304
26303
 
26305
- var validator$2 = {
26304
+ var validator$1 = {
26306
26305
  assertOptions: assertOptions$1,
26307
26306
  validators: validators$1$1
26308
26307
  };
26309
26308
 
26310
- const validators$2 = validator$2.validators;
26309
+ const validators$2 = validator$1.validators;
26311
26310
 
26312
26311
  /**
26313
26312
  * Create a new instance of Axios
@@ -26348,7 +26347,7 @@ let Axios$2 = class Axios {
26348
26347
  const {transitional, paramsSerializer, headers} = config;
26349
26348
 
26350
26349
  if (transitional !== undefined) {
26351
- validator$2.assertOptions(transitional, {
26350
+ validator$1.assertOptions(transitional, {
26352
26351
  silentJSONParsing: validators$2.transitional(validators$2.boolean),
26353
26352
  forcedJSONParsing: validators$2.transitional(validators$2.boolean),
26354
26353
  clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
@@ -26361,7 +26360,7 @@ let Axios$2 = class Axios {
26361
26360
  serialize: paramsSerializer
26362
26361
  };
26363
26362
  } else {
26364
- validator$2.assertOptions(paramsSerializer, {
26363
+ validator$1.assertOptions(paramsSerializer, {
26365
26364
  encode: validators$2.function,
26366
26365
  serialize: validators$2.function
26367
26366
  }, true);
@@ -35080,12 +35079,12 @@ function assertOptions(options, schema, allowUnknown) {
35080
35079
  }
35081
35080
  }
35082
35081
 
35083
- var validator$1 = {
35082
+ var validator = {
35084
35083
  assertOptions,
35085
35084
  validators: validators$1
35086
35085
  };
35087
35086
 
35088
- const validators = validator$1.validators;
35087
+ const validators = validator.validators;
35089
35088
 
35090
35089
  /**
35091
35090
  * Create a new instance of Axios
@@ -35126,7 +35125,7 @@ class Axios {
35126
35125
  const {transitional, paramsSerializer, headers} = config;
35127
35126
 
35128
35127
  if (transitional !== undefined) {
35129
- validator$1.assertOptions(transitional, {
35128
+ validator.assertOptions(transitional, {
35130
35129
  silentJSONParsing: validators.transitional(validators.boolean),
35131
35130
  forcedJSONParsing: validators.transitional(validators.boolean),
35132
35131
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -35139,7 +35138,7 @@ class Axios {
35139
35138
  serialize: paramsSerializer
35140
35139
  };
35141
35140
  } else {
35142
- validator$1.assertOptions(paramsSerializer, {
35141
+ validator.assertOptions(paramsSerializer, {
35143
35142
  encode: validators.function,
35144
35143
  serialize: validators.function
35145
35144
  }, true);
@@ -60898,7 +60897,7 @@ const flattenProperties = (properties) => {
60898
60897
  };
60899
60898
 
60900
60899
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
60901
- const SDK_VERSION = '1.39.1-alpha.1';
60900
+ const SDK_VERSION = '1.39.2';
60902
60901
  const getFrameParentDomain = () => {
60903
60902
  if (isNode()) {
60904
60903
  return '';
@@ -66191,7 +66190,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
66191
66190
  maxPriorityFeePerGas: ethers.BigNumber.from(10e9),
66192
66191
  };
66193
66192
 
66194
- const SDK_VERSION_MARKER = '1.39.1-alpha.1';
66193
+ const SDK_VERSION_MARKER = '1.39.2';
66195
66194
  // This SDK version is replaced by the `yarn build` command ran on the root level
66196
66195
  const globalPackageVersion = () => SDK_VERSION_MARKER;
66197
66196
 
@@ -71948,605 +71947,9 @@ var x = /*#__PURE__*/Object.freeze({
71948
71947
  starkEcOrder: starkEcOrder
71949
71948
  });
71950
71949
 
71951
- const validator = new MessageValidator();
71952
- const allowedTopicArnPrefix = {
71953
- [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
71954
- [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
71955
- };
71956
- const init = async (body, env, handlers) => {
71957
- const msg = await new Promise((resolve, reject) => {
71958
- validator.validate(body, (err, message) => {
71959
- if (err) {
71960
- return reject(err);
71961
- }
71962
- // check for topic arn prefix
71963
- if (!message.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
71964
- throw new Error('Invalid topic arn');
71965
- }
71966
- if (message?.Type === 'SubscriptionConfirmation') {
71967
- fetch(message.SubscribeURL).then(() => {
71968
- resolve(message);
71969
- }).catch((e) => {
71970
- reject(e);
71971
- });
71972
- }
71973
- return resolve(message);
71974
- });
71975
- });
71976
- if (msg.Type === 'Notification') {
71977
- const event = JSON.parse(msg.Message);
71978
- switch (event.event_name) {
71979
- case 'imtbl_zkevm_mint_request_updated':
71980
- await handlers.zkevmMintRequestUpdated(event);
71981
- break;
71982
- default:
71983
- if (handlers.others) {
71984
- await handlers.others(event);
71985
- }
71986
- break;
71987
- }
71988
- }
71989
- };
71990
-
71991
- var webhook = /*#__PURE__*/Object.freeze({
71992
- __proto__: null,
71993
- init: init
71994
- });
71995
-
71996
- const moduleName = 'minting_backend_sdk';
71997
- const trackInitializePersistencePG = () => {
71998
- try {
71999
- track(moduleName, 'initializePersistencePG');
72000
- }
72001
- catch {
72002
- // ignore
72003
- }
72004
- };
72005
- const trackInitializePersistencePrismaSqlite = () => {
72006
- try {
72007
- track(moduleName, 'initializePersistencePrismaSqlite');
72008
- }
72009
- catch {
72010
- // ignore
72011
- }
72012
- };
72013
- const trackSubmitMintingRequests = () => {
72014
- try {
72015
- track(moduleName, 'submitMintingRequests');
72016
- }
72017
- catch {
72018
- // ignore
72019
- }
72020
- };
72021
- const trackProcessMint = () => {
72022
- try {
72023
- track(moduleName, 'processMint');
72024
- }
72025
- catch {
72026
- // ignore
72027
- }
72028
- };
72029
- const trackRecordMint = () => {
72030
- try {
72031
- track(moduleName, 'recordMint');
72032
- }
72033
- catch {
72034
- // ignore
72035
- }
72036
- };
72037
-
72038
- const mintingPersistence$1 = (client) => {
72039
- trackInitializePersistencePG();
72040
- return {
72041
- recordMint: async (request) => {
72042
- const r = await client.query(`
72043
- INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata)
72044
- VALUES ($1, $2, $3, $4) ON CONFLICT (asset_id, contract_address) DO NOTHING;
72045
- `, [request.asset_id, request.contract_address, request.owner_address, request.metadata]);
72046
- if (r.rowCount === 0) {
72047
- throw new Error('Duplicated mint');
72048
- }
72049
- },
72050
- getNextBatchForSubmission: async (limit) => {
72051
- const res = await client.query(`
72052
- UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
72053
- select id from im_assets where minting_status is null limit $1 for update skip locked
72054
- ) returning *;
72055
- `, [limit]);
72056
- return res.rows;
72057
- },
72058
- updateMintingStatusToSubmitted: async (ids) => {
72059
- await client.query(`
72060
- UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
72061
- `, [ids, 'submitted']);
72062
- },
72063
- syncMintingStatus: async (submittedMintRequest) => {
72064
- // doing a upsert just in case the row has not been created yet
72065
- await client.query(`
72066
- INSERT INTO im_assets (
72067
- asset_id,
72068
- contract_address,
72069
- owner_address,
72070
- token_id,
72071
- minting_status,
72072
- metadata_id,
72073
- last_imtbl_zkevm_mint_request_updated_id,
72074
- error
72075
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (asset_id, contract_address)
72076
- DO UPDATE SET
72077
- owner_address = $3,
72078
- token_id = $4,
72079
- minting_status = $5,
72080
- metadata_id = $6,
72081
- last_imtbl_zkevm_mint_request_updated_id = $7,
72082
- error = $8
72083
- where (
72084
- im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
72085
- im_assets.last_imtbl_zkevm_mint_request_updated_id is null
72086
- );
72087
- `, [
72088
- submittedMintRequest.assetId,
72089
- submittedMintRequest.contractAddress,
72090
- submittedMintRequest.ownerAddress,
72091
- submittedMintRequest.tokenId,
72092
- submittedMintRequest.status,
72093
- submittedMintRequest.metadataId,
72094
- submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72095
- submittedMintRequest.error
72096
- ]);
72097
- },
72098
- markAsConflict: async (assetIds, contractAddress) => {
72099
- await client.query(`
72100
- UPDATE im_assets
72101
- SET minting_status = 'conflicting'
72102
- WHERE asset_id = ANY($1)
72103
- AND contract_address = $2;
72104
- `, [assetIds, contractAddress]);
72105
- },
72106
- resetMintingStatus: async (ids) => {
72107
- await client.query(`
72108
- UPDATE im_assets SET minting_status = null WHERE id = ANY($1);
72109
- `, [ids]);
72110
- },
72111
- markForRetry: async (ids) => {
72112
- await client.query(`
72113
- UPDATE im_assets
72114
- SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
72115
- `, [ids]);
72116
- },
72117
- updateMintingStatusToSubmissionFailed: async (ids) => {
72118
- await client.query(`
72119
- UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
72120
- `, [ids]);
72121
- },
72122
- getMintingRequest: async (contractAddress, referenceId) => {
72123
- const res = await client.query(`
72124
- SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
72125
- `, [contractAddress, referenceId]);
72126
- return res.rows[0] || null;
72127
- }
72128
- };
72129
- };
72130
-
72131
- /* eslint-disable no-await-in-loop */
72132
- /* eslint-disable @typescript-eslint/naming-convention */
72133
- // client is a PrismaClient instance. it needs to be generated with
72134
- // additional schema defined inside (TODO: point to repo) file.
72135
- const mintingPersistence = (client) => {
72136
- trackInitializePersistencePrismaSqlite();
72137
- return {
72138
- recordMint: async (request) => {
72139
- const result = await client.imAssets.upsert({
72140
- where: {
72141
- im_assets_uindex: {
72142
- assetId: request.asset_id, contractAddress: request.contract_address
72143
- }
72144
- },
72145
- update: {},
72146
- create: {
72147
- assetId: request.asset_id,
72148
- contractAddress: request.contract_address,
72149
- ownerAddress: request.owner_address,
72150
- metadata: JSON.stringify(request.metadata), // Serialize JSON metadata
72151
- },
72152
- });
72153
- // Since upsert does not throw on update and does not tell directly if it updated or inserted,
72154
- // we need to add additional logic to handle this if "result" does not provide enough info.
72155
- if (!result) {
72156
- throw new Error('Duplicated mint');
72157
- }
72158
- },
72159
- // WARNING: this is NOT concurrency safe. Please only call this method one at a time.
72160
- getNextBatchForSubmission: async (limit) => {
72161
- const assets = await client.imAssets.findMany({
72162
- where: {
72163
- mintingStatus: null
72164
- },
72165
- take: limit
72166
- });
72167
- const assetIds = assets.map((asset) => asset.id);
72168
- await client.imAssets.updateMany({
72169
- where: {
72170
- id: {
72171
- in: assetIds
72172
- }
72173
- },
72174
- data: {
72175
- mintingStatus: 'submitting'
72176
- }
72177
- });
72178
- const updatedAssets = await client.imAssets.findMany({
72179
- where: {
72180
- id: {
72181
- in: assetIds
72182
- }
72183
- }
72184
- });
72185
- return updatedAssets.map((asset) => ({
72186
- id: asset.id,
72187
- contract_address: asset.contractAddress,
72188
- wallet_address: asset.ownerAddress,
72189
- asset_id: asset.assetId,
72190
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72191
- owner_address: asset.ownerAddress,
72192
- tried_count: asset.triedCount,
72193
- }));
72194
- },
72195
- updateMintingStatusToSubmitted: async (ids) => {
72196
- await client.imAssets.updateMany({
72197
- where: {
72198
- id: {
72199
- in: ids
72200
- }
72201
- },
72202
- data: {
72203
- mintingStatus: 'submitted'
72204
- }
72205
- });
72206
- },
72207
- syncMintingStatus: async (submittedMintRequest) => {
72208
- // First, attempt to retrieve the existing asset
72209
- const existingAsset = await client.imAssets.findUnique({
72210
- where: {
72211
- im_assets_uindex: {
72212
- assetId: submittedMintRequest.assetId,
72213
- contractAddress: submittedMintRequest.contractAddress,
72214
- },
72215
- }
72216
- });
72217
- // Check if the asset exists and the condition for updating is met
72218
- if (existingAsset && (existingAsset.lastImtblZkevmMintRequestUpdatedId === null
72219
- || existingAsset.lastImtblZkevmMintRequestUpdatedId < submittedMintRequest.imtblZkevmMintRequestUpdatedId)) {
72220
- // Perform update if the existing record's lastImtblZkevmMintRequestUpdatedId is less than the new one or is null
72221
- await client.imAssets.update({
72222
- where: {
72223
- im_assets_uindex: {
72224
- assetId: submittedMintRequest.assetId,
72225
- contractAddress: submittedMintRequest.contractAddress,
72226
- },
72227
- },
72228
- data: {
72229
- ownerAddress: submittedMintRequest.ownerAddress,
72230
- tokenId: submittedMintRequest.tokenId,
72231
- mintingStatus: submittedMintRequest.status,
72232
- metadataId: submittedMintRequest.metadataId,
72233
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72234
- error: submittedMintRequest.error,
72235
- }
72236
- });
72237
- }
72238
- else if (!existingAsset) {
72239
- // Perform insert if no existing record is found
72240
- await client.imAssets.create({
72241
- data: {
72242
- assetId: submittedMintRequest.assetId,
72243
- contractAddress: submittedMintRequest.contractAddress,
72244
- ownerAddress: submittedMintRequest.ownerAddress,
72245
- tokenId: submittedMintRequest.tokenId,
72246
- mintingStatus: submittedMintRequest.status,
72247
- metadataId: submittedMintRequest.metadataId,
72248
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72249
- error: submittedMintRequest.error,
72250
- }
72251
- });
72252
- }
72253
- // If existing asset does not meet the update condition, do nothing
72254
- },
72255
- updateMintingStatusToSubmissionFailed: async (ids) => {
72256
- await client.imAssets.updateMany({
72257
- where: {
72258
- id: {
72259
- in: ids
72260
- }
72261
- },
72262
- data: {
72263
- mintingStatus: 'submission_failed'
72264
- }
72265
- });
72266
- },
72267
- markAsConflict: async (assetIds, contractAddress) => {
72268
- await client.imAssets.updateMany({
72269
- where: {
72270
- assetId: {
72271
- in: assetIds // Targets assets where assetId is in the provided list
72272
- },
72273
- contractAddress // Additional condition for contract address
72274
- },
72275
- data: {
72276
- mintingStatus: 'conflicting' // Set the new status
72277
- }
72278
- });
72279
- },
72280
- resetMintingStatus: async (ids) => {
72281
- await client.imAssets.updateMany({
72282
- where: {
72283
- id: {
72284
- in: ids // Condition to match ids
72285
- }
72286
- },
72287
- data: {
72288
- mintingStatus: null // Setting minting_status to null
72289
- }
72290
- });
72291
- },
72292
- // this method is not concurrency safe
72293
- markForRetry: async (ids) => {
72294
- // Retrieve the current values of tried_count for the specified ids
72295
- const assets = await client.imAssets.findMany({
72296
- where: {
72297
- id: {
72298
- in: ids
72299
- }
72300
- },
72301
- select: {
72302
- id: true,
72303
- triedCount: true // Assuming the field is named triedCount
72304
- }
72305
- });
72306
- // Update each asset with the new tried_count and nullify minting_status
72307
- for (const asset of assets) {
72308
- await client.imAssets.update({
72309
- where: {
72310
- id: asset.id
72311
- },
72312
- data: {
72313
- mintingStatus: null,
72314
- triedCount: asset.triedCount + 1
72315
- }
72316
- });
72317
- }
72318
- },
72319
- getMintingRequest: async (contractAddress, referenceId) => {
72320
- // Retrieve the asset from the database based on contract_address and asset_id
72321
- const asset = await client.imAssets.findFirst({
72322
- where: {
72323
- contractAddress,
72324
- assetId: referenceId
72325
- }
72326
- });
72327
- if (!asset) {
72328
- return null;
72329
- }
72330
- return {
72331
- asset_id: asset.assetId,
72332
- contract_address: asset.contractAddress,
72333
- id: asset.id,
72334
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72335
- owner_address: asset.ownerAddress,
72336
- tried_count: asset.triedCount,
72337
- wallet_address: asset.ownerAddress
72338
- };
72339
- }
72340
- };
72341
- };
72342
-
72343
- // TODO: expose metrics
72344
- // - submitting status count, conflicting status count
72345
- // - failed events count
72346
- const recordMint = async (mintingPersistence, mintRequest) => {
72347
- trackRecordMint();
72348
- mintingPersistence.recordMint(mintRequest);
72349
- };
72350
- const defaultMintingDelay = 1000;
72351
- // This function can be called in different node process and will run in parallel to mint assets.
72352
- // Each process will NOT mint the same asset.
72353
- // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
72354
- // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
72355
- const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
72356
- trackSubmitMintingRequests();
72357
- let mintingResponse;
72358
- // eslint-disable-next-line no-constant-condition
72359
- while (true) {
72360
- await new Promise((resolve) => {
72361
- setTimeout(resolve, defaultMintingDelay);
72362
- });
72363
- let batchSize = Math.min(mintingResponse?.imx_remaining_mint_requests
72364
- ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
72365
- : defaultBatchSize, defaultBatchSize);
72366
- if (batchSize === 0
72367
- && mintingResponse
72368
- && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
72369
- logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
72370
- continue;
72371
- }
72372
- if (batchSize === 0) {
72373
- logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
72374
- mintingResponse = undefined;
72375
- batchSize = defaultBatchSize;
72376
- }
72377
- // get mints to be submitted
72378
- const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
72379
- if (pendingMints.length === 0) {
72380
- logger.info('no assets to mint');
72381
- continue;
72382
- }
72383
- // chunk assets by every 100 assets. every chunk should all be for the same contract address.
72384
- const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
72385
- if (acc.length === 0) {
72386
- return [{ contractAddress: row.contract_address, assets: [row] }];
72387
- }
72388
- const lastBatch = acc[acc.length - 1];
72389
- if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
72390
- return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
72391
- }
72392
- return [...acc, { contractAddress: row.contract_address, assets: [row] }];
72393
- }, []);
72394
- // submit minting request for each contract address in parallel
72395
- const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
72396
- const mintingRequest = {
72397
- chainName,
72398
- contractAddress,
72399
- createMintRequestRequest: {
72400
- assets: assets.map((row) => ({
72401
- reference_id: row.asset_id,
72402
- owner_address: row.owner_address,
72403
- metadata: row.metadata,
72404
- })),
72405
- },
72406
- };
72407
- try {
72408
- const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
72409
- logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
72410
- // update minting status to submitted
72411
- await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
72412
- return response;
72413
- }
72414
- catch (e) {
72415
- logger.error(e);
72416
- if (e.code === 'CONFLICT_ERROR'
72417
- && e.details?.id === 'reference_id') {
72418
- try {
72419
- // mark the assets as conflicting, so that we don't send them again.
72420
- await mintingPersistence.markAsConflict(e.details.values, contractAddress);
72421
- // remove non conflicting assets status so that they can be retried.
72422
- await mintingPersistence.resetMintingStatus(assets
72423
- .map(({ id }) => id)
72424
- .filter((id) => !e.details.values.includes(id)));
72425
- }
72426
- catch (e2) {
72427
- logger.error(e2);
72428
- }
72429
- }
72430
- else {
72431
- // separate assets into "need to be retied" and "exceeded max number of tries."
72432
- const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
72433
- if (tried_count < maxNumberOfTries) {
72434
- acc.assetsToRetry.push(id);
72435
- }
72436
- else {
72437
- acc.assetsExceededMaxNumberOfTries.push(id);
72438
- }
72439
- return acc;
72440
- }, {
72441
- assetsToRetry: [],
72442
- assetsExceededMaxNumberOfTries: [],
72443
- });
72444
- // remove all assets status so that they can be retried.
72445
- await mintingPersistence.markForRetry(assetsToRetry);
72446
- // mark assets that have exceeded the max number of tries as submission_failed
72447
- await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
72448
- }
72449
- return e;
72450
- }
72451
- }));
72452
- mintingResponse = mintingResults
72453
- .reverse()
72454
- .find((r) => r.status === 'fulfilled')?.value;
72455
- }
72456
- };
72457
- const processMint = async (mintingPersistence, event, logger = console) => {
72458
- trackProcessMint();
72459
- if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
72460
- logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
72461
- return;
72462
- }
72463
- const referenceId = event.data.reference_id;
72464
- if (!referenceId) {
72465
- throw new Error('reference_id not found in webhook event');
72466
- }
72467
- const contractAddress = event.data.contract_address;
72468
- if (!contractAddress) {
72469
- throw new Error('contract_address not found in webhook event');
72470
- }
72471
- if (event.data.status === 'failed') {
72472
- logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
72473
- }
72474
- const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
72475
- if (!mintReq) {
72476
- logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
72477
- }
72478
- const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
72479
- if (!ownerAddress) {
72480
- logger.error('owner_address missing');
72481
- throw new Error('owner_address missing');
72482
- }
72483
- await mintingPersistence.syncMintingStatus({
72484
- tokenId: event.data.token_id,
72485
- status: event.data.status,
72486
- assetId: referenceId,
72487
- contractAddress,
72488
- ownerAddress,
72489
- metadataId: event.data.metadata_id,
72490
- imtblZkevmMintRequestUpdatedId: event.event_id,
72491
- error: event.data.error ? JSON.stringify(event.data.error) : null,
72492
- });
72493
- };
72494
-
72495
- const noopHandlers = {
72496
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
72497
- zkevmMintRequestUpdated: async (event) => { },
72498
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
72499
- others: async (..._args) => { }
72500
- };
72501
- class MintingBackendModule {
72502
- baseConfig;
72503
- persistence;
72504
- blockchainDataClient;
72505
- logger;
72506
- constructor(config) {
72507
- this.baseConfig = config.baseConfig;
72508
- this.persistence = config.persistence;
72509
- this.logger = config.logger || console;
72510
- this.blockchainDataClient = new BlockchainData({
72511
- baseConfig: config.baseConfig
72512
- });
72513
- setEnvironment(this.baseConfig.environment);
72514
- if (this.baseConfig.publishableKey) {
72515
- setPublishableApiKey(this.baseConfig.publishableKey);
72516
- }
72517
- }
72518
- async recordMint(mintRequest) {
72519
- await recordMint(this.persistence, mintRequest);
72520
- }
72521
- async submitMintingRequests(config) {
72522
- await submitMintingRequests(this.persistence, this.blockchainDataClient, config);
72523
- }
72524
- async processMint(body, otherHandlers = noopHandlers) {
72525
- await init(body, this.baseConfig.environment, {
72526
- zkevmMintRequestUpdated: async (event) => {
72527
- await processMint(this.persistence, event, this.logger);
72528
- otherHandlers.zkevmMintRequestUpdated(event);
72529
- },
72530
- others: otherHandlers.others
72531
- });
72532
- }
72533
- }
72534
-
72535
- var minting_backend = /*#__PURE__*/Object.freeze({
72536
- __proto__: null,
72537
- MintingBackendModule: MintingBackendModule,
72538
- mintingPersistencePg: mintingPersistence$1,
72539
- mintingPersistencePrismaSqlite: mintingPersistence,
72540
- processMint: processMint,
72541
- recordMint: recordMint,
72542
- submitMintingRequests: submitMintingRequests
72543
- });
72544
-
72545
71950
  exports.blockchainData = blockchain_data;
72546
71951
  exports.checkout = checkout;
72547
71952
  exports.config = config;
72548
- exports.mintingBackend = minting_backend;
72549
71953
  exports.orderbook = orderbook;
72550
71954
  exports.passport = passport;
72551
- exports.webhook = webhook;
72552
71955
  exports.x = x;