How to use customProtocols method in mountebank

Best JavaScript code snippet using mountebank

customiser.js

Source:customiser.js Github

copy

Full Screen

1import React, { Component } from "react";2import Web3 from "web3";3import Authereum from "authereum";4import Modal from "react-bootstrap/Modal";5import Web3Modal from "web3modal";6import "bootstrap/dist/css/bootstrap.min.css";7import {8 flashBorrow,9 flashPayback,10 genericDSAOperations,11 swap,12 openMakerVault,13 makerGenericOperations,14 transferAsset,15 withdrawDai,16 depositDai17} from "../dsa/utils";18import {19 genericResolver,20 makerVaultResolver,21 makerDSRResolver,22 getBalances23} from "../dsa/resolvers";24import "./Customiser.css";25const DSA = require("dsa-sdk");26class App extends Component {27 constructor(props) {28 super(props);29 this.state = {30 color: "#85f7ff",31 buttonText: "Connect",32 initialtext1: "Select Asset",33 showError: false,34 showWarning: false,35 showSuccess: false,36 showResolver: false,37 showMakerResolver: false,38 showTokenResolver: false,39 errMessage: "",40 shortnerAddress: "",41 successMessage: "",42 resolverData: {},43 vaultStats: {},44 dsrStats: {},45 balances: {},46 shareholders: [{}],47 operationConfig: {48 borrow: ["compound", "aave", "maker", "dydx"],49 deposit: ["compound", "aave", "maker", "dydx"],50 payback: ["compound", "aave", "maker", "dydx"],51 withdraw: ["compound", "aave", "maker", "dydx"],52 openVault: ["maker"],53 swap: ["oasis", "oneInch", "kyber", "curve"],54 flashBorrow: ["instapool"],55 flashPayback: ["instapool"],56 },57 regexp: /^[0-9](\.[0-9]+)?$/,58 makerVaultOptions: {59 ETH: "ETH-A",60 USDC: "USDC-A",61 },62 };63 }64 async componentWillMount() {65 this.showWarningModal();66 }67 async loadWeb3() {68 const providerOptions = {69 /* See Provider Options Section */70 authereum: {71 package: Authereum, // required72 },73 };74 const web3Modal = new Web3Modal({75 network: "mainnet", // optional76 cacheProvider: false, // optional77 providerOptions, // required78 });79 const provider = await web3Modal.connect();80 const web3 = new Web3(provider);81 this.setState({ web3 });82 }83 login = async () => {84 try {85 await this.loadWeb3();86 await this.loadBlockchainData();87 await this.showShortner()88 this.setState({ color: "#0ff279" });89 this.setState({ buttonText: this.state.shortnerAddress});90 } catch (err) {91 this.setState({ color: "#85f7ff", buttonText: "Try Again", errMessage: "Please select Mainnet in your wallet" });92 this.showErrorModal(); 93 }94 };95 async showShortner() {96 let address = this.state.dsaAddress.toString()97 address = address.substring(0,6)+ '......'+ address.substring(address.length -7, address.length -1)98 this.setState({shortnerAddress : address})99 }100 async loadBlockchainData() {101 // in browser with react102 const accounts = await this.state.web3.eth.getAccounts();103 this.setState({ account: accounts[0] });104 const dsa = new DSA(this.state.web3);105 this.setState({ dsa });106 // Getting Your DSA Address107 var existingDSAAddress = await dsa.getAccounts(this.state.account);108 if (existingDSAAddress.length === 0) {109 var newDsaAddress = await dsa.build({110 gasPrice: this.state.web3.utils.toWei("27", "gwei"),111 });112 }113 // change to this.state.account does this requires address as string?114 existingDSAAddress = await dsa.getAccounts(this.state.account);115 this.setState({ dsaAddress: existingDSAAddress[0].address });116 // Setting DSA Instance117 await dsa.setInstance(existingDSAAddress[0].id);118 }119 async customReciepeMaker(customProtocols, web3, dsa) {120 try {121 let spells = await dsa.Spell();122 for (let i = 0; i < customProtocols.length; i++) {123 if (customProtocols[i].protocol !== "maker") {124 // since the spell structure for maker connectors is different from others125 switch (customProtocols[i].name) {126 case "borrow":127 if (!customProtocols[i].amount)128 throw new Error("Amount Mandatory for Borrow");129 else130 spells = await genericDSAOperations(131 spells,132 customProtocols[i].protocol,133 "borrow",134 customProtocols[i].asset,135 customProtocols[i].amount136 );137 break;138 case "deposit":139 if (!customProtocols[i].amount)140 spells = await genericDSAOperations(141 spells,142 customProtocols[i].protocol,143 "deposit",144 customProtocols[i].asset,145 "-1"146 );147 else148 spells = await genericDSAOperations(149 spells,150 customProtocols[i].protocol,151 "deposit",152 customProtocols[i].asset,153 customProtocols[i].amount154 );155 break;156 case "withdraw":157 if (!customProtocols[i].amount)158 throw new Error("Amount Mandatory for Withdraw");159 else160 spells = await genericDSAOperations(161 spells,162 customProtocols[i].protocol,163 "withdraw",164 customProtocols[i].asset,165 customProtocols[i].amount166 );167 break;168 case "payback":169 if (!customProtocols[i].amount)170 spells = await genericDSAOperations(171 spells,172 customProtocols[i].protocol,173 "payback",174 customProtocols[i].asset,175 "-1"176 );177 else178 spells = await genericDSAOperations(179 spells,180 customProtocols[i].protocol,181 "payback",182 customProtocols[i].asset,183 customProtocols[i].amount184 );185 break;186 case "flashBorrow":187 if (!customProtocols[i].amount)188 throw new Error("Amount Mandatory for Flash Borrow");189 else190 spells = await flashBorrow(191 spells,192 customProtocols[i].asset,193 customProtocols[i].amount194 );195 break;196 case "flashPayback":197 spells = await flashPayback(spells, customProtocols[i].asset)198 break;199 case "swap":200 if (customProtocols[i].buyingTokenSymbol === customProtocols[i].sellingTokenSymbol)201 throw new Error("Cannot have both assets same");202 203 if (!customProtocols[i].amount)204 throw new Error("Swap Amount is mandatory");205 const slippage = 2;206 const amount = web3.utils.fromWei(customProtocols[i].amount, 'ether')207 const swapDetail = await dsa[customProtocols[i].protocol.toString()].getBuyAmount(208 customProtocols[i].buyingTokenSymbol,209 customProtocols[i].sellingTokenSymbol,210 amount,211 slippage212 );213 spells = await swap(214 spells,215 customProtocols[i].protocol,216 customProtocols[i].buyAddress,217 customProtocols[i].asset,218 customProtocols[i].amount,219 swapDetail.unitAmt220 );221 break;222 default:223 throw new Error("Invalid Operation");224 }225 } else {226 switch (customProtocols[i].name) {227 case "openVault":228 spells = await openMakerVault(229 spells,230 this.state.makerVaultOptions[231 customProtocols[i].sellingTokenSymbol232 ]233 );234 break;235 case "deposit":236 if (!customProtocols[i].vaultId) customProtocols[i].vaultId = 0;237 238 if (customProtocols[i].sellingTokenSymbol === "DAI") {239 spells = await depositDai(spells, customProtocols[i].amount)240 } else {241 spells = await makerGenericOperations(242 spells,243 "deposit",244 customProtocols[i].vaultId,245 customProtocols[i].amount246 );247 }248 249 break;250 case "borrow":251 if (!customProtocols[i].vaultId) customProtocols[i].vaultId = 0;252 spells = await makerGenericOperations(253 spells,254 "borrow",255 customProtocols[i].vaultId,256 customProtocols[i].amount257 );258 break;259 case "payback":260 if (!customProtocols[i].vaultId) customProtocols[i].vaultId = 0;261 spells = await makerGenericOperations(262 spells,263 "payback",264 customProtocols[i].vaultId,265 customProtocols[i].amount266 );267 break;268 case "withdraw":269 if (!customProtocols[i].vaultId) customProtocols[i].vaultId = 0;270 if (customProtocols[i].sellingTokenSymbol === "DAI") {271 spells = await withdrawDai(spells, customProtocols[i].amount)272 } else {273 spells = await makerGenericOperations(274 spells,275 "withdraw",276 customProtocols[i].vaultId,277 customProtocols[i].amount278 );279 }280 281 break;282 default:283 throw new Error("Invalid Operation");284 }285 }286 }287 var data = {288 spells: spells,289 };290 // For Simulation Testing on tenderly291 var gasLimit = await dsa.estimateCastGas(data).catch((err) => {292 this.setState({293 errMessage: "Transaction is likely to fail, Check you spells once!",294 });295 this.showErrorModal();296 });297 const tx = await dsa.cast({spells: spells})298 .catch((err) => {299 throw new Error("Transaction is likely to fail, Check you spells once!")300 });301 if (tx) {302 this.setState({303 successMessage: "https://etherscan.io/tx/" + tx304 });305 this.showSuccessModal();306 } 307 } catch (err) {308 this.setState({309 errMessage: err.message310 });311 this.showErrorModal(); 312 }313 }314 handleOperationChange = (idx) => (evt) => {315 this.state.shareholders[idx].name = evt.target.value;316 this.setState({ shareholders: this.state.shareholders });317 };318 handleProtocolChange = (idx) => (evt) => {319 this.state.shareholders[idx].protocol = evt.target.value;320 this.setState({ shareholders: this.state.shareholders });321 };322 handleAssetChange = (idx) => (evt) => {323 try {324 const assetInstance = evt.target.value.toLowerCase()325 this.state.shareholders[idx].asset = this.state.dsa.tokens.info[326 assetInstance327 ].address;328 this.state.shareholders[idx].sellingTokenSymbol = evt.target.value;329 this.setState({ shareholders: this.state.shareholders });330 } catch (err) {331 this.setState({ errMessage: "Connect your Metamask Wallet Once!" });332 this.showErrorModal(evt);333 }334 };335 handleBuyingAssetChange = (idx) => (evt) => {336 try {337 const assetInstance = evt.target.value.toLowerCase()338 this.state.shareholders[idx].buyAddress = this.state.dsa.tokens.info[339 assetInstance340 ].address;341 this.state.shareholders[idx].buyingTokenSymbol = evt.target.value;342 this.setState({ shareholders: this.state.shareholders });343 } catch (err) {344 this.setState({ errMessage: "Connect your Metamask Wallet First" });345 this.showErrorModal(evt);346 }347 };348 handleTransferAssetChange = (evt) => {349 try {350 const asset = evt.target.value.toLowerCase()351 const assetname = evt.target.value.toUpperCase()352 this.setState({ transferAssetSymbol: asset });353 this.setState({ initialtext1: assetname });354 } catch (err) {355 this.setState({ errMessage: "Connect your Metamask Wallet First" });356 this.showErrorModal(evt);357 }358 };359 handleAmountChange = (idx) => (evt) => {360 try {361 this.state.shareholders[idx].amount = this.state.web3.utils.toWei(362 evt.target.value,363 "ether"364 );365 this.setState({ shareholders: this.state.shareholders });366 } catch (err) {367 this.setState({ errMessage: "Connect your Metamask Wallet First" });368 this.showErrorModal(evt);369 }370 };371 handleDepositAmountChange = (evt) => {372 try {373 const depositAmount = this.state.web3.utils.toWei(374 evt.target.value,375 "ether"376 );377 this.setState({ depositAmount: evt.target.value });378 } catch (err) {379 this.setState({ errMessage: "Connect your Metamask Wallet First" });380 this.showErrorModal(evt);381 }382 };383 handleVaultIdChange = (idx) => (evt) => {384 this.state.shareholders[idx].vaultId = evt.target.value;385 this.setState({ shareholders: this.state.shareholders });386 };387 handleSubmit = (evt) => {388 evt.preventDefault();389 this.customReciepeMaker(390 this.state.shareholders,391 this.state.web3,392 this.state.dsa393 );394 };395 transferAssets = async (evt) => {396 try {397 evt.preventDefault();398 const result = await transferAsset(399 this.state.dsa,400 this.state.transferAssetSymbol,401 this.state.depositAmount402 );403 // for testing will change it soon404 this.setState({405 successMessage: "https://etherscan.io/tx/" + result,406 });407 this.showSuccessModal(evt);408 } catch (err) {409 this.setState({ errMessage: "Transaction Failed" });410 this.showErrorModal(evt);411 }412 };413 getUserPosition = (protocol) => async (evt) => {414 try {415 evt.preventDefault();416 const positionData = await genericResolver(417 this.state.dsa,418 protocol,419 this.state.dsaAddress420 );421 const filteredData = {};422 filteredData["eth"] = positionData["eth"];423 filteredData["dai"] = positionData["dai"];424 filteredData["usdc"] = positionData["usdc"];425 filteredData["liquidation"] = positionData["liquidation"];426 filteredData["status"] = positionData["status"];427 filteredData["totalBorrowInEth"] = positionData["totalBorrowInEth"];428 filteredData["totalSupplyInEth"] = positionData["totalSupplyInEth"];429 this.setState({ resolverData: filteredData });430 this.showResolverModal();431 } catch (err) {432 this.setState({ errMessage: "Please Connect your Wallet" });433 this.showErrorModal();434 }435 };436 getUserMakerPosition = async () => {437 try {438 let vaultStats = await makerVaultResolver(439 this.state.dsa,440 this.state.dsaAddress441 );442 const dsrStats = await makerDSRResolver(443 this.state.dsa,444 this.state.dsaAddress445 );446 this.setState({ vaultStats, dsrStats });447 this.showMakerResolverModal();448 } catch (err) {449 this.setState({ errMessage: "Please Connect your Wallet" });450 this.showErrorModal();451 }452 };453 getBalances = async () => {454 try {455 const balances = await getBalances(this.state.dsa, this.state.dsaAddress);456 this.setState({balances})457 this.showBalanceResolverModal();458 } catch (err) {459 this.setState({ errMessage: "Please Connect your Wallet" });460 this.showErrorModal();461 }462 }463 handleAddShareholder = () => {464 this.setState({465 shareholders: this.state.shareholders.concat([{}]),466 });467 };468 handleRemoveShareholder = (idx) => () => {469 this.setState({470 shareholders: this.state.shareholders.filter((s, sidx) => idx !== sidx),471 });472 };473 showErrorModal = (e) => {474 this.setState({475 showError: true,476 });477 };478 hideErrorModal = (e) => {479 this.setState({480 showError: false,481 });482 };483 showWarningModal = (e) => {484 this.setState({485 showWarning: true,486 });487 };488 hideWarningModal = (e) => {489 this.setState({490 showWarning: false,491 });492 };493 showSuccessModal = (e) => {494 this.setState({495 showSuccess: true,496 });497 };498 hideSuccessModal = (e) => {499 this.setState({500 showSuccess: false,501 });502 };503 showResolverModal = (e) => {504 this.setState({505 showResolver: true,506 });507 };508 hideResolverModal = (e) => {509 this.setState({510 showResolver: false,511 });512 };513 showMakerResolverModal = (e) => {514 this.setState({515 showMakerResolver: true,516 });517 };518 hideMakerResolverModal = (e) => {519 this.setState({520 showMakerResolver: false,521 });522 };523 showBalanceResolverModal = (e) => {524 this.setState({525 showBalanceResolverModal: true,526 });527 };528 hideBalanceResolverModal = (e) => {529 this.setState({530 showBalanceResolverModal: false,531 });532 };533 render() {534 const resolverNonObjectOptions = [535 "liquidation",536 "status",537 "totalBorrowInEth",538 "totalSupplyInEth",539 ];540 const tokensToRender = ["dai", "eth", "usdc"]541 const userRelatedResolverOptions = ["supply", "borrow"];542 let operatorOptions = Object.keys(this.state.operationConfig).map(543 (operation, index) => (544 <option key={operation.index} value={operation}>545 {operation}{" "}546 </option>547 )548 );549 const protocolList = this.state.operationConfig[550 this.state.operationSelected551 ];552 let protocolOptions;553 if (!protocolList) {554 protocolOptions = null;555 } else {556 protocolOptions = this.state.operationConfig[557 this.state.operationSelected558 ].map((protocol) => (559 <option key={protocol} value={protocol}>560 {protocol}{" "}561 </option>562 ));563 }564 return (565 <div>566 <nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">567 <div className="navbar-brand col-sm-3 col-md-2 mr-0">Dashboard</div>568 <button569 onClick={this.login}570 style={{571 backgroundColor: this.state.color,572 borderRadius: "7px",573 border: "None",574 }}575 >576 {this.state.buttonText}{" "}577 </button>578 </nav>579 <div id="container">580 <div className="content">581 <div className="container1">582 <div className="box1">583 <div className="box3">584 <div className="card card-3">585 <Modal586 show={this.state.showBalanceResolverModal}587 onHide={this.hideBalanceResolverModal}588 >589 <Modal.Header>590 <Modal.Title><b>Your DSA Balances</b></Modal.Title>591 </Modal.Header>592 {Object.keys(this.state.balances).map((balance) => tokensToRender.includes(balance) ? <Modal.Body> {balance} => {this.state.balances[balance]}</Modal.Body>: '')}593 <Modal.Footer>594 <button onClick={this.hideBalanceResolverModal}>Cancel</button>595 </Modal.Footer>{" "}596 </Modal>597 <Modal598 show={this.state.showMakerResolver}599 onHide={this.hideMakerResolverModal}600 >601 <Modal.Title><b>Your DSA Maker Vault Positions</b></Modal.Title>602 {Object.keys(this.state.vaultStats).map((vault) => (603 <Modal.Body>604 <b>{vault}</b>{" "}605 {Object.keys(this.state.vaultStats[vault]).map(606 (info) => (607 <p>608 {" "}609 {info} => {this.state.vaultStats[vault][info]}610 </p>611 )612 )}{" "}613 </Modal.Body>614 ))}615 <br></br>616 <Modal.Title><b>Your DSA Maker DSR Position</b></Modal.Title>617 {Object.keys(this.state.dsrStats).map((properties) => (618 <Modal.Body>619 <b>{properties}</b> =>{" "}620 {this.state.dsrStats[properties]}621 </Modal.Body>622 ))}623 <Modal.Footer>624 <button onClick={this.hideMakerResolverModal}>625 Cancel626 </button>627 </Modal.Footer>{" "}628 </Modal>629 <Modal630 show={this.state.showResolver}631 onHide={this.hideResolverModal}632 >633 <Modal.Header>634 <Modal.Title><b>Your DSA Position</b></Modal.Title>635 </Modal.Header>636 {Object.keys(this.state.resolverData).map((asset) =>637 !resolverNonObjectOptions.includes(asset) ? (638 <Modal.Body>639 <b>{asset}</b>{" "}640 {Object.keys(this.state.resolverData[asset]).map(641 (info) =>642 userRelatedResolverOptions.includes(info) ? (643 <p>644 {info} =>{" "}645 {this.state.resolverData[asset][info]}646 </p>647 ) : (648 <p></p>649 )650 )}{" "}651 </Modal.Body>652 ) : (653 <Modal.Body>654 <b>{asset}</b> => {this.state.resolverData[asset]}655 </Modal.Body>656 )657 )}658 <Modal.Footer>659 <button onClick={this.hideResolverModal}>Cancel</button>660 </Modal.Footer>{" "}661 </Modal>662 <Modal663 show={this.state.showSuccess}664 onHide={this.hideSuccessModal}665 >666 <Modal.Header>667 <Modal.Title><b>Successful Transaction</b></Modal.Title>668 </Modal.Header>669 <Modal.Body>670 <a href={this.state.successMessage}>671 Check Transaction672 </a>673 </Modal.Body>674 <Modal.Footer>675 <button onClick={this.hideSuccessModal}>Cancel</button>676 </Modal.Footer>{" "}677 </Modal>678 <Modal679 show={this.state.showWarning}680 onHide={this.hideWarningModal}681 >682 <Modal.Header>683 <Modal.Title><b>Warning</b></Modal.Title>684 </Modal.Header>685 <Modal.Body>686 Before creating your recipies make sure sure to Connect687 to your Wallet688 </Modal.Body>689 <Modal.Body>690 Make Sure the Asset that you will be using in your691 spells is available in your dsa, if not you can transfer692 </Modal.Body>693 <Modal.Body>694 If you want to edit a block of spell, then better to use the <b>-</b> button and create the particular spell again to avoid any trasaction failures due to spells695 </Modal.Body>696 <Modal.Footer>697 <button onClick={this.hideWarningModal}>Cancel</button>698 </Modal.Footer>{" "}699 </Modal>700 <Modal701 show={this.state.showError}702 onHide={this.hideErrorModal}703 >704 <Modal.Header>705 <Modal.Title><b>Error</b></Modal.Title>706 </Modal.Header>707 <Modal.Body>{this.state.errMessage}</Modal.Body>708 <Modal.Footer>709 <button onClick={this.hideErrorModal}>Cancel</button>710 </Modal.Footer>{" "}711 </Modal>712 <div className="box4">713 <form>714 <div>715 <div className="box6">716 <div className="custom-select2">717 <label className="new-label select-1">718 <span>{this.state.initialtext1}</span>719 </label>720 <select721 className="new-select"722 onChange={this.handleTransferAssetChange}723 >724 <option>Select Asset</option>725 <option>ETH</option>726 <option>DAI</option>727 <option>USDC</option>728 </select>729 </div>730 </div>731 </div>732 <div>733 <input734 type="number"735 onChange={this.handleDepositAmountChange}736 placeholder={`Amount`}737 />738 </div>739 <div>740 <button741 type="button"742 onClick={this.transferAssets}743 className="new-button1 shadow animate green"744 >745 Deposit746 </button>747 </div>748 </form>749 </div>750 </div>751 </div>752 <div className="box3">753 <div className="card card-4">754 <div className="box5">755 <div>756 <button757 type="button"758 className="new-button2 shadow animate red"759 onClick={this.getBalances}760 >761 Tokens762 </button>763 </div>764 <div>765 <button766 type="button"767 className="new-button2 shadow animate red"768 onClick={this.getUserPosition("aave")}769 >770 Aave771 </button>772 </div>773 <div>774 <button775 type="button"776 className="new-button2 shadow animate red"777 onClick={this.getUserMakerPosition}778 >779 Maker780 </button>781 </div>782 <div>783 <button784 type="button"785 className="new-button2 shadow animate red"786 onClick={this.getUserPosition("compound")}787 >788 Compound789 </button>790 </div>791 <div>792 <button793 type="button"794 className="new-button2 shadow animate red"795 onClick={this.getUserPosition("dydx")}796 >797 DyDx798 </button>799 </div>800 </div>801 </div>802 </div>803 </div>804 <div className="box2">805 <div class="gridcontainer">806 <div class="gridbody">807 <div class="gridcontent">808 <div className="box3">809 <form>810 {" "}811 {this.state.shareholders.map((shareholder, idx) => (812 <div>813 <div className="custom-select">814 <select815 className="select2"816 onChange={this.handleOperationChange(idx)}817 >818 <option value="" selected disabled>819 Select Operation820 </option>821 {operatorOptions}{" "}822 </select>823 </div>824 <div className="custom-select">825 <select826 className="select2"827 onChange={this.handleProtocolChange(idx)}828 >829 <option value="" selected disabled>830 Select Protocol831 </option>832 {shareholder.name &&833 this.state.operationConfig[834 shareholder.name835 ].map((protocol) => (836 <option value={protocol}>{protocol}</option>837 ))}{" "}838 </select></div>839 {shareholder.protocol === "maker" && (840 <div className="custom-select">841 <select842 className="select2"843 onChange={this.handleAssetChange(idx)}844 >845 <option value="" selected disabled>846 Select Asset847 </option>848 {shareholder.name !== "openVault" && (849 <option>DAI</option>850 )}851 {shareholder.name !== "payback" &&852 shareholder.name !== "borrow" && (853 <option>ETH</option>854 )}855 {shareholder.name !== "payback" &&856 shareholder.name !== "borrow" && (857 <option>USDC</option>858 )}859 </select>860 </div>861 )}862 {shareholder.protocol !== "maker" && (863 <div className="custom-select">864 <select865 className="select2"866 onChange={this.handleAssetChange(idx)}867 >868 <option value="" selected disabled>869 Select Asset870 </option>871 <option>DAI</option>872 <option>ETH</option>873 <option>USDC</option>874 </select>875 </div>876 )}877 {shareholder.name != "flashPayback" && shareholder.name != "openVault" && <input878 className="input2"879 type="number"880 placeholder={`Amount`}881 onChange={this.handleAmountChange(idx)}882 />}{" "}883 {shareholder.name == "swap" && (884 <div className="custom-select">885 <select886 className="select2"887 onChange={this.handleBuyingAssetChange(idx)}888 >889 <option value="" selected disabled>890 Buying Asset891 </option>892 <option>ETH</option>893 <option>DAI</option>894 <option>USDC</option>895 </select>896 </div>897 )}898 {shareholder.protocol == "maker" &&899 shareholder.name != "openVault" && (900 <input className="input2"901 type="number"902 placeholder={`Vault Id`}903 onChange={this.handleVaultIdChange(idx)}904 />905 )}906 <button907 type="button"908 onClick={this.handleRemoveShareholder(idx)}909 className="new-button3 shadow animate red2"910 >911 -912 </button>913 </div>914 ))}915 <button916 type="button"917 className="action-button shadow animate yellow"918 onClick={this.handleAddShareholder}919 >920 Add Block921 </button>922 <button923 type="button"924 className="action-button shadow animate green"925 onClick={this.handleSubmit}926 >927 Execute928 </button>929 930 </form>931 932 </div>933 </div>934 </div>935 </div>936 </div>937 </div>938 </div>939 </div>940 </div>941 );942 }943}...

Full Screen

Full Screen

protocols.js

Source:protocols.js Github

copy

Full Screen

1'use strict';2/**3 * Abstracts the protocol configuration between the built-in in-memory implementations and out of process4 * implementations5 * @module6 */7/**8 * Loads the imposter creation functions for all built in and custom protocols9 * @param builtInProtocols {Object} - the in-memory protocol implementations that ship with mountebank10 * @param customProtocols {Object} - custom out-of-process protocol implementations11 * @param options {Object} - command line configuration12 * @param isAllowedConnection {Function} - a function that determines whether the connection is allowed or not for security verification13 * @param mbLogger {Object} - the logger14 * @param impostersRepository {Object} - the imposters repository15 * @returns {Object} - a map of protocol name to creation functions16 */17// eslint-disable-next-line max-params18function load (builtInProtocols, customProtocols, options, isAllowedConnection, mbLogger, impostersRepository) {19 function inProcessCreate (createProtocol) {20 return (creationRequest, logger, responseFn) =>21 createProtocol(creationRequest, logger, responseFn).then(server => {22 const stubs = impostersRepository.stubsFor(server.port),23 resolver = require('./responseResolver').create(stubs, server.proxy),24 Q = require('q');25 return Q({26 port: server.port,27 metadata: server.metadata,28 stubs: stubs,29 resolver: resolver,30 close: server.close,31 encoding: server.encoding || 'utf8'32 });33 });34 }35 function outOfProcessCreate (protocolName, config) {36 function customFieldsFor (creationRequest) {37 const result = {},38 commonFields = ['protocol', 'port', 'name', 'recordRequests', 'stubs', 'defaultResponse'];39 Object.keys(creationRequest).forEach(key => {40 if (commonFields.indexOf(key) < 0) {41 result[key] = creationRequest[key];42 }43 });44 return result;45 }46 return (creationRequest, logger) => {47 const Q = require('q'),48 deferred = Q.defer(),49 { spawn } = require('child_process'),50 command = config.createCommand.split(' ')[0],51 args = config.createCommand.split(' ').splice(1),52 port = creationRequest.port,53 commonArgs = {54 port,55 callbackURLTemplate: options.callbackURLTemplate,56 loglevel: options.loglevel,57 allowInjection: options.allowInjection58 },59 configArgs = require('../util/helpers').merge(commonArgs, customFieldsFor(creationRequest));60 if (typeof creationRequest.defaultResponse !== 'undefined') {61 configArgs.defaultResponse = creationRequest.defaultResponse;62 }63 const allArgs = args.concat(JSON.stringify(configArgs)),64 imposterProcess = spawn(command, allArgs);65 let closeCalled = false;66 imposterProcess.on('error', error => {67 const errors = require('../util/errors'),68 message = `Invalid configuration for protocol "${protocolName}": cannot run "${config.createCommand}"`;69 deferred.reject(errors.ProtocolError(message,70 { source: config.createCommand, details: error }));71 });72 imposterProcess.once('exit', code => {73 if (code !== 0 && deferred.promise.isPending()) {74 const errors = require('../util/errors'),75 message = `"${protocolName}" start command failed (exit code ${code})`;76 deferred.reject(errors.ProtocolError(message, { source: config.createCommand }));77 }78 else if (!closeCalled) {79 logger.error("Uh oh! I've crashed! Expect subsequent requests to fail.");80 }81 });82 function resolveWithMetadata (possibleJSON) {83 let metadata = {};84 try {85 metadata = JSON.parse(possibleJSON);86 }87 catch (error) { /* do nothing */ }88 let serverPort = creationRequest.port;89 if (metadata.port) {90 serverPort = metadata.port;91 delete metadata.port;92 }93 const callbackURL = options.callbackURLTemplate.replace(':port', serverPort),94 encoding = metadata.encoding || 'utf8',95 stubs = impostersRepository.stubsFor(serverPort),96 resolver = require('./responseResolver').create(stubs, undefined, callbackURL);97 delete metadata.encoding;98 deferred.resolve({99 port: serverPort,100 metadata: metadata,101 stubs,102 resolver,103 encoding,104 close: callback => {105 closeCalled = true;106 imposterProcess.once('exit', callback);107 imposterProcess.kill();108 }109 });110 }111 function log (message) {112 if (message.indexOf(' ') > 0) {113 const words = message.split(' '),114 level = words[0],115 rest = words.splice(1).join(' ').trim();116 if (['debug', 'info', 'warn', 'error'].indexOf(level) >= 0) {117 logger[level](rest);118 }119 }120 }121 imposterProcess.stdout.on('data', data => {122 const lines = data.toString('utf8').trim().split('\n');123 lines.forEach(line => {124 if (deferred.promise.isPending()) {125 resolveWithMetadata(line);126 }127 log(line);128 });129 });130 imposterProcess.stderr.on('data', logger.error);131 return deferred.promise;132 };133 }134 function createImposter (Protocol, creationRequest) {135 const Imposter = require('./imposter');136 return Imposter.create(Protocol, creationRequest, mbLogger.baseLogger, options, isAllowedConnection);137 }138 const result = {};139 Object.keys(builtInProtocols).forEach(key => {140 result[key] = builtInProtocols[key];141 result[key].createServer = inProcessCreate(result[key].create);142 result[key].createImposterFrom = creationRequest => createImposter(result[key], creationRequest);143 });144 Object.keys(customProtocols).forEach(key => {145 result[key] = customProtocols[key];146 result[key].createServer = outOfProcessCreate(key, result[key]);147 result[key].createImposterFrom = creationRequest => createImposter(result[key], creationRequest);148 });149 return result;150}151function isBuiltInProtocol (protocol) {152 return ['tcp', 'smtp', 'http', 'https'].indexOf(protocol) >= 0;153}154function loadCustomProtocols (protofile, logger) {155 if (typeof protofile === 'undefined') {156 return {};157 }158 const fs = require('fs-extra'),159 path = require('path'),160 filename = path.resolve(path.relative(process.cwd(), protofile));161 if (fs.existsSync(filename)) {162 try {163 const customProtocols = require(filename);164 Object.keys(customProtocols).forEach(proto => {165 if (isBuiltInProtocol(proto)) {166 logger.warn(`Using custom ${proto} implementation instead of the built-in one`);167 }168 else {169 logger.info(`Loaded custom protocol ${proto}`);170 }171 });172 return customProtocols;173 }174 catch (e) {175 logger.error(`${protofile} contains invalid JSON -- no custom protocols loaded`);176 return {};177 }178 }179 else {180 return {};181 }182}183function loadProtocols (options, baseURL, logger, isAllowedConnection, imposters) {184 const builtInProtocols = {185 tcp: require('./tcp/tcpServer'),186 http: require('./http/httpServer'),187 https: require('./https/httpsServer'),188 smtp: require('./smtp/smtpServer')189 },190 customProtocols = loadCustomProtocols(options.protofile, logger),191 config = {192 callbackURLTemplate: `${baseURL}/imposters/:port/_requests`,193 recordRequests: options.mock,194 recordMatches: options.debug,195 loglevel: options.log.level,196 allowInjection: options.allowInjection,197 host: options.host198 };199 return load(builtInProtocols, customProtocols, config, isAllowedConnection, logger, imposters);200}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, imposter) {3 if (error) {4 console.error('Failed to start server', error);5 } else {6 console.log('Server started on port', imposter.port);7 imposter.post('/imposters', {8 stubs: [{9 responses: [{10 is: {11 headers: { 'Content-Type': 'text/html' },12 }13 }]14 }]15 }, function (error, response) {16 if (error) {17 console.error('Failed to create imposter', error);18 } else {19 }20 });21 }22});23var mb = require('mountebank');24mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, imposter) {25 if (error) {26 console.error('Failed to start server', error);27 } else {28 console.log('Server started on port', imposter.port);29 imposter.post('/imposters', {30 stubs: [{31 responses: [{32 is: {33 headers: { 'Content-Type': 'text/html' },34 }35 }]36 }]37 }, function (error, response) {38 if (error) {39 console.error('Failed to create imposter', error);40 } else {41 }42 });43 }44});45var mb = require('mountebank');46mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, imposter) {47 if (error

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = {2 {3 {4 is: {5 }6 }7 }8};9var mb = require('mountebank');10mb.create(imposter, function (err, info) {11 console.log(info);12});13var imposter = {14 {15 {16 is: {17 }18 }19 }20};21var mb = require('mountebank');22mb.create(imposter, function (err, info) {23 console.log(info);24});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.create({3}, function (error, mbInstance) {4 if (error) {5 console.error(error);6 } else {7 console.log('Mountebank started on port ' + mbInstance.port);8 }9});10mb.customProtocols({11 'myProtocol': {12 stubs: [{13 responses: [{14 is: {15 }16 }]17 }]18 }19});20mb.createImposter(2525, {21}, function (error, imposter) {22 if (error) {23 console.error(error);24 } else {25 console.log('Imposter started on port ' + imposter.port);26 }27});28var http = require('http');29 response.on('data', function (chunk) {30 console.log('Response: ' + chunk);31 });32});33mb.stopImposter(2525, 2525, function (error) {34 if (error) {35 console.error(error);36 } else {37 console.log('Imposter stopped');38 }39});40mbInstance.stop(function (error) {41 if (error) {42 console.error(error);43 } else {44 console.log('Mountebank stopped');45 }46});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank'),2 port = 2525;3 mb.create(port, function (error, server) {4 if (error) {5 console.error('Failed to start server', error);6 } else {7 }8 });9mb.create(port, function (error, server) {10 server.post('/imposters', {11 {12 {13 is: {14 }15 }16 }17 }, function (error, response) {18 console.log(response.statusCode, response.body);19 });20});21mb.create(port, function (error, server) {22 server.get('/imposters', function (error, response) {23 console.log(response.statusCode, response.body);24 });25});26mb.create(port, function (error, server) {27 server.get('/imposters/1', function (error, response) {28 console.log(response.statusCode, response.body);29 });30});31mb.create(port, function (error, server) {32 server.del('/imposters', function (error, response) {33 console.log(response.statusCode, response.body);34 });35});36mb.create(port, function (error, server) {37 server.del('/imposters/1', function (error, response) {38 console.log(response.statusCode, response.body);39 });40});41mb.create(port, function (error, server) {42 server.put('/imposters/1/stubs', [43 {44 {45 is: {46 }47 }48 }49 ], function (error, response) {50 console.log(response.statusCode, response.body);51 });52});53mb.create(port, function (error, server) {54 server.get('/imposters/1/stubs', function (error, response) {55 console.log(response.statusCode, response.body);56 });57});58mb.create(port, function (

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require("mountebank");2const customProtocols = mb.create({ port: 2525, pidfile: "mb.pid" });3customProtocols.then(function (imposter) {4 imposter.post("/imposters", {5 {6 {7 is: {8 headers: { "Content-Type": "application/json" },9 body: JSON.stringify({ message: "Hello World" }),10 },11 },12 },13 });14});15const mb = require("mountebank");16const customProtocols = mb.create({ port: 2525, pidfile: "mb.pid" });17customProtocols.then(function (imposter) {18 imposter.post("/imposters", {19 {20 {21 is: {22 headers: { "Content-Type": "application/json" },23 body: JSON.stringify({ message: "Hello World" }),24 },25 },26 },27 });28});29const mb = require("mountebank");30const customProtocols = mb.create({ port: 2525, pidfile: "mb.pid" });31customProtocols.then(function (imposter) {32 imposter.post("/imposters", {33 {34 {35 is: {36 headers: { "Content-Type": "application/json" },37 body: JSON.stringify({ message: "Hello World" }),38 },39 },40 },41 });42});43const mb = require("mountebank");44const customProtocols = mb.create({ port: 2525, pidfile: "mb.pid" });45customProtocols.then(function (imposter) {46 imposter.post("/imposters", {

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const port = 2525;3mb.create(port)4.then(function (imposter) {5 return imposter.post('/imposters', {6 stubs: [{7 responses: [{8 is: {9 }10 }]11 }]12 });13})14.then(function (response) {15 console.log(response.body);16})17.catch(function (error) {18 console.error(error.message);19});20{21 "request": {22 },23 "response": {24 "headers": {25 },26 "body": {27 "stubs": [{28 "responses": [{29 "is": {30 }31 }]32 }]33 }34 }35}36{37 {38 {39 "is": {40 }41 }42 }43}

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var customProtocols = require('mountebank/src/models/customProtocols');3var customProtocol = customProtocols.create();4customProtocol.add({ name: 'myProtocol', port: 1234 });5mb.start({ customProtocols: customProtocol });6var imposter = {7 {8 {9 "is": {10 "headers": {11 },12 }13 }14 }15};16mb.createImposter(imposter);17var imposter = {18 {19 {20 "is": {21 "headers": {22 },23 }24 }25 }26};27mb.createImposter(imposter);28var imposter = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var customProtocols = mb.create({port: 2525, pidfile: 'pidfile', logfile: 'logfile'});3customProtocols.create({4 requestFrom: function (request, logger) {5 return {6 };7 },8 respondTo: function (request, logger) {9 return {10 };11 }12});13var port = 2525;14var protocol = 'test';15 {16 {17 is: {18 }19 }20 }21];22 {23 equals: {24 }25 }26];27var mock = {stubs: stubs, predicates: predicates};28customProtocols.mocks.create(port, protocol, mock);29customProtocols.mocks.verify(port, protocol, mock);30customProtocols.mocks.remove(port, protocol, mock);31customProtocols.mocks.removeAll(port, protocol);32customProtocols.mocks.removeAll(port, protocol);33customProtocols.remove(protocol);34customProtocols.removeAll();35customProtocols.get(protocol);36customProtocols.all();37customProtocols.port();38customProtocols.pidFile();39customProtocols.logFile();

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var Q = require('q');3var port = 2525;4var protocol = 'http';5var stub = {6 {7 equals: {8 }9 }10 {11 is: {12 headers: {13 },14 body: JSON.stringify({15 })16 }17 }18};19mb.create({20}).then(function (imposters) {21 console.log('Imposters created at', imposters);22 return mb.addStub(port, protocol, stub);23}).then(function (addedStub) {24 console.log('Added stub', addedStub);25 return mb.get('/imposters', port);26}).then(function (imposters) {27 console.log('Imposters', imposters);28 return mb.get('/imposters/' + protocol, port);29}).then(function (protocols) {30 console.log('Protocols', protocols);31 return mb.get('/imposters/' + protocol + '/requests', port);32}).then(function (requests) {33 console.log('Requests', requests);34 return mb.del('/imposters/' + protocol + '/requests', port);35}).then(function (delResponse) {36 console.log('Deleted requests', delResponse);37 return mb.get('/imposters/' + protocol + '/requests', port);38}).then(function (requests) {39 console.log('Requests', requests);40 return mb.del('/imposters/' + protocol, port);41}).then(function (delResponse) {42 console.log('Deleted protocol', delResponse);43 return mb.get('/imposters/' + protocol, port);44}).then(function (protocols) {45 console.log('Protocols', protocols);46 return mb.del('/imposters', port);47}).then(function (delResponse) {48 console.log('Deleted imposters', delResponse);49 return mb.get('/imposters', port);50}).then(function (imposters

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful