@imtbl/sdk 1.33.0 → 1.34.0-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
@@ -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.33.0';
164
+ const SDK_VERSION$1 = '1.34.0-alpha';
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.33.0' };
14191
+ const defaultHeaders$2 = { 'x-sdk-version': 'ts-immutable-sdk-1.34.0-alpha' };
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.33.0',
14263
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-1.34.0-alpha',
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.33.0' };
14737
+ const defaultHeaders = { 'x-sdk-version': 'ts-immutable-sdk-1.34.0-alpha' };
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.33.0',
14776
+ sdkVersion: 'ts-immutable-sdk-1.34.0-alpha',
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);
@@ -32246,12 +32247,12 @@ function assertOptions(options, schema, allowUnknown) {
32246
32247
  }
32247
32248
  }
32248
32249
 
32249
- var validator = {
32250
+ var validator$1 = {
32250
32251
  assertOptions,
32251
32252
  validators: validators$1
32252
32253
  };
32253
32254
 
32254
- const validators = validator.validators;
32255
+ const validators = validator$1.validators;
32255
32256
 
32256
32257
  /**
32257
32258
  * Create a new instance of Axios
@@ -32292,7 +32293,7 @@ class Axios {
32292
32293
  const {transitional, paramsSerializer, headers} = config;
32293
32294
 
32294
32295
  if (transitional !== undefined) {
32295
- validator.assertOptions(transitional, {
32296
+ validator$1.assertOptions(transitional, {
32296
32297
  silentJSONParsing: validators.transitional(validators.boolean),
32297
32298
  forcedJSONParsing: validators.transitional(validators.boolean),
32298
32299
  clarifyTimeoutError: validators.transitional(validators.boolean)
@@ -32305,7 +32306,7 @@ class Axios {
32305
32306
  serialize: paramsSerializer
32306
32307
  };
32307
32308
  } else {
32308
- validator.assertOptions(paramsSerializer, {
32309
+ validator$1.assertOptions(paramsSerializer, {
32309
32310
  encode: validators.function,
32310
32311
  serialize: validators.function
32311
32312
  }, true);
@@ -57934,7 +57935,7 @@ const flattenProperties = (properties) => {
57934
57935
  };
57935
57936
 
57936
57937
  // WARNING: DO NOT CHANGE THE STRING BELOW. IT GETS REPLACED AT BUILD TIME.
57937
- const SDK_VERSION = '1.33.0';
57938
+ const SDK_VERSION = '1.34.0-alpha';
57938
57939
  const getFrameParentDomain = () => {
57939
57940
  if (isNode()) {
57940
57941
  return '';
@@ -63156,7 +63157,7 @@ const IMMUTABLE_ZKVEM_GAS_OVERRIDES = {
63156
63157
  maxPriorityFeePerGas: BigNumber$1.from(10e9),
63157
63158
  };
63158
63159
 
63159
- const SDK_VERSION_MARKER = '1.33.0';
63160
+ const SDK_VERSION_MARKER = '1.34.0-alpha';
63160
63161
  // This SDK version is replaced by the `yarn build` command ran on the root level
63161
63162
  const globalPackageVersion = () => SDK_VERSION_MARKER;
63162
63163
 
@@ -68686,4 +68687,316 @@ var x = /*#__PURE__*/Object.freeze({
68686
68687
  sandbox: sandbox
68687
68688
  });
68688
68689
 
68689
- export { blockchain_data as blockchainData, checkout, config, orderbook, passport, x };
68690
+ const validator = new MessageValidator();
68691
+ const allowedTopicArnPrefix = {
68692
+ [Environment$1.PRODUCTION]: 'arn:aws:sns:us-east-2:362750628221:',
68693
+ [Environment$1.SANDBOX]: 'arn:aws:sns:us-east-2:783421985614:'
68694
+ };
68695
+ const init = async (body, env, handlers) => {
68696
+ const msg = await new Promise((resolve, reject) => {
68697
+ validator.validate(body, (err, message) => {
68698
+ if (err) {
68699
+ return reject(err);
68700
+ }
68701
+ // check for topic arn prefix
68702
+ if (!msg.TopicArn.startsWith(allowedTopicArnPrefix[env])) {
68703
+ throw new Error('Invalid topic arn');
68704
+ }
68705
+ if (message?.Type === 'SubscriptionConfirmation') {
68706
+ fetch(message.SubscribeURL).then(() => {
68707
+ resolve(message);
68708
+ }).catch((e) => {
68709
+ reject(e);
68710
+ });
68711
+ }
68712
+ return resolve(message);
68713
+ });
68714
+ });
68715
+ if (msg.Type === 'Notification') {
68716
+ const event = JSON.parse(msg.Message);
68717
+ switch (event.event_name) {
68718
+ case 'imtbl_zkevm_mint_request_updated':
68719
+ await handlers.zkevmMintRequestUpdated(event);
68720
+ break;
68721
+ default:
68722
+ if (handlers.others) {
68723
+ await handlers.others(event);
68724
+ }
68725
+ break;
68726
+ }
68727
+ }
68728
+ };
68729
+
68730
+ var webhook = /*#__PURE__*/Object.freeze({
68731
+ __proto__: null,
68732
+ init: init
68733
+ });
68734
+
68735
+ /* eslint-disable no-console */
68736
+ /* eslint-disable global-require */
68737
+ let optionalPackage = null;
68738
+ let pgClient = null;
68739
+ try {
68740
+ optionalPackage = require('pg');
68741
+ pgClient = new optionalPackage.Pool({
68742
+ user: process.env.PG_USER || 'postgres',
68743
+ host: process.env.PG_HOST || 'localhost',
68744
+ database: process.env.PG_DB_NAME || 'nullus',
68745
+ password: process.env.PG_PASSWORD || 'postgres',
68746
+ port: parseInt(process.env.PG_PORT || '5432', 10) || 5432,
68747
+ });
68748
+ }
68749
+ catch (error) {
68750
+ console.error('pg is not installed. Please install it by running `npm install pg`');
68751
+ optionalPackage = null;
68752
+ }
68753
+ const client = pgClient;
68754
+
68755
+ const mintingPersistence = {
68756
+ recordMint: async (request) => {
68757
+ const r = await client.query(`
68758
+ INSERT INTO im_assets (asset_id, contract_address, owner_address, metadata)
68759
+ VALUES ($1, $2, $3, $4) ON CONFLICT (asset_id) DO NOTHING;
68760
+ `, [request.asset_id, request.contract_address, request.owner_address, request.metadata]);
68761
+ if (r.rowCount === 0) {
68762
+ throw new Error('Duplicated mint');
68763
+ }
68764
+ },
68765
+ getNextBatchForSubmission: async (limit) => {
68766
+ const res = await client.query(`
68767
+ UPDATE im_assets SET minting_status = 'submitting' WHERE minting_status IS NULL and id in (
68768
+ select id from im_assets where minting_status is null limit $1 for update skip locked
68769
+ ) returning *;
68770
+ `, [limit]);
68771
+ return res.rows;
68772
+ },
68773
+ updateMintingStatusToSubmitted: async (ids) => {
68774
+ await client.query(`
68775
+ UPDATE im_assets SET minting_status = $2 WHERE id = ANY($1);
68776
+ `, [ids, 'submitted']);
68777
+ },
68778
+ syncMintingStatus: async (submittedMintRequest) => {
68779
+ // doing a upsert just in case the row has not been created yet
68780
+ await client.query(`
68781
+ INSERT INTO im_assets (
68782
+ asset_id,
68783
+ contract_address,
68784
+ owner_address,
68785
+ token_id,
68786
+ minting_status,
68787
+ metadata_id,
68788
+ last_imtbl_zkevm_mint_request_updated_id,
68789
+ error
68790
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (asset_id, contract_address)
68791
+ DO UPDATE SET
68792
+ owner_address = $3,
68793
+ token_id = $4,
68794
+ minting_status = $5,
68795
+ metadata_id = $6,
68796
+ last_imtbl_zkevm_mint_request_updated_id = $7,
68797
+ error = $8
68798
+ where (
68799
+ im_assets.last_imtbl_zkevm_mint_request_updated_id < $7 OR
68800
+ im_assets.last_imtbl_zkevm_mint_request_updated_id is null
68801
+ );
68802
+ `, [
68803
+ submittedMintRequest.assetId,
68804
+ submittedMintRequest.contractAddress,
68805
+ submittedMintRequest.ownerAddress,
68806
+ submittedMintRequest.tokenId,
68807
+ submittedMintRequest.status,
68808
+ submittedMintRequest.metadataId,
68809
+ submittedMintRequest.imtblZkevmMintRequestUpdatedId,
68810
+ submittedMintRequest.error
68811
+ ]);
68812
+ },
68813
+ markAsConflict: async (assetIds, contractAddress) => {
68814
+ await client.query(`
68815
+ UPDATE im_assets
68816
+ SET minting_status = 'conflicting'
68817
+ WHERE asset_id = ANY($1)
68818
+ AND contract_address = $2;
68819
+ `, [assetIds, contractAddress]);
68820
+ },
68821
+ resetMintingStatus: async (ids) => {
68822
+ await client.query(`
68823
+ UPDATE im_assets SET minting_status = null WHERE id = ANY($1) and contract_address = $2;
68824
+ `, [ids]);
68825
+ },
68826
+ markForRetry: async (ids) => {
68827
+ await client.query(`
68828
+ UPDATE im_assets
68829
+ SET minting_status = null, tried_count = tried_count + 1 WHERE id = ANY($1);
68830
+ `, [ids]);
68831
+ },
68832
+ updateMintingStatusToSubmissionFailed: async (ids) => {
68833
+ await client.query(`
68834
+ UPDATE im_assets SET minting_status = 'submission_failed' WHERE id = ANY($1);
68835
+ `, [ids]);
68836
+ },
68837
+ getMintingRequest: async (contractAddress, referenceId) => {
68838
+ const res = await client.query(`
68839
+ SELECT * FROM im_assets WHERE contract_address = $1 and asset_id = $2;
68840
+ `, [contractAddress, referenceId]);
68841
+ return res.rows[0];
68842
+ }
68843
+ };
68844
+
68845
+ // TODO: expose metrics
68846
+ // - submitting status count, conflicting status count
68847
+ // - failed events count
68848
+ const recordMint = async (mintingPersistence, mintRequest) => {
68849
+ mintingPersistence.recordMint(mintRequest);
68850
+ };
68851
+ const defaultMintingDelay = 1000;
68852
+ // This function can be called in different node process and will run in parallel to mint assets.
68853
+ // Each process will NOT mint the same asset.
68854
+ // Monitor your database to see if parallel processes are saturating the database CPU and triggering excessive vacuuming.
68855
+ // default batch size will be treated as 100 when it exceeds 100 because minting API has a limit of 100 assets per request.
68856
+ const submitMintingRequests = async (mintingPersistence, blockchainDataSDKClient, { defaultBatchSize = 1000, chainName = 'imtbl-zkevm-testnet', maxNumberOfTries = 3, }, logger = console) => {
68857
+ let mintingResponse;
68858
+ // eslint-disable-next-line no-constant-condition
68859
+ while (true) {
68860
+ await new Promise((resolve) => {
68861
+ setTimeout(resolve, defaultMintingDelay);
68862
+ });
68863
+ let batchSize = Math.min(mintingResponse
68864
+ ? parseInt(mintingResponse.imx_remaining_mint_requests, 10)
68865
+ : defaultBatchSize, defaultBatchSize);
68866
+ if (batchSize === 0
68867
+ && mintingResponse
68868
+ && new Date(mintingResponse.imx_mint_requests_limit_reset) > new Date()) {
68869
+ logger.info(`minting limit reached, waiting for reset at ${mintingResponse?.imx_mint_requests_limit_reset}`);
68870
+ continue;
68871
+ }
68872
+ if (batchSize === 0) {
68873
+ logger.info(`minting limit has been reset, use default batch size: ${defaultBatchSize}`);
68874
+ mintingResponse = undefined;
68875
+ batchSize = defaultBatchSize;
68876
+ }
68877
+ // get mints to be submitted
68878
+ const pendingMints = await mintingPersistence.getNextBatchForSubmission(batchSize);
68879
+ if (pendingMints.length === 0) {
68880
+ logger.info('no assets to mint');
68881
+ continue;
68882
+ }
68883
+ // chunk assets by every 100 assets. every chunk should all be for the same contract address.
68884
+ const chunkedAssets = pendingMints.sort((a, b) => (a.contract_address > b.contract_address ? 1 : -1)).reduce((acc, row) => {
68885
+ if (acc.length === 0) {
68886
+ return [{ contractAddress: row.contract_address, assets: [row] }];
68887
+ }
68888
+ const lastBatch = acc[acc.length - 1];
68889
+ if (lastBatch.contractAddress === row.contract_address && lastBatch.assets.length < 100) {
68890
+ return [...acc.slice(0, -1), { ...lastBatch, assets: [...lastBatch.assets, row] }];
68891
+ }
68892
+ return [...acc, { contractAddress: row.contract_address, assets: [row] }];
68893
+ }, []);
68894
+ // submit minting request for each contract address in parallel
68895
+ const mintingResults = await Promise.allSettled(chunkedAssets.map(async ({ contractAddress, assets }) => {
68896
+ const mintingRequest = {
68897
+ chainName,
68898
+ contractAddress,
68899
+ createMintRequestRequest: {
68900
+ assets: assets.map((row) => ({
68901
+ reference_id: row.asset_id,
68902
+ owner_address: row.owner_address,
68903
+ metadata: row.metadata,
68904
+ })),
68905
+ },
68906
+ };
68907
+ try {
68908
+ const response = await blockchainDataSDKClient.createMintRequest(mintingRequest);
68909
+ logger.info(`mintingResponse: ${JSON.stringify(response, null, 2)}`);
68910
+ // update minting status to submitted
68911
+ await mintingPersistence.updateMintingStatusToSubmitted(assets.map(({ id }) => id));
68912
+ return response;
68913
+ }
68914
+ catch (e) {
68915
+ logger.error(e);
68916
+ if (e.code === 'CONFLICT_ERROR'
68917
+ && e.details?.id === 'reference_id') {
68918
+ try {
68919
+ // mark the assets as conflicting, so that we don't send them again.
68920
+ await mintingPersistence.markAsConflict(e.details.values, contractAddress);
68921
+ // remove non conflicting assets status so that they can be retried.
68922
+ await mintingPersistence.resetMintingStatus(assets
68923
+ .map(({ id }) => id)
68924
+ .filter((id) => !e.details.values.includes(id)));
68925
+ }
68926
+ catch (e2) {
68927
+ logger.error(e2);
68928
+ }
68929
+ }
68930
+ else {
68931
+ // separate assets into "need to be retied" and "exceeded max number of tries."
68932
+ const { assetsToRetry, assetsExceededMaxNumberOfTries } = assets.reduce((acc, { tried_count = 0, id }) => {
68933
+ if (tried_count < maxNumberOfTries) {
68934
+ acc.assetsToRetry.push(id);
68935
+ }
68936
+ else {
68937
+ acc.assetsExceededMaxNumberOfTries.push(id);
68938
+ }
68939
+ return acc;
68940
+ }, {
68941
+ assetsToRetry: [],
68942
+ assetsExceededMaxNumberOfTries: [],
68943
+ });
68944
+ // remove all assets status so that they can be retried.
68945
+ await mintingPersistence.markForRetry(assetsToRetry);
68946
+ // mark assets that have exceeded the max number of tries as submission_failed
68947
+ await mintingPersistence.updateMintingStatusToSubmissionFailed(assetsExceededMaxNumberOfTries);
68948
+ }
68949
+ return e;
68950
+ }
68951
+ }));
68952
+ mintingResponse = mintingResults
68953
+ .reverse()
68954
+ .find((r) => r.status === 'fulfilled')?.value;
68955
+ }
68956
+ };
68957
+ const processMint = async (mintingPersistence, event, logger = console) => {
68958
+ if (event.event_name !== 'imtbl_zkevm_mint_request_updated') {
68959
+ logger.info(`${event.event_name} is not imtbl_zkevm_mint_request_updated, skip.`);
68960
+ return;
68961
+ }
68962
+ const referenceId = event.data.reference_id;
68963
+ if (!referenceId) {
68964
+ throw new Error('reference_id not found in webhook event');
68965
+ }
68966
+ const contractAddress = event.data.contract_address;
68967
+ if (!contractAddress) {
68968
+ throw new Error('contract_address not found in webhook event');
68969
+ }
68970
+ if (event.data.status === 'failed') {
68971
+ logger.error(`mint failed: ${JSON.stringify(event.data, null, 2)}`);
68972
+ }
68973
+ const mintReq = await mintingPersistence.getMintingRequest(contractAddress, referenceId);
68974
+ if (!mintReq) {
68975
+ logger.info(`minting request not found in the database, ${JSON.stringify(event.data)}`);
68976
+ }
68977
+ const ownerAddress = mintReq?.wallet_address || event.data.owner_address;
68978
+ if (!ownerAddress) {
68979
+ logger.error('owner_address missing');
68980
+ throw new Error('owner_address missing');
68981
+ }
68982
+ await mintingPersistence.syncMintingStatus({
68983
+ tokenId: event.data.token_id,
68984
+ status: event.data.status,
68985
+ assetId: referenceId,
68986
+ contractAddress,
68987
+ ownerAddress,
68988
+ metadataId: event.data.metadata_id,
68989
+ imtblZkevmMintRequestUpdatedId: event.event_id,
68990
+ error: event.data.error ? JSON.stringify(event.data.error) : null,
68991
+ });
68992
+ };
68993
+
68994
+ var minting_backend = /*#__PURE__*/Object.freeze({
68995
+ __proto__: null,
68996
+ mintingPersistencePg: mintingPersistence,
68997
+ processMint: processMint,
68998
+ recordMint: recordMint,
68999
+ submitMintingRequests: submitMintingRequests
69000
+ });
69001
+
69002
+ export { blockchain_data as blockchainData, checkout, config, minting_backend as mintingBackend, orderbook, passport, webhook, x };