How to use cdpInfo method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

updatapersoninfovalidata.js

Source:updatapersoninfovalidata.js Github

copy

Full Screen

1/////////////////////////////////////////////////修改人员信息/////////////////////////////////////////////////////////////////////////		2var fla = null;3$(function(){4			//DOM Loading hidden DIV---------------start----------------------5			//1.dom载入后隐藏"修改人员信息div"6			$("#modifiypersoninfo").hide();7			//DOM Loading hidden DIV-----------------end-----------------------8			9			//DOM载入时 修改人员信息 面板中的 删除当前人员按钮 为不可用状态10			$("#deletepersoninfo").attr({"disabled":true});11			12			$("#closeModifiyPersonInfo").click(function(){13				$("#modifiypersoninfo").hide(); //点击关闭按钮时,隐藏修改人员信息窗口;14			});15			16			//删除人员的按钮默认是不可用的,选中左侧的复选框按钮后删除按钮变为可用17			$("#yesdel").change(function(){18				if($("#yesdel").is(":checked")==true){19					$("#deletepersoninfo").attr({"disabled":false});20				}else{21					$("#deletepersoninfo").attr({"disabled":true});22				}23			});24			25		//修改人员信息的验证26		// 用户名验证 -->27		$("#updatausername").blur(function(){28			var updatausernameStr = $.trim($("#updatausername").val());29			var updatausernamelen = updatausernameStr.length;30			var updatausernametipobj = $("#updatausernametip");31			var reg = /[\u4e00-\u9fa5],{0,}$/;32			if(updatausernamelen>1&&updatausernamelen<5){33				if(reg.test(updatausernameStr)){34					$("#updatausername").css("border-color","#0000FF","border-width","2px","border-style","solid");35					updatausernametipobj.html("OK");36					updatausernametipobj.css("color","#0000FF");37				}else{38					$("#updatausername").css("border-color","red","border-width","2px","border-style","solid");39					updatausernametipobj.html("请输入中文字符");40					updatausernametipobj.css("color","red");41				}42			}else{43				$("#updatausername").css("border-color","red","border-width","2px","border-style","solid");44				updatausernametipobj.html("2-4个中文字符");45				updatausernametipobj.css("color","red");46			}47		});48		//年龄验证  -->49		$("#updataage").blur(function(){50			var updataageStr = $.trim($("#updataage").val());51			var updataagetipobj = $("#updataagetip");52			var ageReg=/^\d*$/;53			if(ageReg.test(updataageStr)&&updataageStr!=""){54				if(((parseInt(updataageStr))>=17)&&((parseInt(updataageStr))<=100)){55					$("#updataage").css("border-color","#0000FF","border-width","2px","border-style","solid");56					updataagetipobj.html("OK");57					updataagetipobj.css("color","#0000FF");						58				}else{59					$("#updataage").css("border-color","red","border-width","2px","border-style","solid");60					updataagetipobj.html("年龄范围错误!");61					updataagetipobj.css("color","red");			62				}63			}else{64				$("#updataage").css("border-color","red","border-width","2px","border-style","solid");65				updataagetipobj.html("请输入正确的年龄(数字)!");66				updataagetipobj.css("color","red");	67			}68		});69		// 验证电话号码 -->70		$("#updatatel").blur(function(){71			var updatatelStr = $.trim($("#updatatel").val());72			var updatatellen = updatatelStr.length;73			var updatateltipobj = $("#updatateltip");74			var telReg=/^\d*$/;75			var servlettelStr = "/CMS/UpdataPersonInfoQueryTelServlet?"+"&uuid="+personId+"&tel="+updatatelStr;76			if(updatatellen>=7&&updatatellen<=12){77				if(telReg.test(updatatelStr)){78					updataajaxreturn(servlettelStr,$("#updatatel"),updatateltipobj);79					$("#updatatel").css("border-color","#0000FF","border-width","2px","border-style","solid");80					updatateltipobj.html("OK");81					updatateltipobj.css("color","#0000FF");				82				}else{83					$("#updatatel").css("border-color","red","border-width","2px","border-style","solid");84					updatateltipobj.html("电话号码格式错误!(请输入合法的号码)!");85					updatateltipobj.css("color","red");			86				}87			}else{88				$("#updatatel").css("border-color","red","border-width","2px","border-style","solid");89				updatateltipobj.html("电话号码长度错误!(7-12位)!");90				updatateltipobj.css("color","red");				91			}92		});93		// 验证QQ -->94		$("#updataqq").blur(function(){95			var updataqqStr = $.trim($("#updataqq").val());96			var updataqqlen = updataqqStr.length;97			var updataqqtipobj = $("#updataqqtip");98			var qqReg=/^\d*$/;99			var servlstqueryQqStr = "UpdataPersonInfoQueryQqServlet?"+"&uuid="+personId+"&qq="+updataqqStr;100			if(updataqqlen>=4&&updataqqlen<=15){101				updataajaxreturn(servlstqueryQqStr,$("#updataqq"),updataqqtipobj);102				$("#updataqq").css("border-color","#0000FF","border-width","2px","border-style","solid");103				updataqqtipobj.html("OK");104				updataqqtipobj.css("color","#0000FF");105			}else{106				$("#updataqq").css("border-color","red","border-width","2px","border-style","solid");107				updataqqtipobj.html("QQ号码长度不正确!");108				updataqqtipobj.css("color","red");109			}110		});111		//农历生日 -->112		$("#updatabrithday").blur(function(){113			var updatabrithdayStr = $.trim($("#updatabrithday").val());114			var updatabrithdaylen = updatabrithdayStr.length;115			var updatabrithdaytipobj = $("#updatabrithdaytip");116			var brithdayReg=/^\d*$/;117			if(brithdayReg.test(updatabrithdayStr)){118				if(updatabrithdaylen==4){119					if(((updatabrithdayStr.substring(0,2)>0)&&(updatabrithdayStr.substring(0,2)<=12))&&((updatabrithdayStr.substring(2,4)>0)&&(updatabrithdayStr.substring(2,4)<=29))){120						$("#updatabrithday").css("border-color","#0000FF","border-width","2px","border-style","solid");121						updatabrithdaytipobj.html("OK");122						updatabrithdaytipobj.css("color","#0000FF");			123					}else{124						$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");125						updatabrithdaytipobj.html("农历日期范围错误,如:0609");126						updatabrithdaytipobj.css("color","red");	127					}128				}else{129					$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");130					updatabrithdaytipobj.html("农历日期长度错误,如:0609");131					updatabrithdaytipobj.css("color","red");				132				}133			}else{134				$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");135				updatabrithdaytipobj.html("农历日期错误,如:0609");136				updatabrithdaytipobj.css("color","red");			137			}138		});139		140			//身份证验证  -->141		$("#updatacard").blur(function(){142			 var updatacardStr = $.trim($("#updatacard").val());143			 var updatacardlen = updatacardStr.length;144			 var updatacardtipobj = $("#updatacardtip");145			 var cardReg=/^(\d{14}|\d{17})(\d|[xX])$/;146			 var servletcardstr = "UpdataPersonInfoQueryCardServlet?"+"&uuid="+personId+"&card="+updatacardStr;147			 if(cardReg.test(updatacardStr)){148			    updataajaxreturn(servletcardstr,$("#updatacard"),updatacardtipobj);149				$("#updatacard").css("border-color","#0000FF","border-width","2px","border-style","solid");150				updatacardtipobj.html("OK");151				updatacardtipobj.css("color","#0000FF");	 	152			 }else{153				$("#updatacard").css("border-color","red","border-width","2px","border-style","solid");154				updatacardtipobj.html("身份证号码错误,请输入合法身份证!");155				updatacardtipobj.css("color","red");		 156			 }157		});158		159		//点击确认修改时 调用mpsubmitvalidata方法160		$("#updatapersoninfo").click(function(){mpsubmitvalidata();});161		162	});163	164	165	//ajax return 166function updataajaxreturn(urlstr,obj,objtip){167		$(function(){168			$.ajax({169				url: urlstr,170				type: "POST",171				dataType:'json',172				data: $.trim(obj.val()),173				success:function(json) {174					if(json.status=="yes"){175						//set style 176						obj.css("border-color","#0000FF","border-width","2px","border-style","solid");177						objtip.html("OK");178						objtip.css("color","#0000FF");179						fla = true;180					}else{181						obj.css("border-color","red","border-width","2px","border-style","solid");182						objtip.html("该号码已经被注册!");183						objtip.css("color","red");184						fla = false;185					}186				}187			});188		});189}190		//修改人员信息窗口打开时,通过ajax返回公司部门职位json信息191		function mpopenjsoncdp(){192			$(function(){193				$.ajax({194					url: "/CMS/returnCDPServlet?args=09s",195					type: "POST",196					dataType:'json',197					success:function(cdpinfo) {198//						alert(cdpinfo.company[0].name);199						viwempcdp(cdpinfo);200					}201				});202			});203		}204		//将ajax返回的公司部门职位等信息显示在相应的下拉列表中205		function viwempcdp(cdpinfo){206			//别忘记了,这里要做一些判断哦207			//1.把从 人员信息表中取到的数据 加入 修改人员信息208			$("#updatausername").prop("value", personUsername);209			$("#updataage").prop("value", personAge);210			if(personSex=="男"){211				$("input:radio[name='updatasex'][value='男']").prop("checked",true);212			}else if(personSex=="女"){213				$("input:radio[name='updatasex'][value='女']").prop("checked",true);214			}215			$("#updatatel").prop("value",personTel);216			$("#updataqq").prop("value",personQq);217			$("#updatabrithday").prop("value",personBri);218			$("#updatacard").prop("value",personCard);219			220			$("#updatacomp").empty();221			for(var i = 0;i<cdpinfo.company.length;i++){222				$("#updatacomp").append("<option value="+"'"+cdpinfo.company[i].name+"'"+">"+cdpinfo.company[i].name+"</option>");223				if($("#updatacomp option:eq("+i+")").val()==personComp){224					$("#updatacomp option:eq("+i+")").prop("selected","selected");225				}226			}227//			alert($("#updatacomp").find("option").length);//获取option长度228			229			$("#updatadep").empty();230			for(var i = 0;i<cdpinfo.dep.length;i++){231				$("#updatadep").append("<option value="+"'"+cdpinfo.dep[i].name+"'"+">"+cdpinfo.dep[i].name+"</option>");232				if($("#updatadep option:eq("+i+")").val()==personDep){233					$("#updatadep option:eq("+i+")").prop("selected","selected");234				}235			}236			237			$("#updatapost").empty();238			for(var i = 0;i<cdpinfo.post.length;i++){239				$("#updatapost").append("<option value="+"'"+cdpinfo.post[i].name+"'"+">"+cdpinfo.post[i].name+"</option>");240				if($("#updatapost option:eq("+i+")").val()==personPost){241					$("#updatapost option:eq("+i+")").prop("selected","selected");242				}243			}244			245		}246		247		//提交时验证248		function mpsubmitvalidata(){249			var updatausernameStr = $.trim($("#updatausername").val());250			var updatausernamelen = updatausernameStr.length;251			var updatausernametipobj = $("#updatausernametip");252			var reg = /[\u4e00-\u9fa5],{0,}$/;253			if(updatausernamelen<1||updatausernamelen>5){254				$("#updatausername").css("border-color","red","border-width","2px","border-style","solid");255				updatausernametipobj.html("2-4个中文字符");256				updatausernametipobj.css("color","red");257				return false;258					259			}else{260				if(!reg.test(updatausernameStr)){261					$("#updatausername").css("border-color","red","border-width","2px","border-style","solid");262					updatausernametipobj.html("请输入中文字符");263					updatausernametipobj.css("color","red");264					return false;265				}else{266					$("#updatausername").css("border-color","#0000FF","border-width","2px","border-style","solid");267					updatausernametipobj.html("OK");268					updatausernametipobj.css("color","#0000FF");269				}270			}271		272			var updataageStr = $.trim($("#updataage").val());273			var updataagetipobj = $("#updataagetip");274			var ageReg=/^\d*$/;275			if(!ageReg.test(updataageStr)||updataageStr==""){276				$("#updataage").css("border-color","red","border-width","2px","border-style","solid");277				updataagetipobj.html("请输入正确的年龄(数字)!");278				updataagetipobj.css("color","red");	279				return false;280			}else{281				if(((parseInt(updataageStr))<17)||((parseInt(updataageStr))>100)){282					$("#updataage").css("border-color","red","border-width","2px","border-style","solid");283					updataagetipobj.html("年龄范围错误!");284					updataagetipobj.css("color","red");	285					return false;286				}else{287					$("#updataage").css("border-color","#0000FF","border-width","2px","border-style","solid");288					updataagetipobj.html("OK");289					updataagetipobj.css("color","#0000FF");		290				}291			}292			293			294			var updatatelStr = $.trim($("#updatatel").val());295			var updatatellen = updatatelStr.length;296			var updatateltipobj = $("#updatateltip");297			var telReg=/^\d*$/;298			var servlettelStr = "/CMS/UpdataPersonInfoQueryTelServlet?"+"&uuid="+personId+"&tel="+updatatelStr;299			if(updatatellen<7||updatatellen>12){300				$("#updatatel").css("border-color","red","border-width","2px","border-style","solid");301				updatateltipobj.html("电话号码长度错误!(7-12位)!");302				updatateltipobj.css("color","red");		303				return false;304			}else{305				if(!telReg.test(updatatelStr)){306					$("#updatatel").css("border-color","red","border-width","2px","border-style","solid");307					updatateltipobj.html("电话号码格式错误!(请输入合法的号码)!");308					updatateltipobj.css("color","red");		309					return false;310				}else{311					updataajaxreturn(servlettelStr,$("#updatatel"),updatateltipobj);312					if(fla==false){return false;}313				}		314			}315			316			var updataqqStr = $.trim($("#updataqq").val());317			var updataqqlen = updataqqStr.length;318			var updataqqtipobj = $("#updataqqtip");319			var qqReg=/^\d*$/;320			var servlstqueryQqStr = "UpdataPersonInfoQueryQqServlet?"+"&uuid="+personId+"&qq="+updataqqStr;321			if(updataqqlen<4||updataqqlen>15){322				$("#updataqq").css("border-color","red","border-width","2px","border-style","solid");323				updataqqtipobj.html("QQ号码长度不正确!");324				updataqqtipobj.css("color","red");325				return false;326			}else{327				updataajaxreturn(servlstqueryQqStr,$("#updataqq"),updataqqtipobj);328				if(fla==false){return false;}329			}	330		331			var updatabrithdayStr = $.trim($("#updatabrithday").val());332			var updatabrithdaylen = updatabrithdayStr.length;333			var updatabrithdaytipobj = $("#updatabrithdaytip");334			var brithdayReg=/^\d*$/;335			if(!brithdayReg.test(updatabrithdayStr)){336				$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");337				updatabrithdaytipobj.html("农历日期错误,如:0609");338				updatabrithdaytipobj.css("color","red");		339				return false;340			}else{341				if(updatabrithdaylen!=4){342					$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");343					updatabrithdaytipobj.html("农历日期长度错误,如:0609");344					updatabrithdaytipobj.css("color","red");	345					return false;346				}else{347					if(((updatabrithdayStr.substring(0,2)<0)||(updatabrithdayStr.substring(0,2)>12))||((updatabrithdayStr.substring(2,4)<0)&&(updatabrithdayStr.substring(2,4)>29))){348						$("#updatabrithday").css("border-color","red","border-width","2px","border-style","solid");349						updatabrithdaytipobj.html("农历日期范围错误,如:0609");350						updatabrithdaytipobj.css("color","red");	351						return false;352					}else{353						$("#updatabrithday").css("border-color","#0000FF","border-width","2px","border-style","solid");354						updatabrithdaytipobj.html("OK");355						updatabrithdaytipobj.css("color","#0000FF");	356					}			357				}	358			}359			360			var updatacardStr = $.trim($("#updatacard").val());361			 var updatacardlen = updatacardStr.length;362			 var updatacardtipobj = $("#updatacardtip");363			 var cardReg=/^(\d{14}|\d{17})(\d|[xX])$/;364			 var servletcardstr = "UpdataPersonInfoQueryCardServlet?"+"&uuid="+personId+"&card="+updatacardStr;365			 if(!cardReg.test(updatacardStr)){366			 	$("#updatacard").css("border-color","red","border-width","2px","border-style","solid");367				updatacardtipobj.html("身份证号码错误,请输入合法身份证!");368				updatacardtipobj.css("color","red");	369				return false;370			 }else{371				updataajaxreturn(servletcardstr,$("#updatacard"),updatacardtipobj);372				if(fla==false){return false;}373			 }	374			infoupdata();375		}376		//判断fla的值确定是否ajax提交修改信息377		function infoupdata(){378			if(mpsubmitvalidata!=null&&mpsubmitvalidata!=false){379				if(valueyesnomodifiy()){380					alert("数据提交");381					var args = "/CMS/UpdataPersonInfoServlet?"+"&uuid="+personId+"&username="+$.trim($("#updatausername").val())+"&sex="+$("input:radio[name='updatasex']").filter(':checked').val()+"&age="+$.trim($("#updataage").val())+"&tel="+$.trim($("#updatatel").val())+"&qq="+$.trim($("#updataqq").val())+"&brithday="+$.trim($("#updatabrithday").val())+"&card="+$.trim($("#updatacard").val())+"&company="+$("#updatacomp option:selected").text()+"&dep="+$("#updatadep option:selected").text()+"&post="+$("#updatapost option:selected").text();382					updatapersoninfo(args);383				}else{384					alert("数据末修改,提交无效!");385				}386			}else{387				alert("no");388			}389		}390		//提交修改之前判断信息是否修改过391		function valueyesnomodifiy(){392			if($.trim($("#updatausername").val())!=personUsername || $.trim($("#updataage").val())!=personAge || $("input:radio[name='updatasex']").filter(':checked').val()!=personSex||$.trim($("#updatatel").val())!=personTel||$.trim($("#updataqq").val())!=personQq||$.trim($("#updatabrithday").val())!=personBri||$.trim($("#updatacard").val())!=personCard||$("#updatacomp option:selected").text()!=personComp||$("#updatadep option:selected").text()!=personDep||$("#updatapost option:selected").text()!=personPost){393			return true;394			}else{395			return false;396			}397		}398	399		function updatapersoninfo(args){400			$(function(){401				$.ajax({402					url: args,403					type: "POST",404					dataType:'json',405					success:function(pinfo) {406//						alert(pinfo.status);407						if(pinfo.status=="yes"){408							personsearch();409							$("#modifiypersoninfo").hide();410						}411					}412				});413			});414		}415		416/////////////////////////////////////////////////修改人员信息/////////////////////////////////////////////////////////////////////////				417		...

