@imtbl/sdk 1.40.0-alpha.2 → 1.40.0

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.40.0-alpha.2';
187
+ const SDK_VERSION$1 = '1.40.0';
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.40.0-alpha.2' };
14214
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.40.0' };
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.40.0-alpha.2',
14286
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.40.0',
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.40.0-alpha.2' };
14760
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.40.0' };
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.40.0-alpha.2',
14801
+ sdkVersion: 'ts-immutable-sdk-1.40.0',
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);
@@ -35130,12 +35129,12 @@ function assertOptions(options, schema, allowUnknown) {
35130
35129
  }
35131
35130
  }
35132
35131
 
35133
- var validator$1 = {
35132
+ var validator = {
35134
35133
  assertOptions,
35135
35134
  validators: validators$1
35136
35135
  };
35137
35136
 
35138
- const validators = validator$1.validators;
35137
+ const validators = validator.validators;
35139
35138
 
35140
35139
  /**
35141
35140
  * Create a new instance of Axios
@@ -35176,7 +35175,7 @@ class Axios {
35176
35175
  const {transitional, paramsSerializer, headers} = config;
35177
35176
 
35178
35177
  if (transitional !== undefined) {
35179
- validator$1.assertOptions(transitional, {
35178
+ validator.assertOptions(transitional, {
35180
35179
  silentJSONParsing: validators.transitional(validators.boolean),
35181
35180
  forcedJSONParsing: validators.transitional(validators.boolean),
35182
35181
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -35189,7 +35188,7 @@ class Axios {
35189
35188
  serialize: paramsSerializer
35190
35189
  };
35191
35190
  } else {
35192
- validator$1.assertOptions(paramsSerializer, {
35191
+ validator.assertOptions(paramsSerializer, {
35193
35192
  encode: validators.function,
35194
35193
  serialize: validators.function
35195
35194
  }, true);
@@ -60948,7 +60947,7 @@ const flattenProperties = (properties) => {
60948
60947
  };
60949
60948
 
60950
60949
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
60951
- const SDK_VERSION = '1.40.0-alpha.2';
60950
+ const SDK_VERSION = '1.40.0';
60952
60951
  const getFrameParentDomain = () => {
60953
60952
  if (isNode()) {
60954
60953
  return '';
@@ -66266,7 +66265,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
66266
66265
  maxPriorityFeePerGas: ethers.BigNumber.from(10e9),
66267
66266
  };
66268
66267
 
66269
- const SDK_VERSION_MARKER = '1.40.0-alpha.2';
66268
+ const SDK_VERSION_MARKER = '1.40.0';
66270
66269
  // This SDK version is replaced by the `yarn build` command ran on the root level
66271
66270
  const globalPackageVersion = () => SDK_VERSION_MARKER;
66272
66271
 
@@ -72026,750 +72025,9 @@ var x = /*#__PURE__*/Object.freeze({
72026
72025
  starkEcOrder: starkEcOrder
72027
72026
  });
72028
72027
 
72029
- const validator = new MessageValidator();
72030
- const allowedTopicArnPrefix = {
72031
- [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
72032
- [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
72033
- };
72034
- /**
72035
- * handle will validate webhook message origin and verify signature of the message and calls corresponding handlers passed in.
72036
- * @param body The request body to a webhook endpoint in json string or js object form.
72037
- * @param env The Immutable environment the webhook is set up for.
72038
- * @param handlers The optional handlers object for different events. The `all` handler will be triggered for all event types.
72039
- * @returns The event object from the webhook message after validation and verification.
72040
- */
72041
- const handle = async (body, env, handlers) => {
72042
- const msg = await new Promise((resolve, reject) => {
72043
- validator.validate(body, (err, message) => {
72044
- if (err) {
72045
- return reject(err);
72046
- }
72047
- // check for topic arn prefix
72048
- if (!message.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
72049
- throw new Error('Invalid topic arn');
72050
- }
72051
- if (message?.Type === 'SubscriptionConfirmation') {
72052
- fetch(message.SubscribeURL).then(() => {
72053
- resolve(message);
72054
- }).catch((e) => {
72055
- reject(e);
72056
- });
72057
- }
72058
- return resolve(message);
72059
- });
72060
- });
72061
- const event = JSON.parse(msg.Message);
72062
- if (msg.Type === 'Notification') {
72063
- switch (event.event_name) {
72064
- case 'imtbl_zkevm_mint_request_updated':
72065
- if (handlers?.zkevmMintRequestUpdated) {
72066
- await handlers?.zkevmMintRequestUpdated(event);
72067
- }
72068
- break;
72069
- case 'imtbl_zkevm_activity_mint':
72070
- if (handlers?.zkEvmActivityMint) {
72071
- await handlers?.zkEvmActivityMint(event);
72072
- }
72073
- break;
72074
- case 'imtbl_zkevm_activity_burn':
72075
- if (handlers?.zkEvmActivityBurn) {
72076
- await handlers?.zkEvmActivityBurn(event);
72077
- }
72078
- break;
72079
- case 'imtbl_zkevm_activity_transfer':
72080
- if (handlers?.zkEvmActivityTransfer) {
72081
- await handlers?.zkEvmActivityTransfer(event);
72082
- }
72083
- break;
72084
- case 'imtbl_zkevm_activity_sale':
72085
- if (handlers?.zkEvmActivitySale) {
72086
- await handlers?.zkEvmActivitySale(event);
72087
- }
72088
- break;
72089
- case 'imtbl_zkevm_activity_deposit':
72090
- if (handlers?.zkEvmActivityDeposit) {
72091
- await handlers?.zkEvmActivityDeposit(event);
72092
- }
72093
- break;
72094
- case 'imtbl_zkevm_activity_withdrawal':
72095
- if (handlers?.zkEvmActivityWithdrawal) {
72096
- await handlers?.zkEvmActivityWithdrawal(event);
72097
- }
72098
- break;
72099
- case 'imtbl_zkevm_collection_updated':
72100
- if (handlers?.zkEvmCollectionUpdated) {
72101
- await handlers?.zkEvmCollectionUpdated(event);
72102
- }
72103
- break;
72104
- case 'imtbl_zkevm_nft_updated':
72105
- if (handlers?.zkEvmNftUpdated) {
72106
- await handlers?.zkEvmNftUpdated(event);
72107
- }
72108
- break;
72109
- case 'imtbl_zkevm_metadata_updated':
72110
- if (handlers?.zkEvmMetadataUpdated) {
72111
- await handlers?.zkEvmMetadataUpdated(event);
72112
- }
72113
- break;
72114
- case 'imtbl_zkevm_token_updated':
72115
- if (handlers?.zkEvmTokenUpdated) {
72116
- await handlers?.zkEvmTokenUpdated(event);
72117
- }
72118
- break;
72119
- case 'imtbl_zkevm_order_updated':
72120
- if (handlers?.zkEvmOrderUpdated) {
72121
- await handlers?.zkEvmOrderUpdated(event);
72122
- }
72123
- break;
72124
- case 'imtbl_zkevm_trade_created':
72125
- if (handlers?.zkEvmTradeCreated) {
72126
- await handlers?.zkEvmTradeCreated(event);
72127
- }
72128
- break;
72129
- case 'imtbl_x_nft_created':
72130
- if (handlers?.xNftCreated) {
72131
- await handlers?.xNftCreated(event);
72132
- }
72133
- break;
72134
- case 'imtbl_x_nft_updated':
72135
- if (handlers?.xNftUpdated) {
72136
- await handlers?.xNftUpdated(event);
72137
- }
72138
- break;
72139
- case 'imtbl_x_order_accepted':
72140
- if (handlers?.xOrderAccepted) {
72141
- await handlers?.xOrderAccepted(event);
72142
- }
72143
- break;
72144
- case 'imtbl_x_order_filled':
72145
- if (handlers?.xOrderFilled) {
72146
- await handlers?.xOrderFilled(event);
72147
- }
72148
- break;
72149
- case 'imtbl_x_order_cancelled':
72150
- if (handlers?.xOrderCancelled) {
72151
- await handlers?.xOrderCancelled(event);
72152
- }
72153
- break;
72154
- case 'imtbl_x_transfer_created':
72155
- if (handlers?.xTransferCreated) {
72156
- await handlers?.xTransferCreated(event);
72157
- }
72158
- break;
72159
- }
72160
- if (handlers?.all) {
72161
- await handlers?.all(event);
72162
- }
72163
- }
72164
- return event;
72165
- };
72166
-
72167
- var webhook = /*#__PURE__*/Object.freeze({
72168
- __proto__: null,
72169
- handle: handle
72170
- });
72171
-
72172
- const moduleName = 'minting_backend_sdk';
72173
- const trackInitializePersistencePG = () => {
72174
- try {
72175
- track(moduleName, 'initializePersistencePG');
72176
- }
72177
- catch {
72178
- // ignore
72179
- }
72180
- };
72181
- const trackInitializePersistencePrismaSqlite = () => {
72182
- try {
72183
- track(moduleName, 'initializePersistencePrismaSqlite');
72184
- }
72185
- catch {
72186
- // ignore
72187
- }
72188
- };
72189
- const trackSubmitMintingRequests = () => {
72190
- try {
72191
- track(moduleName, 'submitMintingRequests');
72192
- }
72193
- catch {
72194
- // ignore
72195
- }
72196
- };
72197
- const trackProcessMint = () => {
72198
- try {
72199
- track(moduleName, 'processMint');
72200
- }
72201
- catch {
72202
- // ignore
72203
- }
72204
- };
72205
- const trackRecordMint = () => {
72206
- try {
72207
- track(moduleName, 'recordMint');
72208
- }
72209
- catch {
72210
- // ignore
72211
- }
72212
- };
72213
- const trackError = (error) => {
72214
- try {
72215
- track(moduleName, 'error', {
72216
- name: error.name,
72217
- message: error.message
72218
- });
72219
- }
72220
- catch {
72221
- // ignore
72222
- }
72223
- };
72224
- const trackUncaughtException = (error, origin) => {
72225
- try {
72226
- track(moduleName, 'error', {
72227
- name: error.name,
72228
- message: error.message,
72229
- origin,
72230
- });
72231
- }
72232
- catch {
72233
- // ignore
72234
- }
72235
- };
72236
-
72237
- const mintingPersistence$1 = (client) => {
72238
- trackInitializePersistencePG();
72239
- return {
72240
- recordMint: async (request) => {
72241
- const r = await client.query(`
72242
- INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata, amount, token_id)
72243
- VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (asset_id, contract_address) DO NOTHING;
72244
- `, [
72245
- request.asset_id, request.contract_address, request.owner_address,
72246
- request.metadata, request.amount, request.token_id
72247
- ]);
72248
- if (r.rowCount === 0) {
72249
- throw new Error('Duplicated mint');
72250
- }
72251
- },
72252
- getNextBatchForSubmission: async (limit) => {
72253
- const res = await client.query(`
72254
- UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
72255
- select id from im_assets where minting_status is null limit $1 for update skip locked
72256
- ) returning *;
72257
- `, [limit]);
72258
- return res.rows;
72259
- },
72260
- updateMintingStatusToSubmitted: async (ids) => {
72261
- await client.query(`
72262
- UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
72263
- `, [ids, 'submitted']);
72264
- },
72265
- syncMintingStatus: async (submittedMintRequest) => {
72266
- // doing a upsert just in case the row has not been created yet
72267
- await client.query(`
72268
- INSERT INTO im_assets (
72269
- asset_id,
72270
- contract_address,
72271
- owner_address,
72272
- token_id,
72273
- minting_status,
72274
- metadata_id,
72275
- last_imtbl_zkevm_mint_request_updated_id,
72276
- error,
72277
- amount
72278
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (asset_id, contract_address)
72279
- DO UPDATE SET
72280
- owner_address = $3,
72281
- token_id = $4,
72282
- minting_status = $5,
72283
- metadata_id = $6,
72284
- last_imtbl_zkevm_mint_request_updated_id = $7,
72285
- error = $8
72286
- where (
72287
- im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
72288
- im_assets.last_imtbl_zkevm_mint_request_updated_id is null
72289
- );
72290
- `, [
72291
- submittedMintRequest.assetId,
72292
- submittedMintRequest.contractAddress,
72293
- submittedMintRequest.ownerAddress,
72294
- submittedMintRequest.tokenId,
72295
- submittedMintRequest.status,
72296
- submittedMintRequest.metadataId,
72297
- submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72298
- submittedMintRequest.error,
72299
- submittedMintRequest.amount
72300
- ]);
72301
- },
72302
- markAsConflict: async (assetIds, contractAddress) => {
72303
- await client.query(`
72304
- UPDATE im_assets
72305
- SET minting_status = 'conflicting'
72306
- WHERE asset_id = ANY($1)
72307
- AND contract_address = $2;
72308
- `, [assetIds, contractAddress]);
72309
- },
72310
- resetMintingStatus: async (ids) => {
72311
- await client.query(`
72312
- UPDATE im_assets SET minting_status = null WHERE id = ANY($1);
72313
- `, [ids]);
72314
- },
72315
- markForRetry: async (ids) => {
72316
- await client.query(`
72317
- UPDATE im_assets
72318
- SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
72319
- `, [ids]);
72320
- },
72321
- updateMintingStatusToSubmissionFailed: async (ids) => {
72322
- await client.query(`
72323
- UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
72324
- `, [ids]);
72325
- },
72326
- getMintingRequest: async (contractAddress, referenceId) => {
72327
- const res = await client.query(`
72328
- SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
72329
- `, [contractAddress, referenceId]);
72330
- return res.rows[0] || null;
72331
- }
72332
- };
72333
- };
72334
-
72335
- /* eslint-disable no-await-in-loop */
72336
- /* eslint-disable @typescript-eslint/naming-convention */
72337
- // client is a PrismaClient instance. it needs to be generated with
72338
- // additional schema defined inside (TODO: point to repo) file.
72339
- const mintingPersistence = (client) => {
72340
- trackInitializePersistencePrismaSqlite();
72341
- return {
72342
- recordMint: async (request) => {
72343
- const result = await client.imAssets.upsert({
72344
- where: {
72345
- im_assets_uindex: {
72346
- assetId: request.asset_id, contractAddress: request.contract_address
72347
- }
72348
- },
72349
- update: {},
72350
- create: {
72351
- assetId: request.asset_id,
72352
- contractAddress: request.contract_address,
72353
- ownerAddress: request.owner_address,
72354
- metadata: JSON.stringify(request.metadata),
72355
- amount: request.amount || null,
72356
- tokenId: request.token_id || null,
72357
- },
72358
- });
72359
- // Since upsert does not throw on update and does not tell directly if it updated or inserted,
72360
- // we need to add additional logic to handle this if "result" does not provide enough info.
72361
- if (!result) {
72362
- throw new Error('Duplicated mint');
72363
- }
72364
- },
72365
- // WARNING: this is NOT concurrency safe. Please only call this method one at a time.
72366
- getNextBatchForSubmission: async (limit) => {
72367
- const assets = await client.imAssets.findMany({
72368
- where: {
72369
- mintingStatus: null
72370
- },
72371
- take: limit
72372
- });
72373
- const assetIds = assets.map((asset) => asset.id);
72374
- await client.imAssets.updateMany({
72375
- where: {
72376
- id: {
72377
- in: assetIds
72378
- }
72379
- },
72380
- data: {
72381
- mintingStatus: 'submitting'
72382
- }
72383
- });
72384
- const updatedAssets = await client.imAssets.findMany({
72385
- where: {
72386
- id: {
72387
- in: assetIds
72388
- }
72389
- }
72390
- });
72391
- return updatedAssets.map((asset) => ({
72392
- id: asset.id,
72393
- contract_address: asset.contractAddress,
72394
- wallet_address: asset.ownerAddress,
72395
- asset_id: asset.assetId,
72396
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72397
- owner_address: asset.ownerAddress,
72398
- tried_count: asset.triedCount,
72399
- amount: asset.amount || null,
72400
- token_id: asset.tokenId || null,
72401
- }));
72402
- },
72403
- updateMintingStatusToSubmitted: async (ids) => {
72404
- await client.imAssets.updateMany({
72405
- where: {
72406
- id: {
72407
- in: ids
72408
- }
72409
- },
72410
- data: {
72411
- mintingStatus: 'submitted'
72412
- }
72413
- });
72414
- },
72415
- syncMintingStatus: async (submittedMintRequest) => {
72416
- // First, attempt to retrieve the existing asset
72417
- const existingAsset = await client.imAssets.findUnique({
72418
- where: {
72419
- im_assets_uindex: {
72420
- assetId: submittedMintRequest.assetId,
72421
- contractAddress: submittedMintRequest.contractAddress,
72422
- },
72423
- }
72424
- });
72425
- // Check if the asset exists and the condition for updating is met
72426
- if (existingAsset && (existingAsset.lastImtblZkevmMintRequestUpdatedId === null
72427
- || existingAsset.lastImtblZkevmMintRequestUpdatedId < submittedMintRequest.imtblZkevmMintRequestUpdatedId)) {
72428
- // Perform update if the existing record's lastImtblZkevmMintRequestUpdatedId is less than the new one or is null
72429
- await client.imAssets.update({
72430
- where: {
72431
- im_assets_uindex: {
72432
- assetId: submittedMintRequest.assetId,
72433
- contractAddress: submittedMintRequest.contractAddress,
72434
- },
72435
- },
72436
- data: {
72437
- ownerAddress: submittedMintRequest.ownerAddress,
72438
- tokenId: submittedMintRequest.tokenId,
72439
- mintingStatus: submittedMintRequest.status,
72440
- metadataId: submittedMintRequest.metadataId,
72441
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72442
- error: submittedMintRequest.error,
72443
- amount: submittedMintRequest.amount || null
72444
- }
72445
- });
72446
- }
72447
- else if (!existingAsset) {
72448
- // Perform insert if no existing record is found
72449
- await client.imAssets.create({
72450
- data: {
72451
- assetId: submittedMintRequest.assetId,
72452
- contractAddress: submittedMintRequest.contractAddress,
72453
- ownerAddress: submittedMintRequest.ownerAddress,
72454
- tokenId: submittedMintRequest.tokenId,
72455
- mintingStatus: submittedMintRequest.status,
72456
- metadataId: submittedMintRequest.metadataId,
72457
- lastImtblZkevmMintRequestUpdatedId: submittedMintRequest.imtblZkevmMintRequestUpdatedId,
72458
- error: submittedMintRequest.error,
72459
- amount: submittedMintRequest.amount || null
72460
- }
72461
- });
72462
- }
72463
- // If existing asset does not meet the update condition, do nothing
72464
- },
72465
- updateMintingStatusToSubmissionFailed: async (ids) => {
72466
- await client.imAssets.updateMany({
72467
- where: {
72468
- id: {
72469
- in: ids
72470
- }
72471
- },
72472
- data: {
72473
- mintingStatus: 'submission_failed'
72474
- }
72475
- });
72476
- },
72477
- markAsConflict: async (assetIds, contractAddress) => {
72478
- await client.imAssets.updateMany({
72479
- where: {
72480
- assetId: {
72481
- in: assetIds // Targets assets where assetId is in the provided list
72482
- },
72483
- contractAddress // Additional condition for contract address
72484
- },
72485
- data: {
72486
- mintingStatus: 'conflicting' // Set the new status
72487
- }
72488
- });
72489
- },
72490
- resetMintingStatus: async (ids) => {
72491
- await client.imAssets.updateMany({
72492
- where: {
72493
- id: {
72494
- in: ids // Condition to match ids
72495
- }
72496
- },
72497
- data: {
72498
- mintingStatus: null // Setting minting_status to null
72499
- }
72500
- });
72501
- },
72502
- // this method is not concurrency safe
72503
- markForRetry: async (ids) => {
72504
- // Retrieve the current values of tried_count for the specified ids
72505
- const assets = await client.imAssets.findMany({
72506
- where: {
72507
- id: {
72508
- in: ids
72509
- }
72510
- },
72511
- select: {
72512
- id: true,
72513
- triedCount: true // Assuming the field is named triedCount
72514
- }
72515
- });
72516
- // Update each asset with the new tried_count and nullify minting_status
72517
- for (const asset of assets) {
72518
- await client.imAssets.update({
72519
- where: {
72520
- id: asset.id
72521
- },
72522
- data: {
72523
- mintingStatus: null,
72524
- triedCount: asset.triedCount + 1
72525
- }
72526
- });
72527
- }
72528
- },
72529
- getMintingRequest: async (contractAddress, referenceId) => {
72530
- // Retrieve the asset from the database based on contract_address and asset_id
72531
- const asset = await client.imAssets.findFirst({
72532
- where: {
72533
- contractAddress,
72534
- assetId: referenceId
72535
- }
72536
- });
72537
- if (!asset) {
72538
- return null;
72539
- }
72540
- return {
72541
- asset_id: asset.assetId,
72542
- contract_address: asset.contractAddress,
72543
- id: asset.id,
72544
- metadata: asset.metadata ? JSON.parse(asset.metadata) : null,
72545
- owner_address: asset.ownerAddress,
72546
- tried_count: asset.triedCount,
72547
- wallet_address: asset.ownerAddress,
72548
- amount: asset.amount || null
72549
- };
72550
- }
72551
- };
72552
- };
72553
-
72554
- // TODO: expose metrics
72555
- // - submitting status count, conflicting status count
72556
- // - failed events count
72557
- const recordMint = async (mintingPersistence, mintRequest) => {
72558
- trackRecordMint();
72559
- mintingPersistence.recordMint(mintRequest);
72560
- };
72561
- const defaultMintingDelay = 1000;
72562
- // This function can be called in different node process and will run in parallel to mint assets.
72563
- // Each process will NOT mint the same asset.
72564
- // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
72565
- // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
72566
- const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
72567
- trackSubmitMintingRequests();
72568
- let mintingResponse;
72569
- // eslint-disable-next-line no-constant-condition
72570
- while (true) {
72571
- await new Promise((resolve) => {
72572
- setTimeout(resolve, defaultMintingDelay);
72573
- });
72574
- let batchSize = Math.min(mintingResponse?.imx_remaining_mint_requests
72575
- ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
72576
- : defaultBatchSize, defaultBatchSize);
72577
- if (batchSize === 0
72578
- && mintingResponse
72579
- && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
72580
- logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
72581
- continue;
72582
- }
72583
- if (batchSize === 0) {
72584
- logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
72585
- mintingResponse = undefined;
72586
- batchSize = defaultBatchSize;
72587
- }
72588
- // get mints to be submitted
72589
- const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
72590
- if (pendingMints.length === 0) {
72591
- logger.info('no assets to mint');
72592
- continue;
72593
- }
72594
- // chunk assets by every 100 assets. every chunk should all be for the same contract address.
72595
- const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
72596
- if (acc.length === 0) {
72597
- return [{ contractAddress: row.contract_address, assets: [row] }];
72598
- }
72599
- const lastBatch = acc[acc.length - 1];
72600
- if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
72601
- return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
72602
- }
72603
- return [...acc, { contractAddress: row.contract_address, assets: [row] }];
72604
- }, []);
72605
- // submit minting request for each contract address in parallel
72606
- const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
72607
- const mintingRequest = {
72608
- chainName,
72609
- contractAddress,
72610
- createMintRequestRequest: {
72611
- assets: assets.map((row) => ({
72612
- reference_id: row.asset_id,
72613
- owner_address: row.owner_address,
72614
- metadata: row.metadata,
72615
- token_id: row.token_id,
72616
- amount: row.amount ? `${row.amount}` : null,
72617
- })),
72618
- },
72619
- };
72620
- try {
72621
- const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
72622
- logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
72623
- // update minting status to submitted
72624
- await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
72625
- return response;
72626
- }
72627
- catch (e) {
72628
- logger.error(e);
72629
- trackError(e);
72630
- if (e.code === 'CONFLICT_ERROR'
72631
- && e.details?.id === 'reference_id') {
72632
- try {
72633
- // mark the assets as conflicting, so that we don't send them again.
72634
- await mintingPersistence.markAsConflict(e.details.values, contractAddress);
72635
- // remove non conflicting assets status so that they can be retried.
72636
- await mintingPersistence.resetMintingStatus(assets
72637
- .map(({ id }) => id)
72638
- .filter((id) => !e.details.values.includes(id)));
72639
- }
72640
- catch (e2) {
72641
- logger.error(e2);
72642
- trackError(e);
72643
- }
72644
- }
72645
- else {
72646
- // separate assets into "need to be retied" and "exceeded max number of tries."
72647
- const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
72648
- if (tried_count < maxNumberOfTries) {
72649
- acc.assetsToRetry.push(id);
72650
- }
72651
- else {
72652
- acc.assetsExceededMaxNumberOfTries.push(id);
72653
- }
72654
- return acc;
72655
- }, {
72656
- assetsToRetry: [],
72657
- assetsExceededMaxNumberOfTries: [],
72658
- });
72659
- // remove all assets status so that they can be retried.
72660
- await mintingPersistence.markForRetry(assetsToRetry);
72661
- // mark assets that have exceeded the max number of tries as submission_failed
72662
- await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
72663
- }
72664
- return e;
72665
- }
72666
- }));
72667
- mintingResponse = mintingResults
72668
- .reverse()
72669
- .find((r) => r.status === 'fulfilled')?.value;
72670
- }
72671
- };
72672
- const processMint = async (mintingPersistence, event, logger = console) => {
72673
- trackProcessMint();
72674
- if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
72675
- logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
72676
- return;
72677
- }
72678
- const referenceId = event.data.reference_id;
72679
- if (!referenceId) {
72680
- throw new Error('reference_id not found in webhook event');
72681
- }
72682
- const contractAddress = event.data.contract_address;
72683
- if (!contractAddress) {
72684
- throw new Error('contract_address not found in webhook event');
72685
- }
72686
- if (event.data.status === 'failed') {
72687
- logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
72688
- }
72689
- const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
72690
- if (!mintReq) {
72691
- logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
72692
- }
72693
- const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
72694
- if (!ownerAddress) {
72695
- logger.error('owner_address missing');
72696
- throw new Error('owner_address missing');
72697
- }
72698
- await mintingPersistence.syncMintingStatus({
72699
- tokenId: event.data.token_id,
72700
- status: event.data.status,
72701
- assetId: referenceId,
72702
- contractAddress,
72703
- ownerAddress,
72704
- metadataId: event.data.metadata_id,
72705
- imtblZkevmMintRequestUpdatedId: event.event_id,
72706
- error: event.data.error ? JSON.stringify(event.data.error) : null,
72707
- amount: event.data.amount || null,
72708
- });
72709
- };
72710
-
72711
- const noopHandlers = {
72712
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
72713
- zkevmMintRequestUpdated: async (event) => { }
72714
- };
72715
- class MintingBackendModule {
72716
- baseConfig;
72717
- persistence;
72718
- blockchainDataClient;
72719
- logger;
72720
- constructor(config) {
72721
- this.baseConfig = config.baseConfig;
72722
- this.persistence = config.persistence;
72723
- this.logger = config.logger || console;
72724
- this.blockchainDataClient = new BlockchainData({
72725
- baseConfig: config.baseConfig
72726
- });
72727
- setEnvironment(this.baseConfig.environment);
72728
- if (this.baseConfig.publishableKey) {
72729
- setPublishableApiKey(this.baseConfig.publishableKey);
72730
- }
72731
- }
72732
- async recordMint(mintRequest) {
72733
- await recordMint(this.persistence, mintRequest);
72734
- }
72735
- async submitMintingRequests(config) {
72736
- await submitMintingRequests(this.persistence, this.blockchainDataClient, config);
72737
- }
72738
- async processMint(body, otherHandlers = noopHandlers) {
72739
- await handle(body, this.baseConfig.environment, {
72740
- zkevmMintRequestUpdated: async (event) => {
72741
- await processMint(this.persistence, event, this.logger);
72742
- if (otherHandlers.zkevmMintRequestUpdated) {
72743
- otherHandlers.zkevmMintRequestUpdated(event);
72744
- }
72745
- }
72746
- });
72747
- }
72748
- }
72749
- if (typeof process !== 'undefined' && process.on) {
72750
- try {
72751
- process.on('uncaughtExceptionMonitor', trackUncaughtException);
72752
- }
72753
- catch {
72754
- // ignore
72755
- }
72756
- }
72757
-
72758
- var minting_backend = /*#__PURE__*/Object.freeze({
72759
- __proto__: null,
72760
- MintingBackendModule: MintingBackendModule,
72761
- mintingPersistencePg: mintingPersistence$1,
72762
- mintingPersistencePrismaSqlite: mintingPersistence,
72763
- processMint: processMint,
72764
- recordMint: recordMint,
72765
- submitMintingRequests: submitMintingRequests
72766
- });
72767
-
72768
72028
  exports.blockchainData = blockchain_data;
72769
72029
  exports.checkout = checkout;
72770
72030
  exports.config = config;
72771
- exports.mintingBackend = minting_backend;
72772
72031
  exports.orderbook = orderbook;
72773
72032
  exports.passport = passport;
72774
- exports.webhook = webhook;
72775
72033
  exports.x = x;