UNPKG

@tenderly/sdk

Version:
1,256 lines (1,232 loc) 43.4 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __objRest = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols) for (var prop of __getOwnPropSymbols(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) target[prop] = source[prop]; } return target; }; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // lib/errors/GeneralError.ts var GeneralError = class extends Error { constructor({ id, message, slug, data }) { super(message); __publicField(this, "id"); __publicField(this, "message"); __publicField(this, "slug"); __publicField(this, "data"); this.id = id; this.message = message; this.slug = slug; this.data = data; } static handle(error) { if (error instanceof Error) throw error; throw new Error(JSON.stringify(error)); } }; __name(GeneralError, "GeneralError"); // lib/errors/Error.types.ts import { isAxiosError } from "axios"; var isTenderlyAxiosError = /* @__PURE__ */ __name((error) => { var _a, _b, _c; return isAxiosError(error) && !!(((_b = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.error) && ((_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status)); }, "isTenderlyAxiosError"); // lib/errors/ApiError.ts var ApiError = class extends GeneralError { constructor(_a) { var _b = _a, { status } = _b, error = __objRest(_b, ["status"]); super(error); __publicField(this, "status"); this.status = status; this.name = "ApiError"; } static handle(error) { if (isTenderlyAxiosError(error)) { throw new ApiError(__spreadValues({ status: error.response.status }, error.response.data.error)); } } }; __name(ApiError, "ApiError"); // lib/errors/BytecodeMismatchError.ts var BytecodeMismatchError = class extends GeneralError { constructor(message, data) { super({ message, id: "local_error", slug: "bytecode_mismatch_error", data }); this.name = "BytecodeMismatchError"; } }; __name(BytecodeMismatchError, "BytecodeMismatchError"); // lib/errors/CompilationError.ts var CompilationError = class extends GeneralError { constructor(message, data) { super({ message, id: "local_error", slug: "compilation_error", data }); this.name = "CompilationError"; } }; __name(CompilationError, "CompilationError"); // lib/errors/EncodingError.ts var EncodingError = class extends GeneralError { constructor(error) { super(error); this.name = "EncodingError"; } }; __name(EncodingError, "EncodingError"); // lib/errors/Error.handlerRegistry.ts var errorHandlers = [ ApiError, GeneralError ]; // lib/errors/InvalidArgumentsError.ts var InvalidArgumentsError = class extends GeneralError { constructor(message) { super({ id: "local_error", message, slug: "invalid_arguments" }); this.name = "InvalidArgumentsError"; } }; __name(InvalidArgumentsError, "InvalidArgumentsError"); // lib/errors/InvalidResponseError.ts var InvalidResponseError = class extends GeneralError { constructor(message) { super({ id: "local_error", message, slug: "invalid_response" }); this.name = "InvalidResponseError"; } }; __name(InvalidResponseError, "InvalidResponseError"); // lib/errors/NotFoundError.ts var NotFoundError = class extends GeneralError { constructor(message) { super({ message, id: "local_error", slug: "resource_not_found" }); this.name = "NotFoundError"; } }; __name(NotFoundError, "NotFoundError"); // lib/errors/UnexpectedVerificationError.ts var UnexpectedVerificationError = class extends GeneralError { constructor(message) { super({ message, id: "local_error", slug: "unexpected_verification_error" }); this.name = "UnexpectedVerificationError"; } }; __name(UnexpectedVerificationError, "UnexpectedVerificationError"); // lib/errors/index.ts function handleError(error) { errorHandlers.forEach((handler) => handler.handle(error)); throw error; } __name(handleError, "handleError"); // lib/repositories/contracts/contracts.repository.ts function mapContractResponseToContractModel(contractResponse) { const retVal = { address: contractResponse.contract.address, network: Number.parseInt(contractResponse.contract.network_id) }; if (contractResponse.display_name) { retVal.displayName = contractResponse.display_name; } if (contractResponse.tags) { retVal.tags = contractResponse.tags.map(({ tag }) => tag); } return retVal; } __name(mapContractResponseToContractModel, "mapContractResponseToContractModel"); function mapContractModelToContractRequest(contract) { return { address: contract.address, network_id: `${contract.network}`, display_name: contract.displayName }; } __name(mapContractModelToContractRequest, "mapContractModelToContractRequest"); var ContractRepository = class { constructor({ apiProvider, configuration }) { __publicField(this, "apiV1"); __publicField(this, "apiV2"); __publicField(this, "configuration"); this.apiV1 = apiProvider.getApiClient({ version: "v1" }); this.apiV2 = apiProvider.getApiClient({ version: "v2" }); this.configuration = configuration; } /** * Get a contract by address if it exists in the Tenderly's instances' project * @param address - The address of the contract * @returns The contract object in a plain format * @example * const contract = await tenderly.contracts.get('0x1234567890'); */ get(address) { return __async(this, null, function* () { var _a; try { const result = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, { "addresses[]": [ address ], "networkIDs[]": [ `${this.configuration.network}` ], "types[]": [ "contract", "unverified_contract" ] }); if (!((_a = result.data) == null ? void 0 : _a.accounts) || !result.data.accounts[0]) { throw new NotFoundError(`Contract with address ${address} not found`); } return mapContractResponseToContractModel(result.data.accounts[0]); } catch (error) { handleError(error); } }); } /** * Add a contract to the Tenderly's instances' project * @param address - The address of the contract * @param contractData - The data of the contract * @returns The contract object in a plain format * @example * const contract = await tenderly.contracts.add('0x1234567890'); * // or * const contract = await tenderly.contracts.add('0x1234567890', { displayName: 'MyContract' }); */ add(_0) { return __async(this, arguments, function* (address, contractData = {}) { try { yield this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /address `, mapContractModelToContractRequest(__spreadValues({ address, network: this.configuration.network }, contractData))); return this.get(address); } catch (error) { handleError(error); } }); } /** * Remove a contract from the Tenderly's instances' project * @param address - The address of the contract * @returns The contract object in a plain format * @example * await tenderly.contracts.remove('0x1234567890'); */ remove(address) { return __async(this, null, function* () { try { yield this.apiV1.delete(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /contract/${this.configuration.network}/${address} `); } catch (error) { handleError(error); } }); } /** * Update a contract in the Tenderly's instances' project * @param address - The address of the contract * @param payload - The data of the contract * @returns The contract object in a plain format * @example * const contract = await tenderly.contracts.update('0x1234567890', { displayName: 'MyContract' }); * // or * const contract = await tenderly.contracts.update('0x1234567890', { tags: ['my-tag'] }); * // or * const contract = await tenderly.contracts.update('0x1234567890', { * displayName: 'MyContract', * appendTags: ['my-tag'] * }); * // or * const contract = await tenderly.contracts.update('0x1234567890', { appendTags: ['my-tag'] }); */ update(address, payload) { return __async(this, null, function* () { var _a; try { let promiseArray = (_a = payload.appendTags) == null ? void 0 : _a.map((tag) => this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /tag `, { contract_ids: [ `eth:${this.configuration.network}:${address}` ], tag })); promiseArray || (promiseArray = []); if (payload.displayName) { promiseArray.push(this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /contract/${this.configuration.network}/${address} /rename `, { display_name: payload.displayName })); } yield Promise.all(promiseArray); return yield this.get(address); } catch (error) { handleError(error); } }); } getAll() { return __async(this, null, function* () { try { const wallets = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, { "types[]": "contract" }); return wallets.data.accounts.map(mapContractResponseToContractModel); } catch (error) { handleError(error); } }); } /** * Get all contracts in the Tenderly's instances' project * @param queryObject - The query object * @returns The contract objects in a plain format * @example * const contracts = await tenderly.contracts.getBy(); * const contracts = await tenderly.contracts.getBy({ * tags: ['my-tag'], * displayName: ['MyContract'] * }); */ getBy() { return __async(this, arguments, function* (queryObject = {}) { var _a, _b; try { const queryParams = this.buildQueryParams(queryObject); const contracts = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, __spreadProps(__spreadValues({}, queryParams), { "types[]": "contract" })); if ((_b = (_a = contracts == null ? void 0 : contracts.data) == null ? void 0 : _a.accounts) == null ? void 0 : _b.length) { return contracts.data.accounts.map(mapContractResponseToContractModel); } else { return []; } } catch (error) { handleError(error); } }); } buildQueryParams(queryObject = {}) { const queryParams = { "networkIDs[]": `${this.configuration.network}` }; if (queryObject.displayNames && queryObject.displayNames.filter((x) => !!x).length > 0) { queryParams["display_names[]"] = queryObject.displayNames; } if (queryObject.tags && queryObject.tags.filter((x) => !!x).length > 0) { queryParams["tags[]"] = queryObject.tags; } return queryParams; } /**Verifies a contract on Tenderly by submitting a verification request with * the provided address and verification details. * @param {string} address - The address of the contract to be verified. * @param {VerificationRequest} verificationRequest - Details of the verification request. * @returns {Promise<TenderlyContract>} - A Promise that resolves to a TenderlyContract * object representing the verified contract. */ verify(address, verificationRequest) { return __async(this, null, function* () { if (!this._isFullyQualifiedContractName(verificationRequest.contractToVerify)) { throw new Error( // eslint-disable-next-line max-len `The contract name '${verificationRequest.contractToVerify}' is not a fully qualified name. Please use the fully qualified name (e.g. path/to/file.sol:ContractName)` ); } try { const payload = { contracts: [ { compiler: this._repackLibraries(verificationRequest.solc), sources: this._mapSolcSourcesToTenderlySources(verificationRequest.solc.sources), networks: { [this.configuration.network]: { address } }, contractToVerify: verificationRequest.contractToVerify } ] }; const response = yield this.apiV1.post(verificationRequest.config.mode === "private" ? `/accounts/${this.configuration.accountName}/projects/${this.configuration.projectName}/contracts/verify` : "/public/contracts/verify", payload); const verificationResp = response.data; if (verificationResp.compilation_errors) { throw new CompilationError("There has been a compilation error while trying to verify contracts.", verificationResp.compilation_errors); } if (!verificationResp.results || !verificationResp.results[0]) { throw new UnexpectedVerificationError( // eslint-disable-next-line max-len "There has been an unexpected verification error during the verification process. Please check your contract's source code and try again." ); } if (verificationResp.results[0].bytecode_mismatch_error) { throw new BytecodeMismatchError("There has been a bytecode mismatch error while trying to verify contracts.", verificationResp.results[0].bytecode_mismatch_error); } return this.add(address); } catch (error) { handleError(error); } }); } _mapSolcSourcesToTenderlySources(sources) { const tenderlySources = {}; Object.entries(sources).forEach(([path, source]) => { tenderlySources[path] = { code: source.content }; }); return tenderlySources; } _repackLibraries(solcConfig) { var _a; const tenderlySolcConfig = this._copySolcConfigToTenderlySolcConfig(solcConfig); const solcConfigSettings = solcConfig.settings; if (!solcConfigSettings.libraries) { return tenderlySolcConfig; } const libraries = {}; for (const [fileName, libVal] of Object.entries(solcConfigSettings.libraries)) { for (const [libName, libAddress] of Object.entries(libVal)) { libraries[fileName] = { addresses: __spreadProps(__spreadValues({}, (_a = libraries == null ? void 0 : libraries[fileName]) == null ? void 0 : _a.addresses), { [libName]: libAddress }) }; } } tenderlySolcConfig.settings.libraries = libraries; return tenderlySolcConfig; } _isFullyQualifiedContractName(contractName) { const pattern = /^(.+)\.sol:([a-zA-Z_][a-zA-Z_0-9]*)$/; return pattern.test(contractName); } _copySolcConfigToTenderlySolcConfig(solcConfig) { const _a = solcConfig.settings, { libraries: _ } = _a, settings = __objRest(_a, ["libraries"]); return { version: solcConfig.version, settings }; } }; __name(ContractRepository, "ContractRepository"); // lib/repositories/wallets/wallets.repository.ts function getContractFromResponse(contractResponse) { const walletDetails = contractResponse.account || contractResponse.contract; return { address: walletDetails.address, network: Number.parseInt(walletDetails.network_id) }; } __name(getContractFromResponse, "getContractFromResponse"); function mapWalletResponseToWalletModel(walletResponse) { const retVal = getContractFromResponse(walletResponse); if (walletResponse.tags) { retVal.tags = walletResponse.tags.map(({ tag }) => tag); } if (walletResponse.display_name) { retVal.displayName = walletResponse.display_name; } return retVal; } __name(mapWalletResponseToWalletModel, "mapWalletResponseToWalletModel"); function mapWalletModelToWalletRequest(wallet) { return { address: wallet.address, display_name: wallet.displayName || "", network_ids: [ `${wallet.network}` ] }; } __name(mapWalletModelToWalletRequest, "mapWalletModelToWalletRequest"); var WalletRepository = class { constructor({ apiProvider, configuration }) { __publicField(this, "apiV1"); __publicField(this, "apiV2"); __publicField(this, "configuration"); this.apiV1 = apiProvider.getApiClient({ version: "v1" }); this.apiV2 = apiProvider.getApiClient({ version: "v2" }); this.configuration = configuration; } /** * Get a contract by address if it exists in the Tenderly's instances' project * @param address - The address of the contract * @returns The contract object in a plain format * @example * const contract = await tenderly.contracts.get('0x1234567890'); */ get(address) { return __async(this, null, function* () { try { const { data } = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, { "addresses[]": [ address.toLowerCase() ], "networkIDs[]": [ `${this.configuration.network}` ], "types[]": [ "wallet" ] }); if (!(data == null ? void 0 : data.accounts) || !data.accounts[0]) { throw new NotFoundError(`Wallet with address ${address} not found`); } return mapWalletResponseToWalletModel(data.accounts[0]); } catch (error) { handleError(error); } }); } /** * Add a wallet to the project. * @param address - The address of the wallet * @param walletData - Values to populate the displayName * @returns The wallet object in a plain format * @example * const wallet = await tenderly.contracts.add('0x1234567890', { displayName: 'My Wallet' }); */ add(address, walletData) { return __async(this, null, function* () { try { const { data } = yield this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /wallet `, __spreadValues({ return_existing: true }, mapWalletModelToWalletRequest(__spreadValues({ address: address.toLowerCase(), network: this.configuration.network }, walletData)))); if (!data[0]) { throw new InvalidResponseError(`Invalid response received while trying to create a wallet ${address}`); } return mapWalletResponseToWalletModel(data[0]); } catch (error) { handleError(error); } }); } /** * Remove a wallet from the Tenderly instances' project. * @param address - The address of the wallet * @returns {Promise<void>} * @example * await tenderly.contracts.remove('0x1234567890'); */ remove(address) { return __async(this, null, function* () { try { yield this.apiV1.delete(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /contracts `, { account_ids: [ `eth:${this.configuration.network}:${address}` ] }); } catch (error) { handleError(error); } }); } /** * Update a wallet's displayName and/or tags. * @param address - The address of the wallet * @param payload - The values to update the wallet with * @returns The wallet object in a plain format * @example * const wallet = await tenderly.contracts.update('0x1234567890', { * displayName: 'My Wallet', * appendTags: ['my-tag'] * }); * const wallet = await tenderly.contracts.update('0x1234567890', { displayName: 'My Wallet' }); * const wallet = await tenderly.contracts.update('0x1234567890', { appendTags: ['my-tag'] }); */ update(address, payload) { return __async(this, null, function* () { var _a; try { let promiseArray = (_a = payload.appendTags) == null ? void 0 : _a.map((tag) => this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /tag `, { contract_ids: [ `eth:${this.configuration.network}:${address}` ], tag })); promiseArray || (promiseArray = []); if (payload.displayName) { promiseArray.push(this.apiV1.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /contract/${this.configuration.network}/${address} /rename `, { display_name: payload.displayName })); } yield Promise.all(promiseArray); return this.get(address); } catch (error) { handleError(error); } }); } /** * Get all wallets in the Tenderly instances' project. * */ getAll() { return __async(this, null, function* () { var _a, _b; try { const wallets = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, { "types[]": "wallet" }); if ((_b = (_a = wallets == null ? void 0 : wallets.data) == null ? void 0 : _a.accounts) == null ? void 0 : _b.length) { return wallets.data.accounts.map(mapWalletResponseToWalletModel); } else { return []; } } catch (error) { handleError(error); } }); } /** * Get all wallets in the Tenderly instances' project. * @param queryObject - The query object to filter the wallets with * @returns An array of wallets in a plain format * @example * const wallets = await tenderly.contracts.getBy(); * const wallets = await tenderly.contracts.getBy({ * displayName: 'My Wallet', * tags: ['my-tag'] * }); */ getBy() { return __async(this, arguments, function* (queryObject = {}) { var _a, _b; try { const queryParams = this.buildQueryParams(queryObject); const wallets = yield this.apiV2.get(` /accounts/${this.configuration.accountName} /projects/${this.configuration.projectName} /accounts `, __spreadProps(__spreadValues({}, queryParams), { "types[]": "wallet" })); if ((_b = (_a = wallets == null ? void 0 : wallets.data) == null ? void 0 : _a.accounts) == null ? void 0 : _b.length) { return wallets.data.accounts.map(mapWalletResponseToWalletModel); } else { return []; } } catch (error) { handleError(error); } }); } buildQueryParams(queryObject = {}) { const queryParams = { "networkIDs[]": `${this.configuration.network}` }; if (queryObject.displayNames && queryObject.displayNames.filter((x) => !!x).length > 0) { queryParams["display_names[]"] = queryObject.displayNames; } if (queryObject.tags && queryObject.tags.filter((x) => !!x).length > 0) { queryParams["tags[]"] = queryObject.tags; } return queryParams; } }; __name(WalletRepository, "WalletRepository"); // lib/executors/Simulator.ts function mapToSimulationResult(simpleSimulationResponse) { var _a; return { status: simpleSimulationResponse.status, gasUsed: simpleSimulationResponse.gas_used, cumulativeGasUsed: simpleSimulationResponse.cumulative_gas_used, blockNumber: simpleSimulationResponse.block_number, type: simpleSimulationResponse.type, logsBloom: simpleSimulationResponse.logs_bloom, logs: simpleSimulationResponse.logs, trace: (_a = simpleSimulationResponse.trace) == null ? void 0 : _a.map((trace) => __spreadProps(__spreadValues({}, trace), { error_messages: trace.error_reason })) }; } __name(mapToSimulationResult, "mapToSimulationResult"); var Simulator = class { constructor({ apiProvider, configuration }) { __publicField(this, "apiV1"); __publicField(this, "configuration"); __publicField(this, "apiV2"); this.apiV1 = apiProvider.getApiClient({ version: "v1" }); this.apiV2 = apiProvider.getApiClient({ version: "v2" }); this.configuration = configuration; } mapStateOverridesToEncodeStateRequest(overrides) { return { networkID: `${this.configuration.network}`, stateOverrides: Object.keys(overrides).map((contractAddress) => { var _a; const cAddress = contractAddress.toLowerCase(); return { [cAddress]: (_a = overrides[contractAddress]) == null ? void 0 : _a.state }; }).map((addresses) => { const mappedOverrides = {}; Object.keys(addresses).forEach((address) => { mappedOverrides[address] = { value: addresses[address] }; }); return mappedOverrides; }).reduce((acc, curr) => __spreadValues(__spreadValues({}, acc), curr)) }; } mapToEncodedOverrides(stateOverrides) { return Object.keys(stateOverrides).map((address) => address.toLowerCase()).reduce((acc, curr) => { var _a; acc[curr] = (_a = stateOverrides[curr]) == null ? void 0 : _a.value; return acc; }, {}); } replaceJSONOverridesWithEncodedOverrides(overrides, encodedStateOverrides) { if (!overrides) { return null; } return Object.keys(overrides).map((address) => address.toLowerCase()).reduce((acc, curr) => { var _a, _b, _c, _d, _e, _f; const currentOverride = {}; if (encodedStateOverrides && encodedStateOverrides[curr]) { currentOverride.state_diff = encodedStateOverrides[curr]; } if ((_a = overrides[curr]) == null ? void 0 : _a.nonce) { currentOverride.nonce = (_b = overrides[curr]) == null ? void 0 : _b.nonce; } if ((_c = overrides[curr]) == null ? void 0 : _c.code) { currentOverride.code = (_d = overrides[curr]) == null ? void 0 : _d.code; } if ((_e = overrides[curr]) == null ? void 0 : _e.balance) { currentOverride.balance = (_f = overrides[curr]) == null ? void 0 : _f.balance; } return __spreadProps(__spreadValues({}, acc), { [curr]: currentOverride }); }, {}); } buildSimulationBundleRequest(transactions, blockNumber, encodedOverrides) { return { network_id: `${this.configuration.network}`, call_args: transactions.map((transaction) => ({ from: transaction.from, to: transaction.to, gas: transaction.gas, gas_price: transaction.gas_price, max_fee_per_gas: transaction.max_fee_per_gas, max_priority_fee_per_gas: transaction.max_priority_fee_per_gas, value: transaction.value, data: transaction.input, access_list: transaction.access_list })), block_number_or_hash: { blockNumber }, overrides: encodedOverrides }; } buildSimpleSimulationRequest(transaction, blockNumber, encodedOverrides) { return { network_id: `${this.configuration.network}`, call_args: { from: transaction.from, to: transaction.to, gas: transaction.gas, gas_price: transaction.gas_price, max_fee_per_gas: transaction.max_fee_per_gas, max_priority_fee_per_gas: transaction.max_priority_fee_per_gas, value: transaction.value, data: transaction.input, access_list: transaction.access_list }, block_number_or_hash: { blockNumber }, overrides: encodedOverrides }; } encodeOverrideRequest(overrides) { return __async(this, null, function* () { const encodedStateOverrides = yield this.encodeStateOverrides(overrides); return this.replaceJSONOverridesWithEncodedOverrides(overrides, encodedStateOverrides); }); } encodeStateOverrides(overrides) { return __async(this, null, function* () { if (!overrides) { return null; } const encodingRequest = this.mapStateOverridesToEncodeStateRequest(overrides); try { const { data: encodedStates } = yield this.apiV1.post(`/account/${this.configuration.accountName} /project/${this.configuration.projectName} /contracts/encode-states `, encodingRequest); return this.mapToEncodedOverrides(encodedStates.stateOverrides); } catch (error) { if (isTenderlyAxiosError(error)) { throw new EncodingError(error.response.data.error); } throw error; } }); } executeSimpleSimulationRequest(simulationRequest) { return __async(this, null, function* () { const { data } = yield this.apiV2.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /simulations/simulate `, simulationRequest); return data; }); } executeSimulationBundleRequest(simulationRequest) { return __async(this, null, function* () { const { data } = yield this.apiV2.post(` /account/${this.configuration.accountName} /project/${this.configuration.projectName} /simulations/simulate/bundle `, simulationRequest); return data; }); } /** * Simulates a transaction by encoding overrides, building a request body, and executing a simulation request. * @async * @function * @param {SimulationParameters} simulationParams - Parameters for the transaction simulation. * @param {object} simulationParams.transaction - The transaction object to be simulated. * @param {number} simulationParams.blockNumber - The block number for the simulation. * @param {object} simulationParams.overrides - Overrides for the transaction simulation. * @returns {Promise<SimulationOutput>} - A Promise that resolves to a simulation output. */ simulateTransaction(_0) { return __async(this, arguments, function* ({ transaction, blockNumber, overrides }) { try { const encodedOverrides = yield this.encodeOverrideRequest(overrides); const simulationRequest = this.buildSimpleSimulationRequest(transaction, blockNumber, encodedOverrides); const simpleSimulationResponse = yield this.executeSimpleSimulationRequest(simulationRequest); return mapToSimulationResult(simpleSimulationResponse); } catch (error) { handleError(error); } }); } /** * Simulates a bundle of transactions by encoding overrides, building a request body, * and executing a simulation bundle request. * @async * @function * @param {SimulationBundleDetails} params - Details of the transaction bundle simulation. * @param {object[]} params.transactions - An array of transaction objects to be simulated. * @param {object} params.overrides - Overrides for the transaction bundle simulation. * @param {number} params.blockNumber - The block number for the simulation bundle. * @returns {Promise<SimulationOutput[]>} - A Promise that resolves to an array of simulation result objects. */ simulateBundle(_0) { return __async(this, arguments, function* ({ transactions, overrides, blockNumber }) { try { const encodedOverrides = yield this.encodeOverrideRequest(overrides); const simulationBundleRequest = this.buildSimulationBundleRequest(transactions, blockNumber, encodedOverrides); const simulationBundleResponse = yield this.executeSimulationBundleRequest(simulationBundleRequest); return simulationBundleResponse.simulations.map((simulation) => mapToSimulationResult(simulation)); } catch (error) { handleError(error); } }); } }; __name(Simulator, "Simulator"); // lib/core/ApiClient.ts import axios from "axios"; // lib/constants.ts var TENDERLY_API_BASE_URL = "https://api.tenderly.co"; // lib/sdkVersion.ts var TENDERLY_SDK_VERSION = "0.3.1"; // lib/core/ApiClient.ts var ApiClient = class { /** * @param apiKey API key to be used for the requests. * Can be generated in the Tenderly dashboard: https://dashboard.tenderly.co/account/authorization * @param version API version to be used for the requests. Defaults to 'v1' */ constructor({ apiKey, version = "v1" }) { __publicField(this, "api"); this.api = axios.create({ baseURL: `${TENDERLY_API_BASE_URL}/api/${version}`, headers: { "Content-Type": "application/json", "X-Access-Key": apiKey, "X-User-Agent": `@tenderly/sdk-js/${TENDERLY_SDK_VERSION}` } }); } /** * * @param path url path to the resource * @param params url query params * @returns Promise with AxiosResponse that * contains the response data model with a type of a given generic parameter */ get(path, params) { return this.api.get(path.replace(/\s/g, ""), { params }); } /** * * @param path url path to the resource * @param data data to be sent to the server. Type of data expected can be specified with a second generic parameter * @returns Promise with AxiosResponse that * contains the response data model with a type of a second generic parameter */ post(path, data) { return this.api.post(path.replace(/\s/g, ""), data); } /** * * @param path url path to the resource * @param data data to be sent to the server in order to update the model. * Type of data expected can be specified with a second generic parameter * @param params url query params * @returns Promise with AxiosResponse that contains the response data model with a type of a second generic parameter */ put(path, data, params) { return __async(this, null, function* () { return this.api.put(path.replace(/\s/g, ""), data, { params }); }); } /** * @param path url path to the resource * @param data data to be sent to the server in order to remove the model. * @returns AxiosResponse */ delete(path, data) { return __async(this, null, function* () { return this.api.delete(path.replace(/\s/g, ""), { data }); }); } }; __name(ApiClient, "ApiClient"); // lib/core/ApiClientProvider.ts var ApiClientProvider = class { constructor({ apiKey }) { __publicField(this, "apiKey"); __publicField(this, "apiClients", {}); this.apiKey = apiKey; } getApiClient({ version }) { if (!this.apiClients[version]) { this.apiClients[version] = new ApiClient({ version, apiKey: this.apiKey }); } return this.apiClients[version]; } }; __name(ApiClientProvider, "ApiClientProvider"); __publicField(ApiClientProvider, "instance"); // lib/core/Tenderly.ts var Tenderly = class { /** * The main class of the Tenderly SDK * Instantiate this class with your config, and you're ready to go * @example * const tenderly = new Tenderly({ * accountName: 'my-account', * projectName: 'my-project', * accessKey: 'my-access-key', * network: Network.Mainnet, * }) */ constructor(configuration) { __publicField(this, "configuration"); // public readonly api: ApiClient; /** * Contract repository - used for managing contracts on your project */ __publicField(this, "contracts"); /** * Wallet repository - used for managing wallets on your project */ __publicField(this, "wallets"); /** * Simulator - used for simulating transactions */ __publicField(this, "simulator"); __publicField(this, "apiClientProvider"); this.checkConfiguration(configuration); this.configuration = configuration; this.apiClientProvider = new ApiClientProvider({ apiKey: configuration.accessKey }); this.simulator = new Simulator({ apiProvider: this.apiClientProvider, configuration }); this.contracts = new ContractRepository({ apiProvider: this.apiClientProvider, configuration }); this.wallets = new WalletRepository({ apiProvider: this.apiClientProvider, configuration }); } /** * Create a new Tenderly instance with the provided configuration override * @param configurationOverride - The configuration override * @returns The new Tenderly instance * @example * const tenderly = new Tenderly({ * accountName: 'my-account', * projectName: 'my-project', * ); */ with(configurationOverride) { return new Tenderly(__spreadValues(__spreadValues({}, this.configuration), configurationOverride)); } checkConfiguration(configuration) { if (!configuration.accessKey) { throw new InvalidArgumentsError("Missing access key."); } if (!configuration.accountName) { throw new InvalidArgumentsError("Missing account name."); } if (!configuration.projectName) { throw new InvalidArgumentsError("Missing project name."); } if (!configuration.network) { throw new InvalidArgumentsError("Missing network."); } } }; __name(Tenderly, "Tenderly"); // lib/types.ts var Network; (function(Network2) { Network2[Network2["MAINNET"] = 1] = "MAINNET"; Network2[Network2["OPTIMISTIC"] = 10] = "OPTIMISTIC"; Network2[Network2["RSK"] = 30] = "RSK"; Network2[Network2["RSK_TESTNET"] = 31] = "RSK_TESTNET"; Network2[Network2["BINANCE"] = 56] = "BINANCE"; Network2[Network2["RIALTO_BINANCE"] = 97] = "RIALTO_BINANCE"; Network2[Network2["GNOSIS_CHAIN"] = 100] = "GNOSIS_CHAIN"; Network2[Network2["BOB_SEPOLIA"] = 111] = "BOB_SEPOLIA"; Network2[Network2["POLYGON"] = 137] = "POLYGON"; Network2[Network2["FRAXTAL"] = 252] = "FRAXTAL"; Network2[Network2["BOBA_ETHEREUM"] = 288] = "BOBA_ETHEREUM"; Network2[Network2["WORLDCHAIN"] = 480] = "WORLDCHAIN"; Network2[Network2["MODE_SEPOLIA"] = 919] = "MODE_SEPOLIA"; Network2[Network2["LISK"] = 1135] = "LISK"; Network2[Network2["MOONBEAM"] = 1284] = "MOONBEAM"; Network2[Network2["MOONRIVER"] = 1285] = "MOONRIVER"; Network2[Network2["MOONBASE_ALPHA"] = 1287] = "MOONBASE_ALPHA"; Network2[Network2["SEI_ATLANTIC_2"] = 1328] = "SEI_ATLANTIC_2"; Network2[Network2["SEI_PACIFIC_1"] = 1329] = "SEI_PACIFIC_1"; Network2[Network2["FRAXTAL_HOLESKY"] = 2522] = "FRAXTAL_HOLESKY"; Network2[Network2["MORPH_HOLESKY"] = 2810] = "MORPH_HOLESKY"; Network2[Network2["LISK_SEPOLIA"] = 4202] = "LISK_SEPOLIA"; Network2[Network2["GOLD"] = 4653] = "GOLD"; Network2[Network2["WORLDCHAIN_SEPOLIA"] = 4801] = "WORLDCHAIN_SEPOLIA"; Network2[Network2["MANTLE"] = 5e3] = "MANTLE"; Network2[Network2["MANTLE_SEPOLIA"] = 5003] = "MANTLE_SEPOLIA"; Network2[Network2["ZETACHAIN"] = 7e3] = "ZETACHAIN"; Network2[Network2["ZETACHAIN_TESTNET"] = 7001] = "ZETACHAIN_TESTNET"; Network2[Network2["KINTO"] = 7887] = "KINTO"; Network2[Network2["POLYNOMIAL"] = 8008] = "POLYNOMIAL"; Network2[Network2["BASE"] = 8453] = "BASE"; Network2[Network2["BOBA_BINANCE_RIALTO"] = 9728] = "BOBA_BINANCE_RIALTO"; Network2[Network2["INTERVAL_TESTNET"] = 11069] = "INTERVAL_TESTNET"; Network2[Network2["IMMUTABLE"] = 13371] = "IMMUTABLE"; Network2[Network2["IMMUTABLE_TESTNET"] = 13473] = "IMMUTABLE_TESTNET"; Network2[Network2["HOLESKY"] = 17e3] = "HOLESKY"; Network2[Network2["UNREAL"] = 18233] = "UNREAL"; Network2[Network2["CONCRETE_TESTNET"] = 18291] = "CONCRETE_TESTNET"; Network2[Network2["BOBA_SEPOLIA"] = 28882] = "BOBA_SEPOLIA"; Network2[Network2["APECHAIN_CURTIS"] = 33111] = "APECHAIN_CURTIS"; Network2[Network2["APECHAIN"] = 33139] = "APECHAIN"; Network2[Network2["MODE"] = 34443] = "MODE"; Network2[Network2["ARBITRUM_ONE"] = 42161] = "ARBITRUM_ONE"; Network2[Network2["ARBITRUM_NOVA"] = 42170] = "ARBITRUM_NOVA"; Network2[Network2["AVALANCHE_FUJI"] = 43113] = "AVALANCHE_FUJI"; Network2[Network2["AVALANCHE"] = 43114] = "AVALANCHE"; Network2[Network2["BOBA_BINANCE"] = 56288] = "BOBA_BINANCE"; Network2[Network2["LINEA_SEPOLIA"] = 59141] = "LINEA_SEPOLIA"; Network2[Network2["LINEA"] = 59144] = "LINEA"; Network2[Network2["BOB"] = 60808] = "BOB"; Network2[Network2["POLYGON_AMOY"] = 80002] = "POLYGON_AMOY"; Network2[Network2["POLYNOMIAL_SEPOLIA"] = 80008] = "POLYNOMIAL_SEPOLIA"; Network2[Network2["BLAST"] = 81457] = "BLAST"; Network2[Network2["BASE_SEPOLIA"] = 84532] = "BASE_SEPOLIA"; Network2[Network2["REAL"] = 111188] = "REAL"; Network2[Network2["TAIKO"] = 167e3] = "TAIKO"; Network2[Network2["TAIKO_HEKLA"] = 167009] = "TAIKO_HEKLA"; Network2[Network2["ARBITRUM_SEPOLIA"] = 421614] = "ARBITRUM_SEPOLIA"; Network2[Network2["ZORA"] = 7777777] = "ZORA"; Network2[Network2["SEPOLIA"] = 11155111] = "SEPOLIA"; Network2[Network2["OPTIMISTIC_SEPOLIA"] = 11155420] = "OPTIMISTIC_SEPOLIA"; Network2[Network2["ZORA_SEPOLIA"] = 999999999] = "ZORA_SEPOLIA"; })(Network || (Network = {})); // lib/helpers.ts function getEnvironmentVariables() { return process.env; } __name(getEnvironmentVariables, "getEnvironmentVariables"); export { ApiError, BytecodeMismatchError, CompilationError, EncodingError, GeneralError, InvalidArgumentsError, InvalidResponseError, Network, NotFoundError, Tenderly, UnexpectedVerificationError, getEnvironmentVariables, handleError };