Full Screen

Full Screen

MakerService.js

Source:MakerService.js Github

copy

Full Screen

1import Maker from '@makerdao/dai';2import Web3 from 'web3'3export default class MakerService {4    constructor(cdpId) {5        console.log('cdpId: ', cdpId)6        this.cdpId = cdpId7        this.hasWeb3 = true8        this.web3 = window.web3 ? new Web3(window.web3.currentProvider) : this.hasWeb3 = false9        this.loggedIn = false10    }11    init = async () => {12        try{13            // Previous host was 'mainnet' provided by Maker. Switched to infura 27-Mar-19.14            // Private key is random Maker private key from github used on Kovan testnet.15            // this.maker = await Maker.create('mainnet', {16            //     privateKey: 'b178ad06eb08e2cd34346b5c8ec06654d6ccb1cadf1c9dbd776afd25d44ab8d0'17            // })18            this.maker = await Maker.create('http', {19                privateKey: 'b178ad06eb08e2cd34346b5c8ec06654d6ccb1cadf1c9dbd776afd25d44ab8d0',20                url: 'https://mainnet.infura.io/v3/9b85e55cfa5b40a7ac195fba882f04de'21            })22            await this.maker.authenticate()23            this.price = await this.maker.service('price')24            this.ethCdp = await this.maker.service('cdp')25            this.cdp = await this.maker.getCdp(this.cdpId)26        }catch(e){27            console.log('Error authenticating: ', e)28        }29    }30    isLoggedIn = async()=>{31        const accounts = await this.web3.eth.getAccounts()32        accounts[0] ? this.loggedIn = true : this.loggedIn = false33        return this.loggedIn34    }35    hasWeb3 = () => {36        return this.web3 ? true : false37    }38    39    setCdpId = async (cdpId) => {40        if(this.cdpId !== cdpId){41        try{42            this.cdpId = cdpId43            this.cdp = await this.maker.getCdp(this.cdpId)44            console.log('set cdp to id: ', this.cdpId)45            return true46        }47        catch(e){48            console.error('Maker Service: Unable to get CDP ', this.cdpId) //, e)49            return false 50        }51    }52    }53    getDaiDebt = async () => {54        let daiDebt = await (this.cdp.getDebtValue())55        daiDebt = parseFloat(daiDebt.toNumber().toFixed(2))56        return daiDebt57    }58    getPethCollateral = async () => {59        let pethCollateral = await this.cdp.getCollateralValue(Maker.PETH)60        pethCollateral = parseFloat(pethCollateral.toNumber().toFixed(2))61        return pethCollateral62    }63    getEthPrice = async () => {64        let ethUsdPrice = await this.price.getEthPrice()65        ethUsdPrice = parseFloat(ethUsdPrice.toNumber().toFixed(2))66        return ethUsdPrice67    }68    getMkrPrice = async () => {69        return parseFloat((await this.price.getMkrPrice()).toNumber().toFixed(2))70    }71    getLiquidationRatio = async () => {72        return await this.ethCdp.getLiquidationRatio()73    }74    getPethWethRatio = async () => {75        return parseFloat((await this.price.getWethToPethRatio()).toFixed(4))76    }77    getLiquidationPrice = async () => {78        let liquidationPrice = await this.cdp.getLiquidationPrice()79        liquidationPrice = parseFloat(liquidationPrice.toNumber().toFixed(2))80        return liquidationPrice81    }82    getCollateralizationRatio = async () => {83        let collateralizationRatio = await this.cdp.getCollateralizationRatio()84        collateralizationRatio = parseFloat((collateralizationRatio * 100).toFixed(2))85        return collateralizationRatio86    }87    getSystemCollateralization = async () => {88        return parseFloat(((await this.ethCdp.getSystemCollateralization()) * 100).toFixed(2))89    }90    getGovernanceFee = async() =>{91        return parseFloat((await this.cdp.getGovernanceFee(Maker.USD)).toNumber().toFixed(2))92    }93    getGovernanceFeeMkr = async() =>{94        return parseFloat((await this.cdp.getGovernanceFee()).toNumber().toFixed(2))95    }96    getCurrentAccount = async () => {97        try{98        return this.web3.utils.toChecksumAddress(await this.maker.currentAccount().address)99        }catch(e){100            console.error(e)101            return 0102        }103    }104    getDaiSupply = async () =>{105        return parseFloat((await this.maker.getToken('DAI').totalSupply()).toNumber().toFixed(0))106    }107        //TODO, reduces number of calls to blockchain by 3 by removing getPethCollateral, getDaiDebt, 108    getCdpInfo = async () =>{109        const cdpInfo = await this.ethCdp.getInfo(this.cdpId)110        const pethCollateral = this.web3.utils.fromWei(cdpInfo[1].toString())111        const daiDebt = this.web3.utils.fromWei(cdpInfo[2].toString())112        console.log(cdpInfo, pethCollateral, daiDebt)113    }114    getAllDetails = async () => {115        try{116            // await this.getCdpInfo()117            const cdpId = this.cdpId118            const daiDebt = await this.getDaiDebt()119            const pethCollateral = await this.getPethCollateral()120            const ethPrice = await this.getEthPrice()121            const liquidationRatio = await this.getLiquidationRatio()122            const pethWethRatio = await this.getPethWethRatio()123            // Possible issue with dai.js getLiquidationPrice when ink = 0 due to calculation 124            // with ink * liqRatio (possible issue with null as well) 125            let liquidationPrice126            try{127                 liquidationPrice = await this.getLiquidationPrice()128            }catch(e){129                // Manually calculate liqudation price when ink = 0130                 liquidationPrice = parseFloat(((daiDebt * liquidationRatio) / (pethCollateral * pethWethRatio)).toFixed(2))131            }132            133            const collateralizationRatio = await this.getCollateralizationRatio()134            const governanceFee = await this.getGovernanceFee()135            const governanceFeeMkr = await this.getGovernanceFeeMkr()136            137            // console.log('daiDebt, pethCollateral,liquidationRatio, pethWethRatio', daiDebt,pethCollateral,liquidationRatio,pethWethRatio)138            return {139                wipeDraw: {140                    cdpId,141                    daiDebt,142                    pethCollateral,143                    ethPrice,144                    liquidationRatio,145                    pethWethRatio,146                    liquidationPrice147                },148                cdpDetails: {149                    cdpId,150                    daiDebt,151                    pethCollateral,152                    ethPrice,153                    liquidationRatio,154                    pethWethRatio,155                    liquidationPrice,156                    collateralizationRatio,157                    governanceFee,158                    governanceFeeMkr159                }160            }161        }catch(error){162            console.log('AN ERROR HAS OCCURED! ', error)163            // const block = await this.web3.eth.getBlock('latest')164            // console.log('block: ', block)165            return {error}166        }167    }168    populateWipeDraw = async () => {169        const daiDebt = await this.getDaiDebt()170        const pethCollateral = await this.getPethCollateral()171        const ethPrice = await this.getEthPrice()172        const liquidationRatio = await this.getLiquidationRatio()173        const pethWethRatio = await this.getPethWethRatio()174        const liquidationPrice = await this.getLiquidationPrice()175        const account = await this.getCurrentAccount()176        return {177            daiDebt,178            pethCollateral,179            ethPrice,180            liquidationRatio,181            pethWethRatio,182            liquidationPrice,183            account184        }185    }186    populateCdpDetails = async () => {187        const cdpId = this.cdpId188        const daiDebt = await this.getDaiDebt()189        const collateralizationRatio = await this.getCollateralizationRatio()190        const pethCollateral = await this.getPethCollateral()191        const ethPrice = await this.getEthPrice()192        const account = await this.getCurrentAccount()193        return {194            cdpId,195            daiDebt,196            collateralizationRatio,197            ethPrice,198            pethCollateral,199            account200        }201    }202    populateSystemStatus = async () => {203        const ethPrice = await this.getEthPrice()204        const mkrPrice = await this.getMkrPrice()205        const pethWethRatio = await this.getPethWethRatio()206        const systemCollateralization = await this.getSystemCollateralization()207        return {208            ethPrice,209            mkrPrice,210            pethWethRatio,211            systemCollateralization212        }213    }...

Full Screen

Full Screen

bot.js

Source:bot.js Github

copy

Full Screen

1"use strict";2const { BN } = require("@openzeppelin/test-helpers");3const { RAY, RAD, ONE_ETH, DUST, TEN_MINUTES } = require("../../test-utils/constants");4const mcdJSON = require("../../config/mcdTestchain.json");5const bpJSON = require("../../config/bprotocolTestchain.json");6// MCD Contracts7const DssCdpManager = artifacts.require("DssCdpManager");8const Dai = artifacts.require("Dai");9const DaiJoin = artifacts.require("DaiJoin");10const GemJoin = artifacts.require("GemJoin");11const WETH9 = artifacts.require("WETH9");12const Vat = artifacts.require("Vat");13const OSM = artifacts.require("OSM");14// B.Protocol Contracts15const BCdpManager = artifacts.require("BCdpManager");16const Pool = artifacts.require("Pool");17const LiquidatorInfo = artifacts.require("LiquidatorInfo");18const BudConnector = artifacts.require("BudConnector");19// B.Protocol20let bCdpManager;21let pool;22let liqInfo;23// MCD24let dssCdpManager;25let gemJoin;26let weth;27let vat;28let dai;29let daiJoin;30let osm;31let medianizer;32let MEMBER_1 = bpJSON.MEMBER_1;33const ILK_ETH = web3.utils.padRight(web3.utils.asciiToHex("ETH-A"), 64);34// cdp => pending (bool)35const pending = new Map();36module.exports = async function (callback) {37  try {38    bCdpManager = await BCdpManager.at(bpJSON.B_CDP_MANAGER);39    pool = await Pool.at(bpJSON.POOL);40    dai = await Dai.at(mcdJSON.MCD_DAI);41    daiJoin = await DaiJoin.at(mcdJSON.MCD_JOIN_DAI);42    dssCdpManager = await DssCdpManager.at(mcdJSON.CDP_MANAGER);43    gemJoin = await GemJoin.at(mcdJSON.MCD_JOIN_ETH_A);44    vat = await Vat.at(mcdJSON.MCD_VAT);45    osm = await OSM.at(mcdJSON.PIP_ETH);46    weth = await WETH9.at(await gemJoin.gem());47    liqInfo = await LiquidatorInfo.at(bpJSON.LIQUIDATOR_INFO);48    // initialize49    await init();50    web3.eth.subscribe("newBlockHeaders", async (error, event) => {51      try {52        if (!error) {53          console.log("Block: " + event.number + " Timestamp: " + event.timestamp);54          await processCdps();55        } else {56          console.log(error);57        }58      } catch (err) {59        console.log(err);60      }61    });62  } catch (err) {63    console.log(err);64  }65};66async function processCdps() {67  const maxCdp = await bCdpManager.cdpi();68  const medianizerPrice = await getMedianizerPrice();69  for (let cdp = 1; cdp <= maxCdp; cdp++) {70    if (!pending.get(cdp)) {71      pending.set(cdp, true);72      try {73        await processCdp(cdp, medianizerPrice);74      } catch (err) {75        console.log(err);76      }77      pending.set(cdp, false);78    }79  }80}81async function processCdp(cdp, medianizerPrice) {82  try {83    const cdpInfo = await liqInfo.getCdpData.call(84      cdp,85      cdp,86      MEMBER_1,87      medianizerPrice,88      { gas: 12.5e6 } // Higher gas limit needed to execute89    );90    const vaultInfo = cdpInfo[0].vault;91    const cushionInfo = cdpInfo[0].cushion;92    const biteInfo = cdpInfo[0].bite;93    // isExpectedEthLessThanCollateral = expectedEth > Cdp-Collateral94    const expectedEth = new BN(vaultInfo.expectedEthReturnWithCurrentPrice);95    const isExpectedEthLessThanCollateral = expectedEth.lt(new BN(vaultInfo.collateralInWei));96    const priceFeedOk = vaultInfo.expectedEthReturnBetterThanChainlinkPrice;97    const shouldDepositOrTopup = priceFeedOk && isExpectedEthLessThanCollateral;98    // (debtInDaiWei - cushionSizeInWei) > DUST99    const notDust = new BN(vaultInfo.debtInDaiWei)100      .sub(new BN(cushionInfo.cushionSizeInWei))101      .gt(DUST);102    if (cushionInfo.shouldProvideCushion && shouldDepositOrTopup && notDust) {103      await depositBeforeTopup(cdp, cushionInfo);104    }105    if (cushionInfo.canCallTopupNow && shouldDepositOrTopup && notDust) {106      await processTopup(cdp, biteInfo);107    } else if (cushionInfo.shouldCallUntop) {108      await processUntop(cdp);109    }110    if (biteInfo.canCallBiteNow) {111      await processBite(cdp, cushionInfo, biteInfo);112    }113  } catch (err) {114    console.log(err);115  }116}117async function depositBeforeTopup(cdp, ci) {118  const timeToReachTopup = new BN(ci.minimumTimeBeforeCallingTopup);119  // console.log("TimeToReachTopup: " + timeToReachTopup.toString());120  if (timeToReachTopup.lt(TEN_MINUTES)) {121    await ensureDAIBalance(cdp, new BN(ci.cushionSizeInWei).mul(RAY), MEMBER_1);122  }123}124async function processTopup(cdp, bi) {125  const timeToReachBite = new BN(bi.minimumTimeBeforeCallingBite);126  if (timeToReachBite.lt(TEN_MINUTES)) {127    await pool.topup(cdp, { from: MEMBER_1 });128    console.log("### TOPPED-UP ###: " + cdp);129  }130}131async function processUntop(cdp) {132  await pool.untop(cdp, { from: MEMBER_1 });133  console.log("### UN-TOPPED ###: " + cdp);134}135async function processBite(cdp, ci, bi) {136  const avail = await pool.availBite.call(cdp, MEMBER_1, { from: MEMBER_1 });137  const providedCushion = new BN(ci.cushionSizeInWei).div(new BN(ci.numLiquidators));138  const daiNeeded = avail.sub(providedCushion);139  await ensureDAIBalance(cdp, daiNeeded.mul(RAY), MEMBER_1);140  const eth2daiPrice = await getEth2DaiMarketPrice();141  const minEthReturn = new BN(bi.availableBiteInDaiWei).div(eth2daiPrice);142  // bite143  await pool.bite(cdp, avail, minEthReturn, { from: MEMBER_1 });144  console.log("### BITTEN ###: " + cdp);145  // exit146  const afterGem = await vat.gem(ILK_ETH, MEMBER_1);147  await gemJoin.exit(MEMBER_1, afterGem, { from: MEMBER_1 });148  // withdraw149  const rad = await pool.rad(MEMBER_1);150  await pool.withdraw(rad, { from: MEMBER_1 });151  console.log("### WITHDRAWN ###: " + radToDAI(rad) + " DAI");152}153async function getEth2DaiMarketPrice() {154  // NOTICE: This ETH to DAI rate should be taken from real market. eg. Binance order-book etc.155  const eth2daiMarketPrice = new BN(145);156  // NOTICE: You can get the real market rate here and return from this function.157  return eth2daiMarketPrice;158}159async function getMedianizerPrice() {160  const val = await medianizer.read(ILK_ETH, { from: bpJSON.B_CDP_MANAGER });161  return new BN(web3.utils.hexToNumberString(val));162}163// Ensure that the MEMBER has expected DAI balance before topup164async function ensureDAIBalance(cdp, neededRadBal, _from) {165  try {166    if (neededRadBal.eq(new BN(0))) return;167    // Add 1 DAI to avoid rounding errors168    neededRadBal = neededRadBal.add(RAD);169    const radInVat = await vat.dai(_from);170    const radInPool = await pool.rad(_from);171    const radMemberHave = radInPool.add(radInVat);172    if (radMemberHave.lt(neededRadBal)) {173      // mint more DAI174      const radNeedsMore = neededRadBal.sub(radMemberHave);175      await dssCdpManager.frob(cdp, 0, radNeedsMore, { from: _from });176      console.log("MINTED " + radToDAI(radNeedsMore) + " DAI");177    }178    if (radInPool.lt(neededRadBal)) {179      // radNeedsMore = neededRadBal - radInPool + 1e18180      const radNeedsMore = neededRadBal.sub(radInPool);181      await pool.deposit(radNeedsMore, { from: _from });182      console.log("Member:" + _from + " deposited: " + radToDAI(radNeedsMore) + " DAI");183    }184  } catch (err) {185    console.log(err);186  }187}188async function init() {189  const real = await bCdpManager.real();190  medianizer = await BudConnector.at(real);191  await mintDaiForMember(20, 1000, MEMBER_1);192  await vat.hope(pool.address, { from: MEMBER_1 });193  // deposit 1 DAI194  const depositRad = ONE_ETH.mul(RAY);195  await pool.deposit(depositRad, { from: MEMBER_1 });196  console.log("Member:" + MEMBER_1 + " deposited: " + radToDAI(depositRad) + " DAI");197}198function radToDAI(radVal) {199  return radVal.div(RAD).toString();200}201async function mintDai(manager, amtInEth, amtInDai, isMove, _from) {202  const ink = new BN(amtInEth).mul(new BN(ONE_ETH));203  const art = new BN(amtInDai).mul(new BN(ONE_ETH));204  // manager.open();205  const cdp = await manager.open.call(ILK_ETH, _from, {206    from: _from,207  });208  await manager.open(ILK_ETH, _from, { from: _from });209  // WETH.deposit()210  await web3.eth.sendTransaction({211    from: _from,212    to: weth.address,213    value: ink,214  });215  // WETH.approve()216  await weth.approve(gemJoin.address, ink, { from: _from });217  // ethJoin.join()218  const urn = await manager.urns(cdp);219  await gemJoin.join(urn, ink, { from: _from });220  // manager.frob()221  await manager.frob(cdp, ink, art, { from: _from });222  if (isMove) {223    // manager.move();224    await manager.move(cdp, _from, art.mul(RAY), {225      from: _from,226    });227  }228}229async function mintDaiForMember(amtInEth, amtInDai, _from) {230  await mintDai(dssCdpManager, amtInEth, amtInDai, true, _from);231  console.log("Minted: " + amtInDai + " DAI for MEMBER:" + _from);...

Full Screen

Full Screen

cdpAlertHubotListeners.js

Source:cdpAlertHubotListeners.js Github

copy

Full Screen

1const {RBU, FU} = require('hubot-doge-utility-functions')2const Maker = require('./api/maker.js')3const {Validate} = require('./validation.js')4const cdpObjectToString = (cdpObj) => {5  if (cdpObj.collateralizationRatio.toString() != 'Infinity')6    cdpObj.collateralizationRatio = `${cdpObj.collateralizationRatio}%`7  return `Id: ${cdpObj.id}\n Collateralization ratio: ${cdpObj.collateralizationRatio}\n Collateral value: ${cdpObj.collateralValueInEth}\n Debt value in dai: ${cdpObj.debtValueDai}\n Liquidation price: ${cdpObj.liquidationPriceEthUSD}`8}9const newLineJoin = FU.join('\n\n')10const modObjArrRemoveCdpKickBack = (prop, value) => object => {11  let newObj = FU.purify(object)12  let finalCDPArr = []13  newObj[prop].forEach( cdp => {14    if (cdp.id === value) return15    finalCDPArr.push(cdp)16  })17  newObj[prop] = finalCDPArr18  return newObj19}20const checkForCdp = (cdpId, cdpArr) => {21  return cdpArr.filter(cdp =>{22    if (cdp.id === cdpId) return cdp23  })[0]24}25const checkForLiquidRatio = (collatPercent) => {26  if (!collatPercent) {27    return '200%'28  }29  return collatPercent30}31const setupCdpTimedList = (timeDelin, timeDelinString, robot, msg) => {32  RBU.newUserCheckAndCreate(robot, msg.message.user.id)33  // Check if CDP is already being tracked by the user34  if (robot.brain.get(msg.message.user.id).cdps && robot.brain.get(msg.message.user.id).cdps.length) {35    const activCdpList = FU.modObjKickBack(timeDelin, true)36    const deActivCdpList = FU.modObjKickBack(timeDelin, false)37    // User 'toggles' cdp list timeDelin flipping it to 'true' || 'false'38    if (robot.brain.get(msg.message.user.id)[timeDelin]) {39      robot.brain.set(msg.message.user.id, deActivCdpList(robot.brain.get(msg.message.user.id)))40      return `You have *opted out* of the automatic ${timeDelinString} listing of your watched CDP\'s`41    } else {42      robot.brain.set(msg.message.user.id, activCdpList(robot.brain.get(msg.message.user.id)))43      return `You have *opted in* for an automatic ${timeDelinString} list of your watched CDP\'s`44    }45  }46  return 'We can\'t list your watched CDP\'s if you don\'t have any. To start watching a CDP run the command \`@doge cdp watch <cdpId>[, <collateralizationRatio percent>]\`.'47}48module.exports = (robot) => {49  robot.respond('/cdp watch (.*)$/i', async (msg) => {50    msg.finish()51    let arrayOfCmd = FU.spaceSplit(msg.match[1])52    // arrayOfCmd -> [cdpId, collateralizationRatio] -> [12, '300%']53    arrayOfCmd[1] = checkForLiquidRatio(arrayOfCmd[1])54    const {outcome, explain} = Validate.cdpWatchReq(arrayOfCmd)55    if (!outcome) {56      return msg.reply(explain)57    }58    RBU.newUserCheckAndCreate(robot, msg.message.user.id)59    // Check if CDP is already being tracked by the user60    if (robot.brain.get(msg.message.user.id).cdps && checkForCdp(arrayOfCmd[0], robot.brain.get(msg.message.user.id).cdps)) {61      return msg.reply(`You are already tracking the CDP with the ID of ${arrayOfCmd[0]}`)62    }63    try {64      // get CDP takes the CdpId as an arg65      console.log('cdpID', Number(arrayOfCmd[0]))66      const cdpInfo = await Maker.getCDP(Number(arrayOfCmd[0]))67      const desiredCollatRatio = Number(arrayOfCmd[1].substring(0, arrayOfCmd[1].length - 1))68      //addCDPId and get back userObj69      const addCdpId = FU.modObjArrPushKickBack('cdps', {id: arrayOfCmd[0], liqNotifyRatio: desiredCollatRatio})70      robot.brain.set(msg.message.user.id, addCdpId(robot.brain.get(msg.message.user.id)))71      console.log('cdp we try to track', cdpInfo)72      return msg.reply(`You are now tracking the following CDP and will be notified when the CDP\'s collateralization ratio falls below *${desiredCollatRatio}%*\n ${cdpObjectToString(cdpInfo)}`)73    } catch (error) {74      console.log('in error!', error)75      return msg.reply(`${error}`)76    }77  })78   robot.respond('/cdp list(.*)$/i', async (msg) => {79    if (msg.match[1] === ' daily') {80      msg.finish()81      const outcomeMessage = setupCdpTimedList('cdpListDaily','daily', robot, msg)82      msg.reply(outcomeMessage)83    } else if (msg.match[1] === ' weekly') {84      msg.finish()85      const outcomeMessage = setupCdpTimedList('cdpListWeekly','weekly', robot, msg)86      msg.reply(outcomeMessage)87    } else if (msg.match[1] === '') {88      msg.finish()89      try {90        if (robot.brain.get(msg.message.user.id) && (robot.brain.get(msg.message.user.id).cdps && robot.brain.get(msg.message.user.id).cdps.length)) {91          const trackedBrainCdps = robot.brain.get(msg.message.user.id).cdps92          const arrTrackedCdpPromises = trackedBrainCdps.map( async (cdp) => await Maker.getCDP(Number(cdp.id)))93          const arrTrackedCdps = await Promise.all(arrTrackedCdpPromises)94          const trackedCdpsString = newLineJoin(arrTrackedCdps.map(cdpObj => cdpObjectToString(cdpObj)))95          return msg.reply(`Here are all of the CDPs you are currently tracking:\n ${trackedCdpsString}`)96        } else {97          return msg.reply(`You are not currently watching any CDP\'s and therefore cannot perform \`@doge cdp list\`. To watch a cdp type \`@doge cdp watch <CDPId>\``)98        }99      } catch (err) {100        msg.reply(err)101      }102    } else {103      msg.reply('Command was not recognized. Try the command \`@doge help cdp\` for assistance.')104    }105  })106  robot.respond(/cdp forget(.*)$/i, async (msg) => {107    msg.finish()108    const cdpIdToForget = FU.trim(msg.match[1])109    const {outcome, explain} = Validate.cdpForgetReq(cdpIdToForget)110    if (!outcome) {111      return msg.reply(explain)112    }113    if (checkForCdp(cdpIdToForget, robot.brain.get(msg.message.user.id).cdps)) {114      const forgetCdp = modObjArrRemoveCdpKickBack('cdps', cdpIdToForget)115      robot.brain.set(msg.message.user.id, forgetCdp(robot.brain.get(msg.message.user.id)))116      return msg.reply(`CDP ${cdpIdToForget} has now been forgotten and will no longer be watched.`)117    }118    return msg.reply(`You were not watching CDP ${cdpIdToForget} and therefore can\'t forget it. If you would like to see a full list of the CDP\'s you are watching, run the command \`@doge cdp list\`.`)119  })120  robot.listen( msg => {121    if (msg.message && (msg.message.text.substr(0,9) ==='@doge cdp')) {122      return true123    }124  }, msg => {125    return msg.reply(`I did not recognize \`${msg.message.message.text}\`as a command. Be sure to remove all trailing spaces when running a command. Additionally, If you need to see a list of commands that I can run, type \`@doge help cdp\`.`)126  })...

Full Screen

Full Screen

MakerCDP.js

Source:MakerCDP.js Github

copy

Full Screen

1import React, { useEffect, useState } from 'react';2import { connect } from 'react-redux'3import styled from 'styled-components'4import Maker from '@makerdao/dai';5import { GraphQLClient } from 'graphql-request'6import axios from 'axios'7import BigNumber from 'bignumber.js'8import async from 'async'9import MakerCDPRow from './MakerCDPRow'10import { setMakerBalanceNw } from '../../actions/index'11import BoxWrapper from '../../components/BoxWrapper'12import MakerLogo from '../../images/maker_logo.svg'13//https://developer.makerdao.com/dai/1/graphql/14//What are proxy addresses?15//https://makerdao.com/documentation/16const MakerCDP = (props) => {17    const { account, prices } = props;18    const [cdps,setCdps] = useState(null)19    const [loading,setLoading] = useState(false)20    const createMaker = async () => {21        22        setLoading(true)23        const maker = await Maker.create("http", {24            url: 'https://mainnet.infura.io/v3/16336a82e72c4f8eb86903e55ac6a8b2',25            web3: {26                statusTimerDelay: 15000,27            },28            log:false29        });30        await maker.authenticate();31        const proxy = await maker.service('proxy').getProxyAddress(account);32        const query = `33        {34            allCups(35                first: 10,36                condition: { lad: "${proxy}" },37                orderBy: RATIO_ASC38            ) {39                totalCount40                pageInfo {41                hasNextPage42                hasPreviousPage43                endCursor44                }45                nodes {46                id47                lad48                art49                ink50                ratio51                actions(first: 5) {52                    nodes {53                    act54                    time55                    }56                }57                }58            }59        }60        `61        const graphQLClient = new GraphQLClient('https://sai-mainnet.makerfoundation.com/v1', {62            mode: 'cors',63        })64        const response = await graphQLClient.request(query)65        66        let cdpsTemp = []67        if (response.allCups.totalCount > 0){68            let nwContributionTotal = BigNumber(0);69            let i = 0;70            async.each(response.allCups.nodes,async (item,callback) => {71                //get missing data from dai.js API72                let cdp = await maker.getCdp(item.id)73                let liquidationObject = await cdp.getLiquidationPrice();74                let liquidationPrice = liquidationObject._amount.toFixed(3)75                let safety;76                if (item.art !== '0'){77                    safety = await cdp.isSafe();78                } else {79                    safety = true;80                }81                82                //calculate things for nw83                let collateral = BigNumber(item.ink);84                let collateralUsd = collateral.multipliedBy(BigNumber(prices.ETH));85                let debt = BigNumber(item.art)86                let debtFloat = parseFloat(debt.toFixed(3))87                //for sorting88                let priceToFall = (parseFloat(liquidationPrice) - parseFloat(prices.ETH)) / parseFloat(prices.ETH)* -10089                priceToFall = priceToFall.toFixed(3)90                console.log("price to fall",priceToFall)91                92                93                94                let nwContribution = collateralUsd.minus(debt);95                nwContributionTotal = nwContributionTotal.plus(nwContribution);96                97                //To do: Add % swing to kill CDP98                let cdpInfo = {99                    id: item.id,100                    art: item.art,101                    ink: item.ink,102                    ratio:item.ratio,103                    lad: item.lad,104                    safety:safety.toString(),105                    liquidationPrice:liquidationPrice,106                    percentToFall:priceToFall107                }108                cdpsTemp.push(cdpInfo)109                i++ //for sorting110                callback()111            }, (err) => {112                //after async.each113                //How to sort cdps by item.art114                setCdps(cdpsTemp)115                setLoading(false)116                props.setMakerBalanceNw(parseFloat(nwContributionTotal.toFixed(2)))117            })118            119        } else {120            setLoading(false)121        }122    }123    useEffect(()=> {124        createMaker();125        126    },[])127    return (128        <BoxWrapper129            minHeight="100px"130            width={props.width}131            headerTitle={"Maker"}132            headerLogo={MakerLogo}133            margin={'20px 0px 20px 0px'}134            link={"https://cdp.makerdao.com/"}135           136        >137         138        {!loading ? 139        <React.Fragment>140            { cdps ?141                <ContentWrapper>142                    {cdps.map(cdp => <MakerCDPRow cdp={cdp} key={cdp.id} />)}143                </ContentWrapper>144                :145                <div>No CDPs</div>146            }147            148        </React.Fragment>149        :150        "loading"}151                    152        </BoxWrapper>153        154    );155}156const mapStateToProps = state => ({157    account:state.account,158    prices:state.prices159})160const mapDispatchToProps = dispatch => ({161    setMakerBalanceNw: value => dispatch(setMakerBalanceNw(value)),162})163export default connect(164    mapStateToProps,165    mapDispatchToProps166)(MakerCDP)167const ContentWrapper = styled.div`168    width:100%;169    display:flex;170    flex-direction:column;171    align-self:flex-start;...

Full Screen

Full Screen

liquidity_calc.js

Source:liquidity_calc.js Github

copy

Full Screen

...17function payBack(daiDebt, collateral, ratio) {18    const max_col = getMaxCollateral(daiDebt, collateral);19    const converted_dai = max_col * (ETH_PRICE - (ETH_PRICE/100)*1);20    console.log("Converted dai: ", converted_dai);21    cdpInfo(daiDebt - converted_dai, collateral - max_col);22    console.log("   ");23    // if (getRatio(daiDebt - converted_dai, collateral - max_col) < ratio) {24    //     payBack(daiDebt - converted_dai, collateral - max_col, ratio);25    // }26}27function cdpInfo(daiDebt, collateral) {28    console.log('Debt left: ' + daiDebt + "  Collateral: " + collateral);29    console.log('Ratio: ', getRatio(daiDebt, collateral));30    console.log('getLiquidationPrice: ', getLiquidationPrice(daiDebt, collateral));31    console.log('getMaxCollateral: ', getMaxCollateral(daiDebt, collateral));32    console.log('getMaxDai: ', getMaxDai(daiDebt, collateral));33}34function payBackGetRatio(daiDebt, collateral, conversionLost) {35    const max_col = getMaxCollateral(daiDebt, collateral);36    const converted_dai = max_col * (ETH_PRICE - (ETH_PRICE/100)*conversionLost);37    // console.log("max col " + max_col + " Converted dai: ", converted_dai);38    return getRatio(daiDebt - converted_dai, collateral - max_col);39}40function getRatiosAfterRepay() {41    const collateral = 1; // 1 eth42    let data = [];43    for(let i = 1; i <= 100; ++i) {44        const daiDebt = (collateral* ETH_PRICE * PETH_ETH_RATIO / (LIQUIDATION_RATIO + (i / 100)));45        let ratios = [];46        //for(let j = 0; j < 1; ++j) {47            ratios[0] = payBackGetRatio(daiDebt, collateral, 10).toFixed(4);48        //}49        data.push({oldRatio: (LIQUIDATION_RATIO*100) + i, ratios})50    }51    const file = fs.createWriteStream('ratios.txt');52    data.forEach((v) => file.write(`${v.ratios[0]}\n`));53    file.end();54}55//console.log('getMaxDai: ', getMaxDai(0, 1));56console.log(getRatio(0.416853661522540849, 0.005000782116139281));57console.log(getMaxCollateral(0.416853661522540849, 0.006064592417692078));58//getRatiosAfterRepay();59// cdpInfo(79.9, 1);60// console.log("   ");...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1require('dotenv').config();2const sdk = require('../../sdk');3const utils = require('../../sdk/util');4const { bytesToString, getContractAddress, getContractMethod, getContractBlock } = require('./utils');5async function tvl(timestamp, block) {6  let makerSubs = [];7  let compoundSubs = [];8  let aaveSubs = [];9  if (block >= getContractBlock('McdSubscriptions')) makerSubs = (await sdk.api.abi.call({10    block,11    target: getContractAddress('McdSubscriptions'),12    abi: getContractMethod('getSubscribers', 'McdSubscriptions'),13  })).output;14  let calls = [];15  let cdpsDetailed = [];16  let cdpInfo = [];17  for (const cdp of makerSubs) {18    calls = [19      ...calls,20      { target: getContractAddress('MCDSaverProxy'), params: [cdp[5]] },21    ];22  }23  if (block >= getContractBlock('McdSubscriptions')) {24    cdpsDetailed = (await sdk.api.abi.multiCall({25      block,26      calls,27      abi: getContractMethod('getCdpDetailedInfo', 'MCDSaverProxy'),28    })).output;29    makerSubs.forEach((cdp, i) => {30      cdpInfo = [31        ...cdpInfo,32        {33          id: cdp[5],34          ilk: bytesToString(cdpsDetailed.find(({ input }) => input.params[0] === cdp[5]).output[3]),35        },36      ];37    });38  }39  if (block >= getContractBlock('CompoundSubscriptions')) compoundSubs = (await sdk.api.abi.call({40    block,41    target: getContractAddress('CompoundSubscriptions'),42    abi: getContractMethod('getSubscribers', 'CompoundSubscriptions'),43  })).output;44  if (block >= getContractBlock('AaveSubscriptions')) aaveSubs = (await sdk.api.abi.call({45    block,46    target: getContractAddress('AaveSubscriptions'),47    abi: getContractMethod('getSubscribers', 'AaveSubscriptions'),48  })).output;49  const compoundSubscribers = new Set();50  const aaveSubscribers = new Set();51  for (const sub of compoundSubs) { compoundSubscribers.add(sub[0]); }52  for (const sub of aaveSubs) { aaveSubscribers.add(sub[0]); }53  let makerBalances = (await sdk.api.cdp.maker.getAssetsLocked({54    block,55    targets: cdpInfo,56    ids: true57  })).output;58  let compoundBalances = (await sdk.api.cdp.compound.getAssetsLocked({59    block,60    targets: [...compoundSubscribers]61  })).output;62  let aaveBalances = (await sdk.api.cdp.aave.getAssetsLocked({63    block,64    targets: [...aaveSubscribers]65  })).output;66  let balances = utils.sum([makerBalances, compoundBalances, aaveBalances]);67  if (Object.keys(balances).length === 0) {68    balances = {69      "0x0000000000000000000000000000000000000000": "0"70    }71  }72  return balances;73}74module.exports = {75  tvl,76  name: 'DeFi Saver',77  token: null,78  website: 'https://defisaver.com/',79  category: 'lending',80  start: 1586430640, // 09/04/2020 @ 11:10 (UTC)81  contributesTo: ['Maker', 'Compound', 'Aave'],...

Full Screen

Full Screen

cdp.test.js

Source:cdp.test.js Github

copy

Full Screen

1const Maker = require('@makerdao/dai');2const { default: McdPlugin, ETH, MDAI } = require('@makerdao/dai-plugin-mcd');3const CDP = artifacts.require("CDP");4contract('cdp', (accounts) => {5    it("should assert true", async () => {6        const maker = await Maker.create('test', {7            plugins: [8                [McdPlugin, {}]9            ]10        });11        await maker.authenticate();12        // const balance = await maker13        //     .service('token')14        //     .getToken('ETH')15        //     .balance();16        // console.log('Account: ', maker.currentAddress());17        // console.log('Balance', balance.toString());18        // const cdp = await maker19        //     .service('mcd:cdpManager')20        //     .openLockAndDraw('ETH-A', ETH(1), MDAI(20));21        // console.log('Opened CDP #'+cdp.id);22        // console.log('Collateral amount:'+cdp.collateralAmount.toString());23        // console.log('Debt Value:'+cdp.debtValue.toString());24        const cdp = await CDP.deployed();25        await cdp.open();26        // const cdpInfo = await maker27        //     .service('mcd:cdpManager')28        //     .getInfo(cdp.cdpId);29        // console.info("!!!!!!!!", cdpInfo);30    });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var driver = new webdriver.Builder()4    .forBrowser('chrome')5    .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.cdpInfo();11var webdriver = require('selenium-webdriver'),12    until = webdriver.until;13var driver = new webdriver.Builder()14    .forBrowser('chrome')15    .build();16driver.findElement(By.name('q')).sendKeys('webdriver');17driver.findElement(By.name('btnG')).click();18driver.wait(until.titleIs('webdriver - Google Search'), 1000);19driver.quit();20driver.cdp('Network.enable');21Appium version (or git revision) that exhibits the issue: v1.15.122Last Appium version that did not exhibit the issue (if applicable): NA23Node.js version (unless using Appium.app|exe): v10.16.3

Full Screen

Using AI Code Generation

copy

Full Screen

1const { AndroidDriver } = require('appium-android-driver');2const driver = new AndroidDriver();3const cdpInfo = await driver.cdpInfo();4console.log(cdpInfo);5const { IOSDriver } = require('appium-ios-driver');6const driver = new IOSDriver();7const cdpInfo = await driver.cdpInfo();8console.log(cdpInfo);9const { WindowsDriver } = require('appium-windows-driver');10const driver = new WindowsDriver();11const cdpInfo = await driver.cdpInfo();12console.log(cdpInfo);13const { MacDriver } = require('appium-mac-driver');14const driver = new MacDriver();15const cdpInfo = await driver.cdpInfo();16console.log(cdpInfo);17const { Webdriverio } = require('appium-webdriverio');18const driver = new Webdriverio();19const cdpInfo = await driver.cdpInfo();20console.log(cdpInfo);21const { FakeDriver } = require('appium-fake-driver');22const driver = new FakeDriver();23const cdpInfo = await driver.cdpInfo();24console.log(cdpInfo);25const { YouiEngineDriver } = require('appium-youiengine-driver');26const driver = new YouiEngineDriver();27const cdpInfo = await driver.cdpInfo();28console.log(cdpInfo);29const { EspressoDriver } = require('appium-espresso-driver');30const driver = new EspressoDriver();31const cdpInfo = await driver.cdpInfo();32console.log(cdpInfo);33const { Mac2Driver } = require('appium-mac2-driver');34const driver = new Mac2Driver();35const cdpInfo = await driver.cdpInfo();36console.log(cdpInfo);37const { WindowsDriver } = require('appium-windows-driver');38const driver = new WindowsDriver();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { remote } = require('webdriverio');2const opts = {3    capabilities: {4    }5};6async function main() {7    const client = await remote(opts);8    const cdpInfo = await client.cdp('Network', 'enable');9    console.log(cdpInfo);10    await client.deleteSession();11}12main();13const { remote } = require('webdriverio');14const opts = {15    capabilities: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var AndroidDriver = require('appium-android-driver');3var driver = new AndroidDriver();4var cdpInfo = driver.cdpInfo();5console.log(cdpInfo);6driver.quit();7var webdriver = require('selenium-webdriver');8var AndroidDriver = require('appium-android-driver');9var driver = new AndroidDriver();10var cdp = driver.cdp();11console.log(cdp);12driver.quit();13var webdriver = require('selenium-webdriver');14var AndroidDriver = require('appium-android-driver');15var driver = new AndroidDriver();16console.log(cdp);17driver.quit();18var webdriver = require('selenium-webdriver');19var AndroidDriver = require('appium-android-driver');20var driver = new AndroidDriver();21console.log(cdp);22driver.quit();23var webdriver = require('selenium-webdriver');24var AndroidDriver = require('appium-android-driver');25var driver = new AndroidDriver();26console.log(cdp);27driver.quit();28var webdriver = require('selenium-webdriver');29var AndroidDriver = require('appium-android-driver');30var driver = new AndroidDriver();31console.log(cdp);32driver.quit();33var webdriver = require('selenium-webdriver');34var AndroidDriver = require('appium-android-driver');35var driver = new AndroidDriver();

Full Screen

Using AI Code Generation

copy

Full Screen

1const cdpInfo = require('appium-android-driver').androidHelpers.cdpInfo;2async function test() {3  const cdpInfoObj = await cdpInfo();4  console.log(cdpInfoObj);5}6test();

Full Screen

Using AI Code Generation

copy

Full Screen

1const Appium = require('appium');2const Android = require('appium-android-driver');3const android = new Android();4android.cdpInfo().then((result) => {5    console.log(result);6});

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 Appium Android Driver 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