@imtbl/sdk 1.36.2 → 1.36.3-alpha.1

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
@@ -33,6 +33,7 @@ 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';
36
37
 
37
38
  const isNode$1 = () => typeof window === 'undefined';
38
39
  const isBrowser$1 = () => !isNode$1();
@@ -160,7 +161,7 @@ const flattenProperties$1 = (properties) => {
160
161
  };
161
162
 
162
163
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
163
- const SDK_VERSION$1 = '1.36.2';
164
+ const SDK_VERSION$1 = '1.36.3-alpha.1';
164
165
  const getFrameParentDomain$1 = () => {
165
166
  if (isNode$1()) {
166
167
  return '';
@@ -14187,7 +14188,7 @@ class MultiRollupApiClients {
14187
14188
  }
14188
14189
 
14189
14190
  // eslint-disable-next-line @typescript-eslint/naming-convention
14190
- const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.36.2' };
14191
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.36.3-alpha.1' };
14191
14192
  const createConfig$1 = ({ basePath, headers, }) => {
14192
14193
  if (!basePath.trim()) {
14193
14194
  throw Error('basePath can not be empty');
@@ -14259,7 +14260,7 @@ class APIError extends Error {
14259
14260
 
14260
14261
  /* eslint-disable implicit-arrow-linebreak */
14261
14262
  const defaultHeaders$1 = {
14262
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.36.2',
14263
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.36.3-alpha.1',
14263
14264
  };
14264
14265
  /**
14265
14266
  * createAPIConfiguration to create a custom Configuration
@@ -14733,7 +14734,7 @@ var blockchain_data = /*#__PURE__*/Object.freeze({
14733
14734
  /* eslint-disable @typescript-eslint/naming-convention */
14734
14735
  class ApiConfiguration extends index$2.Configuration {
14735
14736
  }
14736
- const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.36.2' };
14737
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.36.3-alpha.1' };
14737
14738
  /**
14738
14739
  * @dev use createImmutableXConfiguration instead
14739
14740
  */
@@ -14772,7 +14773,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
14772
14773
  chainID,
14773
14774
  coreContractAddress,
14774
14775
  registrationContractAddress,
14775
- sdkVersion: 'ts-immutable-sdk-1.36.2',
14776
+ sdkVersion: 'ts-immutable-sdk-1.36.3-alpha.1',
14776
14777
  baseConfig,
14777
14778
  });
14778
14779
  const production = ({ baseConfig }) => createImmutableXConfiguration({
@@ -23594,12 +23595,12 @@ function assertOptions$1(options, schema, allowUnknown) {
23594
23595
  }
23595
23596
  }
23596
23597
 
23597
- var validator$1 = {
23598
+ var validator$2 = {
23598
23599
  assertOptions: assertOptions$1,
23599
23600
  validators: validators$1$1
23600
23601
  };
23601
23602
 
23602
- const validators$2 = validator$1.validators;
23603
+ const validators$2 = validator$2.validators;
23603
23604
 
23604
23605
  /**
23605
23606
  * Create a new instance of Axios
@@ -23640,7 +23641,7 @@ let Axios$2 = class Axios {
23640
23641
  const {transitional, paramsSerializer, headers} = config;
23641
23642
 
23642
23643
  if (transitional !== undefined) {
23643
- validator$1.assertOptions(transitional, {
23644
+ validator$2.assertOptions(transitional, {
23644
23645
  silentJSONParsing: validators$2.transitional(validators$2.boolean),
23645
23646
  forcedJSONParsing: validators$2.transitional(validators$2.boolean),
23646
23647
  clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
@@ -23653,7 +23654,7 @@ let Axios$2 = class Axios {
23653
23654
  serialize: paramsSerializer
23654
23655
  };
23655
23656
  } else {
23656
- validator$1.assertOptions(paramsSerializer, {
23657
+ validator$2.assertOptions(paramsSerializer, {
23657
23658
  encode: validators$2.function,
23658
23659
  serialize: validators$2.function
23659
23660
  }, true);
@@ -29246,8 +29247,6 @@ function getOrderbookConfig(config) {
29246
29247
  case Environment$1.SANDBOX:
29247
29248
  return {
29248
29249
  seaportContractAddress: '0x7d117aA8BD6D31c4fa91722f246388f38ab1942c',
29249
- // eslint-disable-next-line max-len
29250
- // zoneContractAddress: '0x8831867E347AB87FA30199C5B695F0A31604Bb52', // ImmutableSignedZoneV1
29251
29250
  zoneContractAddress: '0x1004f9615E79462c711Ff05a386BdbA91a7628C3',
29252
29251
  apiEndpoint: 'https://api.sandbox.immutable.com',
29253
29252
  chainName: TESTNET_CHAIN_NAME,
@@ -29257,10 +29256,7 @@ function getOrderbookConfig(config) {
29257
29256
  case Environment$1.PRODUCTION:
29258
29257
  return {
29259
29258
  seaportContractAddress: '0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424',
29260
- // eslint-disable-next-line max-len
29261
- zoneContractAddress: '0x00338b92Bec262078B3e49BF12bbEA058916BF91',
29262
- // eslint-disable-next-line max-len
29263
- // zoneContractAddress: '0x1004f9615E79462c711Ff05a386BdbA91a7628C3', // ImmutableSignedZoneV2
29259
+ zoneContractAddress: '0x1004f9615E79462c711Ff05a386BdbA91a7628C3',
29264
29260
  apiEndpoint: 'https://api.immutable.com',
29265
29261
  chainName: MAINNET_CHAIN_NAME,
29266
29262
  provider: getConfiguredProvider('https://rpc.immutable.com', config.baseConfig.rateLimitingKey),
@@ -32354,12 +32350,12 @@ function assertOptions(options, schema, allowUnknown) {
32354
32350
  }
32355
32351
  }
32356
32352
 
32357
- var validator = {
32353
+ var validator$1 = {
32358
32354
  assertOptions,
32359
32355
  validators: validators$1
32360
32356
  };
32361
32357
 
32362
- const validators = validator.validators;
32358
+ const validators = validator$1.validators;
32363
32359
 
32364
32360
  /**
32365
32361
  * Create a new instance of Axios
@@ -32400,7 +32396,7 @@ class Axios {
32400
32396
  const {transitional, paramsSerializer, headers} = config;
32401
32397
 
32402
32398
  if (transitional !== undefined) {
32403
- validator.assertOptions(transitional, {
32399
+ validator$1.assertOptions(transitional, {
32404
32400
  silentJSONParsing: validators.transitional(validators.boolean),
32405
32401
  forcedJSONParsing: validators.transitional(validators.boolean),
32406
32402
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -32413,7 +32409,7 @@ class Axios {
32413
32409
  serialize: paramsSerializer
32414
32410
  };
32415
32411
  } else {
32416
- validator.assertOptions(paramsSerializer, {
32412
+ validator$1.assertOptions(paramsSerializer, {
32417
32413
  encode: validators.function,
32418
32414
  serialize: validators.function
32419
32415
  }, true);
@@ -58172,7 +58168,7 @@ const flattenProperties = (properties) => {
58172
58168
  };
58173
58169
 
58174
58170
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
58175
- const SDK_VERSION = '1.36.2';
58171
+ const SDK_VERSION = '1.36.3-alpha.1';
58176
58172
  const getFrameParentDomain = () => {
58177
58173
  if (isNode()) {
58178
58174
  return '';
@@ -63465,7 +63461,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
63465
63461
  maxPriorityFeePerGas: BigNumber$1.from(10e9),
63466
63462
  };
63467
63463
 
63468
- const SDK_VERSION_MARKER = '1.36.2';
63464
+ const SDK_VERSION_MARKER = '1.36.3-alpha.1';
63469
63465
  // This SDK version is replaced by the `yarn build` command ran on the root level
63470
63466
  const globalPackageVersion = () => SDK_VERSION_MARKER;
63471
63467
 
@@ -69131,4 +69127,594 @@ var x = /*#__PURE__*/Object.freeze({
69131
69127
  sandbox: sandbox
69132
69128
  });
69133
69129
 
69134
- export { blockchain_data as blockchainData, checkout, config, orderbook, passport, x };
69130
+ const validator = new MessageValidator();
69131
+ const allowedTopicArnPrefix = {
69132
+ [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
69133
+ [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
69134
+ };
69135
+ const init = async (body, env, handlers) => {
69136
+ const msg = await new Promise((resolve, reject) => {
69137
+ validator.validate(body, (err, message) => {
69138
+ if (err) {
69139
+ return reject(err);
69140
+ }
69141
+ // check for topic arn prefix
69142
+ if (!message.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
69143
+ throw new Error('Invalid topic arn');
69144
+ }
69145
+ if (message?.Type === 'SubscriptionConfirmation') {
69146
+ fetch(message.SubscribeURL).then(() => {
69147
+ resolve(message);
69148
+ }).catch((e) => {
69149
+ reject(e);
69150
+ });
69151
+ }
69152
+ return resolve(message);
69153
+ });
69154
+ });
69155
+ if (msg.Type === 'Notification') {
69156
+ const event = JSON.parse(msg.Message);
69157
+ switch (event.event_name) {
69158
+ case 'imtbl_zkevm_mint_request_updated':
69159
+ await handlers.zkevmMintRequestUpdated(event);
69160
+ break;
69161
+ default:
69162
+ if (handlers.others) {
69163
+ await handlers.others(event);
69164
+ }
69165
+ break;
69166
+ }
69167
+ }
69168
+ };
69169
+
69170
+ var webhook = /*#__PURE__*/Object.freeze({
69171
+ __proto__: null,
69172
+ init: init
69173
+ });
69174
+
69175
+ const moduleName = 'minting_backend_sdk';
69176
+ const trackInitializePersistencePG = () => {
69177
+ try {
69178
+ track(moduleName, 'initializePersistencePG');
69179
+ }
69180
+ catch {
69181
+ // ignore
69182
+ }
69183
+ };
69184
+ const trackInitializePersistencePrismaSqlite = () => {
69185
+ try {
69186
+ track(moduleName, 'initializePersistencePrismaSqlite');
69187
+ }
69188
+ catch {
69189
+ // ignore
69190
+ }
69191
+ };
69192
+ const trackSubmitMintingRequests = () => {
69193
+ try {
69194
+ track(moduleName, 'submitMintingRequests');
69195
+ }
69196
+ catch {
69197
+ // ignore
69198
+ }
69199
+ };
69200
+ const trackProcessMint = () => {
69201
+ try {
69202
+ track(moduleName, 'processMint');
69203
+ }
69204
+ catch {
69205
+ // ignore
69206
+ }
69207
+ };
69208
+ const trackRecordMint = () => {
69209
+ try {
69210
+ track(moduleName, 'recordMint');
69211
+ }
69212
+ catch {
69213
+ // ignore
69214
+ }
69215
+ };
69216
+
69217
+ const mintingPersistence$1 = (client) => {
69218
+ trackInitializePersistencePG();
69219
+ return {
69220
+ recordMint: async (request) => {
69221
+ const r = await client.query(`
69222
+ INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata)
69223
+ VALUES ($1, $2, $3, $4) ON CONFLICT (asset_id, contract_address) DO NOTHING;
69224
+ `, [request.asset_id, request.contract_address, request.owner_address, request.metadata]);
69225
+ if (r.rowCount === 0) {
69226
+ throw new Error('Duplicated mint');
69227
+ }
69228
+ },
69229
+ getNextBatchForSubmission: async (limit) => {
69230
+ const res = await client.query(`
69231
+ UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
69232
+ select id from im_assets where minting_status is null limit $1 for update skip locked
69233
+ ) returning *;
69234
+ `, [limit]);
69235
+ return res.rows;
69236
+ },
69237
+ updateMintingStatusToSubmitted: async (ids) => {
69238
+ await client.query(`
69239
+ UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
69240
+ `, [ids, 'submitted']);
69241
+ },
69242
+ syncMintingStatus: async (submittedMintRequest) => {
69243
+ // doing a upsert just in case the row has not been created yet
69244
+ await client.query(`
69245
+ INSERT INTO im_assets (
69246
+ asset_id,
69247
+ contract_address,
69248
+ owner_address,
69249
+ token_id,
69250
+ minting_status,
69251
+ metadata_id,
69252
+ last_imtbl_zkevm_mint_request_updated_id,
69253
+ error
69254
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (asset_id, contract_address)
69255
+ DO UPDATE SET
69256
+ owner_address = $3,
69257
+ token_id = $4,
69258
+ minting_status = $5,
69259
+ metadata_id = $6,
69260
+ last_imtbl_zkevm_mint_request_updated_id = $7,
69261
+ error = $8
69262
+ where (
69263
+ im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
69264
+ im_assets.last_imtbl_zkevm_mint_request_updated_id is null
69265
+ );
69266
+ `, [
69267
+ submittedMintRequest.assetId,
69268
+ submittedMintRequest.contractAddress,
69269
+ submittedMintRequest.ownerAddress,
69270
+ submittedMintRequest.tokenId,
69271
+ submittedMintRequest.status,
69272
+ submittedMintRequest.metadataId,
69273
+ submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69274
+ submittedMintRequest.error
69275
+ ]);
69276
+ },
69277
+ markAsConflict: async (assetIds, contractAddress) => {
69278
+ await client.query(`
69279
+ UPDATE im_assets
69280
+ SET minting_status = 'conflicting'
69281
+ WHERE asset_id = ANY($1)
69282
+ AND contract_address = $2;
69283
+ `, [assetIds, contractAddress]);
69284
+ },
69285
+ resetMintingStatus: async (ids) => {
69286
+ await client.query(`
69287
+ UPDATE im_assets SET minting_status = null WHERE id = ANY($1);
69288
+ `, [ids]);
69289
+ },
69290
+ markForRetry: async (ids) => {
69291
+ await client.query(`
69292
+ UPDATE im_assets
69293
+ SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
69294
+ `, [ids]);
69295
+ },
69296
+ updateMintingStatusToSubmissionFailed: async (ids) => {
69297
+ await client.query(`
69298
+ UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
69299
+ `, [ids]);
69300
+ },
69301
+ getMintingRequest: async (contractAddress, referenceId) => {
69302
+ const res = await client.query(`
69303
+ SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
69304
+ `, [contractAddress, referenceId]);
69305
+ return res.rows[0] || null;
69306
+ }
69307
+ };
69308
+ };
69309
+
69310
+ /* eslint-disable no-await-in-loop */
69311
+ /* eslint-disable @typescript-eslint/naming-convention */
69312
+ // client is a PrismaClient instance. it needs to be generated with
69313
+ // additional schema defined inside (TODO: point to repo) file.
69314
+ const mintingPersistence = (client) => {
69315
+ trackInitializePersistencePrismaSqlite();
69316
+ return {
69317
+ recordMint: async (request) => {
69318
+ const result = await client.imAssets.upsert({
69319
+ where: {
69320
+ im_assets_uindex: {
69321
+ assetId: request.asset_id, contractAddress: request.contract_address
69322
+ }
69323
+ },
69324
+ update: {},
69325
+ create: {
69326
+ assetId: request.asset_id,
69327
+ contractAddress: request.contract_address,
69328
+ ownerAddress: request.owner_address,
69329
+ metadata: JSON.stringify(request.metadata), // Serialize JSON metadata
69330
+ },
69331
+ });
69332
+ // Since upsert does not throw on update and does not tell directly if it updated or inserted,
69333
+ // we need to add additional logic to handle this if "result" does not provide enough info.
69334
+ if (!result) {
69335
+ throw new Error('Duplicated mint');
69336
+ }
69337
+ },
69338
+ // WARNING: this is NOT concurrency safe. Please only call this method one at a time.
69339
+ getNextBatchForSubmission: async (limit) => {
69340
+ const assets = await client.imAssets.findMany({
69341
+ where: {
69342
+ mintingStatus: null
69343
+ },
69344
+ take: limit
69345
+ });
69346
+ const assetIds = assets.map((asset) => asset.id);
69347
+ await client.imAssets.updateMany({
69348
+ where: {
69349
+ id: {
69350
+ in: assetIds
69351
+ }
69352
+ },
69353
+ data: {
69354
+ mintingStatus: 'submitting'
69355
+ }
69356
+ });
69357
+ const updatedAssets = await client.imAssets.findMany({
69358
+ where: {
69359
+ id: {
69360
+ in: assetIds
69361
+ }
69362
+ }
69363
+ });
69364
+ return updatedAssets.map((asset) => ({
69365
+ id: asset.id,
69366
+ contract_address: asset.contractAddress,
69367
+ wallet_address: asset.ownerAddress,
69368
+ asset_id: asset.assetId,
69369
+ metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
69370
+ owner_address: asset.ownerAddress,
69371
+ tried_count: asset.triedCount,
69372
+ }));
69373
+ },
69374
+ updateMintingStatusToSubmitted: async (ids) => {
69375
+ await client.imAssets.updateMany({
69376
+ where: {
69377
+ id: {
69378
+ in: ids
69379
+ }
69380
+ },
69381
+ data: {
69382
+ mintingStatus: 'submitted'
69383
+ }
69384
+ });
69385
+ },
69386
+ syncMintingStatus: async (submittedMintRequest) => {
69387
+ // First, attempt to retrieve the existing asset
69388
+ const existingAsset = await client.imAssets.findUnique({
69389
+ where: {
69390
+ im_assets_uindex: {
69391
+ assetId: submittedMintRequest.assetId,
69392
+ contractAddress: submittedMintRequest.contractAddress,
69393
+ },
69394
+ }
69395
+ });
69396
+ // Check if the asset exists and the condition for updating is met
69397
+ if (existingAsset && (existingAsset.lastImtblZkevmMintRequestUpdatedId === null
69398
+ || existingAsset.lastImtblZkevmMintRequestUpdatedId < submittedMintRequest.imtblZkevmMintRequestUpdatedId)) {
69399
+ // Perform update if the existing record's lastImtblZkevmMintRequestUpdatedId is less than the new one or is null
69400
+ await client.imAssets.update({
69401
+ where: {
69402
+ im_assets_uindex: {
69403
+ assetId: submittedMintRequest.assetId,
69404
+ contractAddress: submittedMintRequest.contractAddress,
69405
+ },
69406
+ },
69407
+ data: {
69408
+ ownerAddress: submittedMintRequest.ownerAddress,
69409
+ tokenId: submittedMintRequest.tokenId,
69410
+ mintingStatus: submittedMintRequest.status,
69411
+ metadataId: submittedMintRequest.metadataId,
69412
+ lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69413
+ error: submittedMintRequest.error,
69414
+ }
69415
+ });
69416
+ }
69417
+ else if (!existingAsset) {
69418
+ // Perform insert if no existing record is found
69419
+ await client.imAssets.create({
69420
+ data: {
69421
+ assetId: submittedMintRequest.assetId,
69422
+ contractAddress: submittedMintRequest.contractAddress,
69423
+ ownerAddress: submittedMintRequest.ownerAddress,
69424
+ tokenId: submittedMintRequest.tokenId,
69425
+ mintingStatus: submittedMintRequest.status,
69426
+ metadataId: submittedMintRequest.metadataId,
69427
+ lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
69428
+ error: submittedMintRequest.error,
69429
+ }
69430
+ });
69431
+ }
69432
+ // If existing asset does not meet the update condition, do nothing
69433
+ },
69434
+ updateMintingStatusToSubmissionFailed: async (ids) => {
69435
+ await client.imAssets.updateMany({
69436
+ where: {
69437
+ id: {
69438
+ in: ids
69439
+ }
69440
+ },
69441
+ data: {
69442
+ mintingStatus: 'submission_failed'
69443
+ }
69444
+ });
69445
+ },
69446
+ markAsConflict: async (assetIds, contractAddress) => {
69447
+ await client.imAssets.updateMany({
69448
+ where: {
69449
+ assetId: {
69450
+ in: assetIds // Targets assets where assetId is in the provided list
69451
+ },
69452
+ contractAddress // Additional condition for contract address
69453
+ },
69454
+ data: {
69455
+ mintingStatus: 'conflicting' // Set the new status
69456
+ }
69457
+ });
69458
+ },
69459
+ resetMintingStatus: async (ids) => {
69460
+ await client.imAssets.updateMany({
69461
+ where: {
69462
+ id: {
69463
+ in: ids // Condition to match ids
69464
+ }
69465
+ },
69466
+ data: {
69467
+ mintingStatus: null // Setting minting_status to null
69468
+ }
69469
+ });
69470
+ },
69471
+ // this method is not concurrency safe
69472
+ markForRetry: async (ids) => {
69473
+ // Retrieve the current values of tried_count for the specified ids
69474
+ const assets = await client.imAssets.findMany({
69475
+ where: {
69476
+ id: {
69477
+ in: ids
69478
+ }
69479
+ },
69480
+ select: {
69481
+ id: true,
69482
+ triedCount: true // Assuming the field is named triedCount
69483
+ }
69484
+ });
69485
+ // Update each asset with the new tried_count and nullify minting_status
69486
+ for (const asset of assets) {
69487
+ await client.imAssets.update({
69488
+ where: {
69489
+ id: asset.id
69490
+ },
69491
+ data: {
69492
+ mintingStatus: null,
69493
+ triedCount: asset.triedCount + 1
69494
+ }
69495
+ });
69496
+ }
69497
+ },
69498
+ getMintingRequest: async (contractAddress, referenceId) => {
69499
+ // Retrieve the asset from the database based on contract_address and asset_id
69500
+ const asset = await client.imAssets.findFirst({
69501
+ where: {
69502
+ contractAddress,
69503
+ assetId: referenceId
69504
+ }
69505
+ });
69506
+ if (!asset) {
69507
+ return null;
69508
+ }
69509
+ return {
69510
+ asset_id: asset.assetId,
69511
+ contract_address: asset.contractAddress,
69512
+ id: asset.id,
69513
+ metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
69514
+ owner_address: asset.ownerAddress,
69515
+ tried_count: asset.triedCount,
69516
+ wallet_address: asset.ownerAddress
69517
+ };
69518
+ }
69519
+ };
69520
+ };
69521
+
69522
+ // TODO: expose metrics
69523
+ // - submitting status count, conflicting status count
69524
+ // - failed events count
69525
+ const recordMint = async (mintingPersistence, mintRequest) => {
69526
+ trackRecordMint();
69527
+ mintingPersistence.recordMint(mintRequest);
69528
+ };
69529
+ const defaultMintingDelay = 1000;
69530
+ // This function can be called in different node process and will run in parallel to mint assets.
69531
+ // Each process will NOT mint the same asset.
69532
+ // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
69533
+ // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
69534
+ const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
69535
+ trackSubmitMintingRequests();
69536
+ let mintingResponse;
69537
+ // eslint-disable-next-line no-constant-condition
69538
+ while (true) {
69539
+ await new Promise((resolve) => {
69540
+ setTimeout(resolve, defaultMintingDelay);
69541
+ });
69542
+ let batchSize = Math.min(mintingResponse?.imx_remaining_mint_requests
69543
+ ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
69544
+ : defaultBatchSize, defaultBatchSize);
69545
+ if (batchSize === 0
69546
+ && mintingResponse
69547
+ && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
69548
+ logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
69549
+ continue;
69550
+ }
69551
+ if (batchSize === 0) {
69552
+ logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
69553
+ mintingResponse = undefined;
69554
+ batchSize = defaultBatchSize;
69555
+ }
69556
+ // get mints to be submitted
69557
+ const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
69558
+ if (pendingMints.length === 0) {
69559
+ logger.info('no assets to mint');
69560
+ continue;
69561
+ }
69562
+ // chunk assets by every 100 assets. every chunk should all be for the same contract address.
69563
+ const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
69564
+ if (acc.length === 0) {
69565
+ return [{ contractAddress: row.contract_address, assets: [row] }];
69566
+ }
69567
+ const lastBatch = acc[acc.length - 1];
69568
+ if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
69569
+ return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
69570
+ }
69571
+ return [...acc, { contractAddress: row.contract_address, assets: [row] }];
69572
+ }, []);
69573
+ // submit minting request for each contract address in parallel
69574
+ const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
69575
+ const mintingRequest = {
69576
+ chainName,
69577
+ contractAddress,
69578
+ createMintRequestRequest: {
69579
+ assets: assets.map((row) => ({
69580
+ reference_id: row.asset_id,
69581
+ owner_address: row.owner_address,
69582
+ metadata: row.metadata,
69583
+ })),
69584
+ },
69585
+ };
69586
+ try {
69587
+ const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
69588
+ logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
69589
+ // update minting status to submitted
69590
+ await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
69591
+ return response;
69592
+ }
69593
+ catch (e) {
69594
+ logger.error(e);
69595
+ if (e.code === 'CONFLICT_ERROR'
69596
+ && e.details?.id === 'reference_id') {
69597
+ try {
69598
+ // mark the assets as conflicting, so that we don't send them again.
69599
+ await mintingPersistence.markAsConflict(e.details.values, contractAddress);
69600
+ // remove non conflicting assets status so that they can be retried.
69601
+ await mintingPersistence.resetMintingStatus(assets
69602
+ .map(({ id }) => id)
69603
+ .filter((id) => !e.details.values.includes(id)));
69604
+ }
69605
+ catch (e2) {
69606
+ logger.error(e2);
69607
+ }
69608
+ }
69609
+ else {
69610
+ // separate assets into "need to be retied" and "exceeded max number of tries."
69611
+ const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
69612
+ if (tried_count < maxNumberOfTries) {
69613
+ acc.assetsToRetry.push(id);
69614
+ }
69615
+ else {
69616
+ acc.assetsExceededMaxNumberOfTries.push(id);
69617
+ }
69618
+ return acc;
69619
+ }, {
69620
+ assetsToRetry: [],
69621
+ assetsExceededMaxNumberOfTries: [],
69622
+ });
69623
+ // remove all assets status so that they can be retried.
69624
+ await mintingPersistence.markForRetry(assetsToRetry);
69625
+ // mark assets that have exceeded the max number of tries as submission_failed
69626
+ await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
69627
+ }
69628
+ return e;
69629
+ }
69630
+ }));
69631
+ mintingResponse = mintingResults
69632
+ .reverse()
69633
+ .find((r) => r.status === 'fulfilled')?.value;
69634
+ }
69635
+ };
69636
+ const processMint = async (mintingPersistence, event, logger = console) => {
69637
+ trackProcessMint();
69638
+ if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
69639
+ logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
69640
+ return;
69641
+ }
69642
+ const referenceId = event.data.reference_id;
69643
+ if (!referenceId) {
69644
+ throw new Error('reference_id not found in webhook event');
69645
+ }
69646
+ const contractAddress = event.data.contract_address;
69647
+ if (!contractAddress) {
69648
+ throw new Error('contract_address not found in webhook event');
69649
+ }
69650
+ if (event.data.status === 'failed') {
69651
+ logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
69652
+ }
69653
+ const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
69654
+ if (!mintReq) {
69655
+ logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
69656
+ }
69657
+ const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
69658
+ if (!ownerAddress) {
69659
+ logger.error('owner_address missing');
69660
+ throw new Error('owner_address missing');
69661
+ }
69662
+ await mintingPersistence.syncMintingStatus({
69663
+ tokenId: event.data.token_id,
69664
+ status: event.data.status,
69665
+ assetId: referenceId,
69666
+ contractAddress,
69667
+ ownerAddress,
69668
+ metadataId: event.data.metadata_id,
69669
+ imtblZkevmMintRequestUpdatedId: event.event_id,
69670
+ error: event.data.error ? JSON.stringify(event.data.error) : null,
69671
+ });
69672
+ };
69673
+
69674
+ const noopHandlers = {
69675
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
69676
+ zkevmMintRequestUpdated: async (event) => { },
69677
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
69678
+ others: async (..._args) => { }
69679
+ };
69680
+ class MintingBackendModule {
69681
+ baseConfig;
69682
+ persistence;
69683
+ blockchainDataClient;
69684
+ logger;
69685
+ constructor(config) {
69686
+ this.baseConfig = config.baseConfig;
69687
+ this.persistence = config.persistence;
69688
+ this.logger = config.logger || console;
69689
+ this.blockchainDataClient = new BlockchainData({
69690
+ baseConfig: config.baseConfig
69691
+ });
69692
+ }
69693
+ async recordMint(mintRequest) {
69694
+ await recordMint(this.persistence, mintRequest);
69695
+ }
69696
+ async submitMintingRequests(config) {
69697
+ await submitMintingRequests(this.persistence, this.blockchainDataClient, config);
69698
+ }
69699
+ async processMint(body, otherHandlers = noopHandlers) {
69700
+ await init(body, this.baseConfig.environment, {
69701
+ zkevmMintRequestUpdated: async (event) => {
69702
+ await processMint(this.persistence, event, this.logger);
69703
+ otherHandlers.zkevmMintRequestUpdated(event);
69704
+ },
69705
+ others: otherHandlers.others
69706
+ });
69707
+ }
69708
+ }
69709
+
69710
+ var minting_backend = /*#__PURE__*/Object.freeze({
69711
+ __proto__: null,
69712
+ MintingBackendModule: MintingBackendModule,
69713
+ mintingPersistencePg: mintingPersistence$1,
69714
+ mintingPersistencePrismaSqlite: mintingPersistence,
69715
+ processMint: processMint,
69716
+ recordMint: recordMint,
69717
+ submitMintingRequests: submitMintingRequests
69718
+ });
69719
+
69720
+ export { blockchain_data as blockchainData, checkout, config, minting_backend as mintingBackend, orderbook, passport, webhook, x };