@imtbl/sdk 1.39.0 → 1.39.1-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -35,6 +35,7 @@ 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');
38
39
 
39
40
  function _interopNamespaceDefault(e) {
40
41
  var n = Object.create(null);
@@ -184,7 +185,7 @@ const flattenProperties$1 = (properties) => {
184
185
  };
185
186
 
186
187
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
187
- const SDK_VERSION$1 = '1.39.0';
188
+ const SDK_VERSION$1 = '1.39.1-alpha';
188
189
  const getFrameParentDomain$1 = () => {
189
190
  if (isNode$1()) {
190
191
  return '';
@@ -14211,7 +14212,7 @@ class MultiRollupApiClients {
14211
14212
  }
14212
14213
 
14213
14214
  // eslint-disable-next-line @typescript-eslint/naming-convention
14214
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.0' };
14215
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha' };
14215
14216
  const createConfig$1 = ({ basePath, headers, }) => {
14216
14217
  if (!basePath.trim()) {
14217
14218
  throw Error('basePath can not be empty');
@@ -14283,7 +14284,7 @@ class APIError extends Error {
14283
14284
 
14284
14285
  /* eslint-disable implicit-arrow-linebreak */
14285
14286
  const defaultHeaders$1 = {
14286
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.0',
14287
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.1-alpha',
14287
14288
  };
14288
14289
  /**
14289
14290
  * createAPIConfiguration to create a custom Configuration
@@ -14757,7 +14758,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
14757
14758
  /* eslint-disable @typescript-eslint/naming-convention */
14758
14759
  class ApiConfiguration extends index$2.Configuration {
14759
14760
  }
14760
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.0' };
14761
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha' };
14761
14762
  /**
14762
14763
  * @dev use createImmutableXConfiguration instead
14763
14764
  */
@@ -14798,7 +14799,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
14798
14799
  coreContractAddress,
14799
14800
  registrationContractAddress,
14800
14801
  registrationV4ContractAddress,
14801
- sdkVersion: 'ts-immutable-sdk-1.39.0',
14802
+ sdkVersion: 'ts-immutable-sdk-1.39.1-alpha',
14802
14803
  baseConfig,
14803
14804
  });
14804
14805
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -26301,12 +26302,12 @@ function assertOptions$1(options, schema, allowUnknown) {
26301
26302
  }
26302
26303
  }
26303
26304
 
26304
- var validator$1 = {
26305
+ var validator$2 = {
26305
26306
  assertOptions: assertOptions$1,
26306
26307
  validators: validators$1$1
26307
26308
  };
26308
26309
 
26309
- const validators$2 = validator$1.validators;
26310
+ const validators$2 = validator$2.validators;
26310
26311
 
26311
26312
  /**
26312
26313
  * Create a new instance of Axios
@@ -26347,7 +26348,7 @@ let Axios$2 = class Axios {
26347
26348
  const {transitional, paramsSerializer, headers} = config;
26348
26349
 
26349
26350
  if (transitional !== undefined) {
26350
- validator$1.assertOptions(transitional, {
26351
+ validator$2.assertOptions(transitional, {
26351
26352
  silentJSONParsing: validators$2.transitional(validators$2.boolean),
26352
26353
  forcedJSONParsing: validators$2.transitional(validators$2.boolean),
26353
26354
  clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
@@ -26360,7 +26361,7 @@ let Axios$2 = class Axios {
26360
26361
  serialize: paramsSerializer
26361
26362
  };
26362
26363
  } else {
26363
- validator$1.assertOptions(paramsSerializer, {
26364
+ validator$2.assertOptions(paramsSerializer, {
26364
26365
  encode: validators$2.function,
26365
26366
  serialize: validators$2.function
26366
26367
  }, true);
@@ -35079,12 +35080,12 @@ function assertOptions(options, schema, allowUnknown) {
35079
35080
  }
35080
35081
  }
35081
35082
 
35082
- var validator = {
35083
+ var validator$1 = {
35083
35084
  assertOptions,
35084
35085
  validators: validators$1
35085
35086
  };
35086
35087
 
35087
- const validators = validator.validators;
35088
+ const validators = validator$1.validators;
35088
35089
 
35089
35090
  /**
35090
35091
  * Create a new instance of Axios
@@ -35125,7 +35126,7 @@ class Axios {
35125
35126
  const {transitional, paramsSerializer, headers} = config;
35126
35127
 
35127
35128
  if (transitional !== undefined) {
35128
- validator.assertOptions(transitional, {
35129
+ validator$1.assertOptions(transitional, {
35129
35130
  silentJSONParsing: validators.transitional(validators.boolean),
35130
35131
  forcedJSONParsing: validators.transitional(validators.boolean),
35131
35132
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -35138,7 +35139,7 @@ class Axios {
35138
35139
  serialize: paramsSerializer
35139
35140
  };
35140
35141
  } else {
35141
- validator.assertOptions(paramsSerializer, {
35142
+ validator$1.assertOptions(paramsSerializer, {
35142
35143
  encode: validators.function,
35143
35144
  serialize: validators.function
35144
35145
  }, true);
@@ -60897,7 +60898,7 @@ const flattenProperties = (properties) => {
60897
60898
  };
60898
60899
 
60899
60900
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
60900
- const SDK_VERSION = '1.39.0';
60901
+ const SDK_VERSION = '1.39.1-alpha';
60901
60902
  const getFrameParentDomain = () => {
60902
60903
  if (isNode()) {
60903
60904
  return '';
@@ -66190,7 +66191,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
66190
66191
  maxPriorityFeePerGas: ethers.BigNumber.from(10e9),
66191
66192
  };
66192
66193
 
66193
- const SDK_VERSION_MARKER = '1.39.0';
66194
+ const SDK_VERSION_MARKER = '1.39.1-alpha';
66194
66195
  // This SDK version is replaced by the `yarn build` command ran on the root level
66195
66196
  const globalPackageVersion = () => SDK_VERSION_MARKER;
66196
66197
 
@@ -71947,9 +71948,605 @@ var x = /*#__PURE__*/Object.freeze({
71947
71948
  starkEcOrder: starkEcOrder
71948
71949
  });
71949
71950
 
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
+
71950
72545
  exports.blockchainData = blockchain_data;
71951
72546
  exports.checkout = checkout;
71952
72547
  exports.config = config;
72548
+ exports.mintingBackend = minting_backend;
71953
72549
  exports.orderbook = orderbook;
71954
72550
  exports.passport = passport;
72551
+ exports.webhook = webhook;
71955
72552
  exports.x = x;