@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.js CHANGED
@@ -34,6 +34,7 @@ import { keccak256 as keccak256$3 } from '@ethersproject/solidity';
34
34
  import { SwapRouter, PaymentsExtended } from '@uniswap/router-sdk';
35
35
  import { parseUnits as parseUnits$1 } from '@ethersproject/units';
36
36
  import { BigNumber as BigNumber$2 } from '@ethersproject/bignumber';
37
+ import MessageValidator from 'sns-validator';
37
38
 
38
39
  const isNode$1 = () => typeof window === 'undefined';
39
40
  const isBrowser$1 = () => !isNode$1();
@@ -161,7 +162,7 @@ const flattenProperties$1 = (properties) => {
161
162
  };
162
163
 
163
164
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
164
- const SDK_VERSION$1 = '1.39.0';
165
+ const SDK_VERSION$1 = '1.39.1-alpha';
165
166
  const getFrameParentDomain$1 = () => {
166
167
  if (isNode$1()) {
167
168
  return '';
@@ -14188,7 +14189,7 @@ class MultiRollupApiClients {
14188
14189
  }
14189
14190
 
14190
14191
  // eslint-disable-next-line @typescript-eslint/naming-convention
14191
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.0' };
14192
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha' };
14192
14193
  const createConfig$1 = ({ basePath, headers, }) => {
14193
14194
  if (!basePath.trim()) {
14194
14195
  throw Error('basePath can not be empty');
@@ -14260,7 +14261,7 @@ class APIError extends Error {
14260
14261
 
14261
14262
  /* eslint-disable implicit-arrow-linebreak */
14262
14263
  const defaultHeaders$1 = {
14263
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.0',
14264
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.39.1-alpha',
14264
14265
  };
14265
14266
  /**
14266
14267
  * createAPIConfiguration to create a custom Configuration
@@ -14734,7 +14735,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
14734
14735
  /* eslint-disable @typescript-eslint/naming-convention */
14735
14736
  class ApiConfiguration extends index$2.Configuration {
14736
14737
  }
14737
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.0' };
14738
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.39.1-alpha' };
14738
14739
  /**
14739
14740
  * @dev use createImmutableXConfiguration instead
14740
14741
  */
@@ -14775,7 +14776,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
14775
14776
  coreContractAddress,
14776
14777
  registrationContractAddress,
14777
14778
  registrationV4ContractAddress,
14778
- sdkVersion: 'ts-immutable-sdk-1.39.0',
14779
+ sdkVersion: 'ts-immutable-sdk-1.39.1-alpha',
14779
14780
  baseConfig,
14780
14781
  });
14781
14782
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -26278,12 +26279,12 @@ function assertOptions$1(options, schema, allowUnknown) {
26278
26279
  }
26279
26280
  }
26280
26281
 
26281
- var validator$1 = {
26282
+ var validator$2 = {
26282
26283
  assertOptions: assertOptions$1,
26283
26284
  validators: validators$1$1
26284
26285
  };
26285
26286
 
26286
- const validators$2 = validator$1.validators;
26287
+ const validators$2 = validator$2.validators;
26287
26288
 
26288
26289
  /**
26289
26290
  * Create a new instance of Axios
@@ -26324,7 +26325,7 @@ let Axios$2 = class Axios {
26324
26325
  const {transitional, paramsSerializer, headers} = config;
26325
26326
 
26326
26327
  if (transitional !== undefined) {
26327
- validator$1.assertOptions(transitional, {
26328
+ validator$2.assertOptions(transitional, {
26328
26329
  silentJSONParsing: validators$2.transitional(validators$2.boolean),
26329
26330
  forcedJSONParsing: validators$2.transitional(validators$2.boolean),
26330
26331
  clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
@@ -26337,7 +26338,7 @@ let Axios$2 = class Axios {
26337
26338
  serialize: paramsSerializer
26338
26339
  };
26339
26340
  } else {
26340
- validator$1.assertOptions(paramsSerializer, {
26341
+ validator$2.assertOptions(paramsSerializer, {
26341
26342
  encode: validators$2.function,
26342
26343
  serialize: validators$2.function
26343
26344
  }, true);
@@ -35056,12 +35057,12 @@ function assertOptions(options, schema, allowUnknown) {
35056
35057
  }
35057
35058
  }
35058
35059
 
35059
- var validator = {
35060
+ var validator$1 = {
35060
35061
  assertOptions,
35061
35062
  validators: validators$1
35062
35063
  };
35063
35064
 
35064
- const validators = validator.validators;
35065
+ const validators = validator$1.validators;
35065
35066
 
35066
35067
  /**
35067
35068
  * Create a new instance of Axios
@@ -35102,7 +35103,7 @@ class Axios {
35102
35103
  const {transitional, paramsSerializer, headers} = config;
35103
35104
 
35104
35105
  if (transitional !== undefined) {
35105
- validator.assertOptions(transitional, {
35106
+ validator$1.assertOptions(transitional, {
35106
35107
  silentJSONParsing: validators.transitional(validators.boolean),
35107
35108
  forcedJSONParsing: validators.transitional(validators.boolean),
35108
35109
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -35115,7 +35116,7 @@ class Axios {
35115
35116
  serialize: paramsSerializer
35116
35117
  };
35117
35118
  } else {
35118
- validator.assertOptions(paramsSerializer, {
35119
+ validator$1.assertOptions(paramsSerializer, {
35119
35120
  encode: validators.function,
35120
35121
  serialize: validators.function
35121
35122
  }, true);
@@ -60874,7 +60875,7 @@ const flattenProperties = (properties) => {
60874
60875
  };
60875
60876
 
60876
60877
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
60877
- const SDK_VERSION = '1.39.0';
60878
+ const SDK_VERSION = '1.39.1-alpha';
60878
60879
  const getFrameParentDomain = () => {
60879
60880
  if (isNode()) {
60880
60881
  return '';
@@ -66167,7 +66168,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
66167
66168
  maxPriorityFeePerGas: BigNumber$1.from(10e9),
66168
66169
  };
66169
66170
 
66170
- const SDK_VERSION_MARKER = '1.39.0';
66171
+ const SDK_VERSION_MARKER = '1.39.1-alpha';
66171
66172
  // This SDK version is replaced by the `yarn build` command ran on the root level
66172
66173
  const globalPackageVersion = () => SDK_VERSION_MARKER;
66173
66174
 
@@ -71924,4 +71925,598 @@ var x = /*#__PURE__*/Object.freeze({
71924
71925
  starkEcOrder: starkEcOrder
71925
71926
  });
71926
71927
 
71927
- export { blockchain_data as blockchainData, checkout, config, orderbook, passport, x };
71928
+ const validator = new MessageValidator();
71929
+ const allowedTopicArnPrefix = {
71930
+ [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
71931
+ [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
71932
+ };
71933
+ const init = async (body, env, handlers) => {
71934
+ const msg = await new Promise((resolve, reject) => {
71935
+ validator.validate(body, (err, message) => {
71936
+ if (err) {
71937
+ return reject(err);
71938
+ }
71939
+ // check for topic arn prefix
71940
+ if (!message.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
71941
+ throw new Error('Invalid topic arn');
71942
+ }
71943
+ if (message?.Type === 'SubscriptionConfirmation') {
71944
+ fetch(message.SubscribeURL).then(() => {
71945
+ resolve(message);
71946
+ }).catch((e) => {
71947
+ reject(e);
71948
+ });
71949
+ }
71950
+ return resolve(message);
71951
+ });
71952
+ });
71953
+ if (msg.Type === 'Notification') {
71954
+ const event = JSON.parse(msg.Message);
71955
+ switch (event.event_name) {
71956
+ case 'imtbl_zkevm_mint_request_updated':
71957
+ await handlers.zkevmMintRequestUpdated(event);
71958
+ break;
71959
+ default:
71960
+ if (handlers.others) {
71961
+ await handlers.others(event);
71962
+ }
71963
+ break;
71964
+ }
71965
+ }
71966
+ };
71967
+
71968
+ var webhook = /*#__PURE__*/Object.freeze({
71969
+ __proto__: null,
71970
+ init: init
71971
+ });
71972
+
71973
+ const moduleName = 'minting_backend_sdk';
71974
+ const trackInitializePersistencePG = () => {
71975
+ try {
71976
+ track(moduleName, 'initializePersistencePG');
71977
+ }
71978
+ catch {
71979
+ // ignore
71980
+ }
71981
+ };
71982
+ const trackInitializePersistencePrismaSqlite = () => {
71983
+ try {
71984
+ track(moduleName, 'initializePersistencePrismaSqlite');
71985
+ }
71986
+ catch {
71987
+ // ignore
71988
+ }
71989
+ };
71990
+ const trackSubmitMintingRequests = () => {
71991
+ try {
71992
+ track(moduleName, 'submitMintingRequests');
71993
+ }
71994
+ catch {
71995
+ // ignore
71996
+ }
71997
+ };
71998
+ const trackProcessMint = () => {
71999
+ try {
72000
+ track(moduleName, 'processMint');
72001
+ }
72002
+ catch {
72003
+ // ignore
72004
+ }
72005
+ };
72006
+ const trackRecordMint = () => {
72007
+ try {
72008
+ track(moduleName, 'recordMint');
72009
+ }
72010
+ catch {
72011
+ // ignore
72012
+ }
72013
+ };
72014
+
72015
+ const mintingPersistence$1 = (client) => {
72016
+ trackInitializePersistencePG();
72017
+ return {
72018
+ recordMint: async (request) => {
72019
+ const r = await client.query(`
72020
+ INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata)
72021
+ VALUES ($1, $2, $3, $4) ON CONFLICT (asset_id, contract_address) DO NOTHING;
72022
+ `, [request.asset_id, request.contract_address, request.owner_address, request.metadata]);
72023
+ if (r.rowCount === 0) {
72024
+ throw new Error('Duplicated mint');
72025
+ }
72026
+ },
72027
+ getNextBatchForSubmission: async (limit) => {
72028
+ const res = await client.query(`
72029
+ UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
72030
+ select id from im_assets where minting_status is null limit $1 for update skip locked
72031
+ ) returning *;
72032
+ `, [limit]);
72033
+ return res.rows;
72034
+ },
72035
+ updateMintingStatusToSubmitted: async (ids) => {
72036
+ await client.query(`
72037
+ UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
72038
+ `, [ids, 'submitted']);
72039
+ },
72040
+ syncMintingStatus: async (submittedMintRequest) => {
72041
+ // doing a upsert just in case the row has not been created yet
72042
+ await client.query(`
72043
+ INSERT INTO im_assets (
72044
+ asset_id,
72045
+ contract_address,
72046
+ owner_address,
72047
+ token_id,
72048
+ minting_status,
72049
+ metadata_id,
72050
+ last_imtbl_zkevm_mint_request_updated_id,
72051
+ error
72052
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (asset_id, contract_address)
72053
+ DO UPDATE SET
72054
+ owner_address = $3,
72055
+ token_id = $4,
72056
+ minting_status = $5,
72057
+ metadata_id = $6,
72058
+ last_imtbl_zkevm_mint_request_updated_id = $7,
72059
+ error = $8
72060
+ where (
72061
+ im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
72062
+ im_assets.last_imtbl_zkevm_mint_request_updated_id is null
72063
+ );
72064
+ `, [
72065
+ submittedMintRequest.assetId,
72066
+ submittedMintRequest.contractAddress,
72067
+ submittedMintRequest.ownerAddress,
72068
+ submittedMintRequest.tokenId,
72069
+ submittedMintRequest.status,
72070
+ submittedMintRequest.metadataId,
72071
+ submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72072
+ submittedMintRequest.error
72073
+ ]);
72074
+ },
72075
+ markAsConflict: async (assetIds, contractAddress) => {
72076
+ await client.query(`
72077
+ UPDATE im_assets
72078
+ SET minting_status = 'conflicting'
72079
+ WHERE asset_id = ANY($1)
72080
+ AND contract_address = $2;
72081
+ `, [assetIds, contractAddress]);
72082
+ },
72083
+ resetMintingStatus: async (ids) => {
72084
+ await client.query(`
72085
+ UPDATE im_assets SET minting_status = null WHERE id = ANY($1);
72086
+ `, [ids]);
72087
+ },
72088
+ markForRetry: async (ids) => {
72089
+ await client.query(`
72090
+ UPDATE im_assets
72091
+ SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
72092
+ `, [ids]);
72093
+ },
72094
+ updateMintingStatusToSubmissionFailed: async (ids) => {
72095
+ await client.query(`
72096
+ UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
72097
+ `, [ids]);
72098
+ },
72099
+ getMintingRequest: async (contractAddress, referenceId) => {
72100
+ const res = await client.query(`
72101
+ SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
72102
+ `, [contractAddress, referenceId]);
72103
+ return res.rows[0] || null;
72104
+ }
72105
+ };
72106
+ };
72107
+
72108
+ /* eslint-disable no-await-in-loop */
72109
+ /* eslint-disable @typescript-eslint/naming-convention */
72110
+ // client is a PrismaClient instance. it needs to be generated with
72111
+ // additional schema defined inside (TODO: point to repo) file.
72112
+ const mintingPersistence = (client) => {
72113
+ trackInitializePersistencePrismaSqlite();
72114
+ return {
72115
+ recordMint: async (request) => {
72116
+ const result = await client.imAssets.upsert({
72117
+ where: {
72118
+ im_assets_uindex: {
72119
+ assetId: request.asset_id, contractAddress: request.contract_address
72120
+ }
72121
+ },
72122
+ update: {},
72123
+ create: {
72124
+ assetId: request.asset_id,
72125
+ contractAddress: request.contract_address,
72126
+ ownerAddress: request.owner_address,
72127
+ metadata: JSON.stringify(request.metadata), // Serialize JSON metadata
72128
+ },
72129
+ });
72130
+ // Since upsert does not throw on update and does not tell directly if it updated or inserted,
72131
+ // we need to add additional logic to handle this if "result" does not provide enough info.
72132
+ if (!result) {
72133
+ throw new Error('Duplicated mint');
72134
+ }
72135
+ },
72136
+ // WARNING: this is NOT concurrency safe. Please only call this method one at a time.
72137
+ getNextBatchForSubmission: async (limit) => {
72138
+ const assets = await client.imAssets.findMany({
72139
+ where: {
72140
+ mintingStatus: null
72141
+ },
72142
+ take: limit
72143
+ });
72144
+ const assetIds = assets.map((asset) => asset.id);
72145
+ await client.imAssets.updateMany({
72146
+ where: {
72147
+ id: {
72148
+ in: assetIds
72149
+ }
72150
+ },
72151
+ data: {
72152
+ mintingStatus: 'submitting'
72153
+ }
72154
+ });
72155
+ const updatedAssets = await client.imAssets.findMany({
72156
+ where: {
72157
+ id: {
72158
+ in: assetIds
72159
+ }
72160
+ }
72161
+ });
72162
+ return updatedAssets.map((asset) => ({
72163
+ id: asset.id,
72164
+ contract_address: asset.contractAddress,
72165
+ wallet_address: asset.ownerAddress,
72166
+ asset_id: asset.assetId,
72167
+ metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72168
+ owner_address: asset.ownerAddress,
72169
+ tried_count: asset.triedCount,
72170
+ }));
72171
+ },
72172
+ updateMintingStatusToSubmitted: async (ids) => {
72173
+ await client.imAssets.updateMany({
72174
+ where: {
72175
+ id: {
72176
+ in: ids
72177
+ }
72178
+ },
72179
+ data: {
72180
+ mintingStatus: 'submitted'
72181
+ }
72182
+ });
72183
+ },
72184
+ syncMintingStatus: async (submittedMintRequest) => {
72185
+ // First, attempt to retrieve the existing asset
72186
+ const existingAsset = await client.imAssets.findUnique({
72187
+ where: {
72188
+ im_assets_uindex: {
72189
+ assetId: submittedMintRequest.assetId,
72190
+ contractAddress: submittedMintRequest.contractAddress,
72191
+ },
72192
+ }
72193
+ });
72194
+ // Check if the asset exists and the condition for updating is met
72195
+ if (existingAsset && (existingAsset.lastImtblZkevmMintRequestUpdatedId === null
72196
+ || existingAsset.lastImtblZkevmMintRequestUpdatedId < submittedMintRequest.imtblZkevmMintRequestUpdatedId)) {
72197
+ // Perform update if the existing record's lastImtblZkevmMintRequestUpdatedId is less than the new one or is null
72198
+ await client.imAssets.update({
72199
+ where: {
72200
+ im_assets_uindex: {
72201
+ assetId: submittedMintRequest.assetId,
72202
+ contractAddress: submittedMintRequest.contractAddress,
72203
+ },
72204
+ },
72205
+ data: {
72206
+ ownerAddress: submittedMintRequest.ownerAddress,
72207
+ tokenId: submittedMintRequest.tokenId,
72208
+ mintingStatus: submittedMintRequest.status,
72209
+ metadataId: submittedMintRequest.metadataId,
72210
+ lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72211
+ error: submittedMintRequest.error,
72212
+ }
72213
+ });
72214
+ }
72215
+ else if (!existingAsset) {
72216
+ // Perform insert if no existing record is found
72217
+ await client.imAssets.create({
72218
+ data: {
72219
+ assetId: submittedMintRequest.assetId,
72220
+ contractAddress: submittedMintRequest.contractAddress,
72221
+ ownerAddress: submittedMintRequest.ownerAddress,
72222
+ tokenId: submittedMintRequest.tokenId,
72223
+ mintingStatus: submittedMintRequest.status,
72224
+ metadataId: submittedMintRequest.metadataId,
72225
+ lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72226
+ error: submittedMintRequest.error,
72227
+ }
72228
+ });
72229
+ }
72230
+ // If existing asset does not meet the update condition, do nothing
72231
+ },
72232
+ updateMintingStatusToSubmissionFailed: async (ids) => {
72233
+ await client.imAssets.updateMany({
72234
+ where: {
72235
+ id: {
72236
+ in: ids
72237
+ }
72238
+ },
72239
+ data: {
72240
+ mintingStatus: 'submission_failed'
72241
+ }
72242
+ });
72243
+ },
72244
+ markAsConflict: async (assetIds, contractAddress) => {
72245
+ await client.imAssets.updateMany({
72246
+ where: {
72247
+ assetId: {
72248
+ in: assetIds // Targets assets where assetId is in the provided list
72249
+ },
72250
+ contractAddress // Additional condition for contract address
72251
+ },
72252
+ data: {
72253
+ mintingStatus: 'conflicting' // Set the new status
72254
+ }
72255
+ });
72256
+ },
72257
+ resetMintingStatus: async (ids) => {
72258
+ await client.imAssets.updateMany({
72259
+ where: {
72260
+ id: {
72261
+ in: ids // Condition to match ids
72262
+ }
72263
+ },
72264
+ data: {
72265
+ mintingStatus: null // Setting minting_status to null
72266
+ }
72267
+ });
72268
+ },
72269
+ // this method is not concurrency safe
72270
+ markForRetry: async (ids) => {
72271
+ // Retrieve the current values of tried_count for the specified ids
72272
+ const assets = await client.imAssets.findMany({
72273
+ where: {
72274
+ id: {
72275
+ in: ids
72276
+ }
72277
+ },
72278
+ select: {
72279
+ id: true,
72280
+ triedCount: true // Assuming the field is named triedCount
72281
+ }
72282
+ });
72283
+ // Update each asset with the new tried_count and nullify minting_status
72284
+ for (const asset of assets) {
72285
+ await client.imAssets.update({
72286
+ where: {
72287
+ id: asset.id
72288
+ },
72289
+ data: {
72290
+ mintingStatus: null,
72291
+ triedCount: asset.triedCount + 1
72292
+ }
72293
+ });
72294
+ }
72295
+ },
72296
+ getMintingRequest: async (contractAddress, referenceId) => {
72297
+ // Retrieve the asset from the database based on contract_address and asset_id
72298
+ const asset = await client.imAssets.findFirst({
72299
+ where: {
72300
+ contractAddress,
72301
+ assetId: referenceId
72302
+ }
72303
+ });
72304
+ if (!asset) {
72305
+ return null;
72306
+ }
72307
+ return {
72308
+ asset_id: asset.assetId,
72309
+ contract_address: asset.contractAddress,
72310
+ id: asset.id,
72311
+ metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72312
+ owner_address: asset.ownerAddress,
72313
+ tried_count: asset.triedCount,
72314
+ wallet_address: asset.ownerAddress
72315
+ };
72316
+ }
72317
+ };
72318
+ };
72319
+
72320
+ // TODO: expose metrics
72321
+ // - submitting status count, conflicting status count
72322
+ // - failed events count
72323
+ const recordMint = async (mintingPersistence, mintRequest) => {
72324
+ trackRecordMint();
72325
+ mintingPersistence.recordMint(mintRequest);
72326
+ };
72327
+ const defaultMintingDelay = 1000;
72328
+ // This function can be called in different node process and will run in parallel to mint assets.
72329
+ // Each process will NOT mint the same asset.
72330
+ // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
72331
+ // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
72332
+ const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
72333
+ trackSubmitMintingRequests();
72334
+ let mintingResponse;
72335
+ // eslint-disable-next-line no-constant-condition
72336
+ while (true) {
72337
+ await new Promise((resolve) => {
72338
+ setTimeout(resolve, defaultMintingDelay);
72339
+ });
72340
+ let batchSize = Math.min(mintingResponse?.imx_remaining_mint_requests
72341
+ ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
72342
+ : defaultBatchSize, defaultBatchSize);
72343
+ if (batchSize === 0
72344
+ && mintingResponse
72345
+ && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
72346
+ logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
72347
+ continue;
72348
+ }
72349
+ if (batchSize === 0) {
72350
+ logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
72351
+ mintingResponse = undefined;
72352
+ batchSize = defaultBatchSize;
72353
+ }
72354
+ // get mints to be submitted
72355
+ const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
72356
+ if (pendingMints.length === 0) {
72357
+ logger.info('no assets to mint');
72358
+ continue;
72359
+ }
72360
+ // chunk assets by every 100 assets. every chunk should all be for the same contract address.
72361
+ const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
72362
+ if (acc.length === 0) {
72363
+ return [{ contractAddress: row.contract_address, assets: [row] }];
72364
+ }
72365
+ const lastBatch = acc[acc.length - 1];
72366
+ if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
72367
+ return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
72368
+ }
72369
+ return [...acc, { contractAddress: row.contract_address, assets: [row] }];
72370
+ }, []);
72371
+ // submit minting request for each contract address in parallel
72372
+ const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
72373
+ const mintingRequest = {
72374
+ chainName,
72375
+ contractAddress,
72376
+ createMintRequestRequest: {
72377
+ assets: assets.map((row) => ({
72378
+ reference_id: row.asset_id,
72379
+ owner_address: row.owner_address,
72380
+ metadata: row.metadata,
72381
+ })),
72382
+ },
72383
+ };
72384
+ try {
72385
+ const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
72386
+ logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
72387
+ // update minting status to submitted
72388
+ await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
72389
+ return response;
72390
+ }
72391
+ catch (e) {
72392
+ logger.error(e);
72393
+ if (e.code === 'CONFLICT_ERROR'
72394
+ && e.details?.id === 'reference_id') {
72395
+ try {
72396
+ // mark the assets as conflicting, so that we don't send them again.
72397
+ await mintingPersistence.markAsConflict(e.details.values, contractAddress);
72398
+ // remove non conflicting assets status so that they can be retried.
72399
+ await mintingPersistence.resetMintingStatus(assets
72400
+ .map(({ id }) => id)
72401
+ .filter((id) => !e.details.values.includes(id)));
72402
+ }
72403
+ catch (e2) {
72404
+ logger.error(e2);
72405
+ }
72406
+ }
72407
+ else {
72408
+ // separate assets into "need to be retied" and "exceeded max number of tries."
72409
+ const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
72410
+ if (tried_count < maxNumberOfTries) {
72411
+ acc.assetsToRetry.push(id);
72412
+ }
72413
+ else {
72414
+ acc.assetsExceededMaxNumberOfTries.push(id);
72415
+ }
72416
+ return acc;
72417
+ }, {
72418
+ assetsToRetry: [],
72419
+ assetsExceededMaxNumberOfTries: [],
72420
+ });
72421
+ // remove all assets status so that they can be retried.
72422
+ await mintingPersistence.markForRetry(assetsToRetry);
72423
+ // mark assets that have exceeded the max number of tries as submission_failed
72424
+ await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
72425
+ }
72426
+ return e;
72427
+ }
72428
+ }));
72429
+ mintingResponse = mintingResults
72430
+ .reverse()
72431
+ .find((r) => r.status === 'fulfilled')?.value;
72432
+ }
72433
+ };
72434
+ const processMint = async (mintingPersistence, event, logger = console) => {
72435
+ trackProcessMint();
72436
+ if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
72437
+ logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
72438
+ return;
72439
+ }
72440
+ const referenceId = event.data.reference_id;
72441
+ if (!referenceId) {
72442
+ throw new Error('reference_id not found in webhook event');
72443
+ }
72444
+ const contractAddress = event.data.contract_address;
72445
+ if (!contractAddress) {
72446
+ throw new Error('contract_address not found in webhook event');
72447
+ }
72448
+ if (event.data.status === 'failed') {
72449
+ logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
72450
+ }
72451
+ const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
72452
+ if (!mintReq) {
72453
+ logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
72454
+ }
72455
+ const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
72456
+ if (!ownerAddress) {
72457
+ logger.error('owner_address missing');
72458
+ throw new Error('owner_address missing');
72459
+ }
72460
+ await mintingPersistence.syncMintingStatus({
72461
+ tokenId: event.data.token_id,
72462
+ status: event.data.status,
72463
+ assetId: referenceId,
72464
+ contractAddress,
72465
+ ownerAddress,
72466
+ metadataId: event.data.metadata_id,
72467
+ imtblZkevmMintRequestUpdatedId: event.event_id,
72468
+ error: event.data.error ? JSON.stringify(event.data.error) : null,
72469
+ });
72470
+ };
72471
+
72472
+ const noopHandlers = {
72473
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
72474
+ zkevmMintRequestUpdated: async (event) => { },
72475
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
72476
+ others: async (..._args) => { }
72477
+ };
72478
+ class MintingBackendModule {
72479
+ baseConfig;
72480
+ persistence;
72481
+ blockchainDataClient;
72482
+ logger;
72483
+ constructor(config) {
72484
+ this.baseConfig = config.baseConfig;
72485
+ this.persistence = config.persistence;
72486
+ this.logger = config.logger || console;
72487
+ this.blockchainDataClient = new BlockchainData({
72488
+ baseConfig: config.baseConfig
72489
+ });
72490
+ setEnvironment(this.baseConfig.environment);
72491
+ if (this.baseConfig.publishableKey) {
72492
+ setPublishableApiKey(this.baseConfig.publishableKey);
72493
+ }
72494
+ }
72495
+ async recordMint(mintRequest) {
72496
+ await recordMint(this.persistence, mintRequest);
72497
+ }
72498
+ async submitMintingRequests(config) {
72499
+ await submitMintingRequests(this.persistence, this.blockchainDataClient, config);
72500
+ }
72501
+ async processMint(body, otherHandlers = noopHandlers) {
72502
+ await init(body, this.baseConfig.environment, {
72503
+ zkevmMintRequestUpdated: async (event) => {
72504
+ await processMint(this.persistence, event, this.logger);
72505
+ otherHandlers.zkevmMintRequestUpdated(event);
72506
+ },
72507
+ others: otherHandlers.others
72508
+ });
72509
+ }
72510
+ }
72511
+
72512
+ var minting_backend = /*#__PURE__*/Object.freeze({
72513
+ __proto__: null,
72514
+ MintingBackendModule: MintingBackendModule,
72515
+ mintingPersistencePg: mintingPersistence$1,
72516
+ mintingPersistencePrismaSqlite: mintingPersistence,
72517
+ processMint: processMint,
72518
+ recordMint: recordMint,
72519
+ submitMintingRequests: submitMintingRequests
72520
+ });
72521
+
72522
+ export { blockchain_data as blockchainData, checkout, config, minting_backend as mintingBackend, orderbook, passport, webhook, x };