feat: update param filters in listContractProcess

refactor
style
This commit is contained in:
Frank.R.Wu 2021-06-30 10:39:00 +08:00
parent 10841c1b03
commit 59d54cb2b5
12 changed files with 1449 additions and 1457 deletions

View File

@ -405,7 +405,7 @@
</select>
<div class="input-group-append">
<button type="button" class="btn btn-outline-primary"
title="预览" data-toggle="tooltip" onclick="openinClient()">
title="预览" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg">
</button>

View File

@ -584,7 +584,7 @@
</div>
<select id="selectMemeryFiles" class="custom-select"
onchange="changeMemeryFiles(this.value)"
onchange="changeMemoryFiles(this.value)"
style="appearance:none; -webkit-appearance:none">
<option selected>选择时间</option>
</select>

View File

@ -413,7 +413,7 @@
</select>
<div class="input-group-append">
<button type="button" class="btn btn-outline-primary"
title="预览" data-toggle="tooltip" onclick="openinClient()">
title="预览" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg">
</button>

View File

@ -394,7 +394,7 @@
<div class="input-group-append">
<button type="button" class="btn btn-outline-primary"
title="Preview" data-toggle="tooltip" onclick="openinClient()">
title="Preview" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg">
</button>

View File

@ -1,57 +1,70 @@
var loadContractInstances = function (event) {
console.log("loadContractInstances" + event);
listContractProcess();
const CONSENSUS_TABLE = {
0: '无',
1: 'PBFT',
2: 'RAFT',
3: 'Single'
};
var listContractProcess = function (event) {
const RESPONSE_TYPE_TABLE = {
0: 'ALL',
1: 'MOST',
2: 'FIRST'
};
function loadContractInstances(event) {
console.log("loadContractInstances" + event);
listContractProcess();
}
function listContractProcess(event) {
console.log("listContractProcess" + event);
setTimeout(function () {
var param = {};
param.action = "listContractProcess";
global.wssocket.send(JSON.stringify({
action: 'listContractProcess',
// data: event,
// 1 << 0: INIT, 1 << 1: RUNNING, 1 << 2: HANGED, 1 << 3: KILLED, 0: ALL
filters: global.myRole && global.myRole.indexOf('NodeManager') > -1 ? 0 : 7
}));
// param.data = event;
param.fromNodePortal = true;
global.wssocket.send(JSON.stringify(param));
var request2 = {};
request2.action = "listLeakContractProcess";
global.wssocket.send(JSON.stringify(request2));
global.wssocket.send(JSON.stringify({
action: 'listLeakContractProcess'
}));
}, 300);
};
}
var onListContractProcess1 = function (obj) {
console.log("+++++++++=" + obj.data);
var table = JSON.parse(obj.data);
function onListContractProcess1(obj) {
console.log("+++++++++=" + obj.data.length);
const table = JSON.parse(obj.data);
global.contractList = table;
drawContractInstanceStatusPie(table);
// drawContractInstanceTimesPie(table);
drawContractInstanceTypeTimesPie(table);
drawciTable(table);
drawConInfoTable(table);
console.log(table);
$("#selectContractInstance").html("");
var x = document.getElementById("selectContractInstance");
const x = document.getElementById("selectContractInstance");
x.options.length = 0;
x.add(new Option("选择...", " "));
global.permissionNameMap = {};
for (var i = 0; i < table.length; i++) {
if (table[i].contractStatus == "KILLED") {
for (let i = 0; i < table.length; i++) {
if (table[i]['contractStatus'] !== 'RUNNING') {
continue;
}
var option = document.createElement("option");
let option = document.createElement("option");
option.text = table[i].name;
console.log(table[i].name);
global.permissionNameMap[table[i].id] = table[i].contractPermission;
global.permissionNameMap[table[i].id] = table[i]['contractPermission'];
// option.value=table[i].id;
option.value = table[i].id;
x.add(option, null);
}
};
}
var drawciTable = function (table) {
if ($("#ciTabDiv").css("height") == "0px") {
console.log("drawciTabDiv: ignore");
function drawConInfoTable(table) {
const ciTabDiv = $("#ciTabDiv");
if (ciTabDiv.css("height") === "0px") {
console.log("drawConInfoTabDiv: ignore");
return;
}
var dtLang = {
@ -81,78 +94,51 @@ var drawciTable = function (table) {
"sSortDescending": ": 以降序排列此列"
}
};
var tableHead = "<table id='ciTabDivTab' class='table display row-border' style='word-break:normal; word-break:keep-all'><thead><tr><th>序号</th><th>ID</th><th>名称</th><th>状态</th><th>端口</th><th>类型</th><th>通讯</th><th>共识</th><th>统计</th><th>次数</th><th>流量</th><th>内存</th><th>管理</th></tr></thead><tbody>";
var tableTail = "</tbody></table>";
const tableHead = `<table id='ciTabDivTab' class='table display row-border' style='word-break:keep-all;'>
<thead><tr>
<th>序号</th>
<th>ID</th>
<th>名称</th>
<th>状态</th>
<th>端口</th>
<th>类型</th>
<th>通讯</th>
<th>共识</th>
<!--<th>返回方式</th>-->
<th>次数</th>
<th>流量</th>
<th>内存</th>
<th>管理</th>
</tr>
</thead><tbody>`;
const tableTail = "</tbody></table>";
console.log("drawciTable");
var html = tableHead;
for (var i = 0; i < table.length; i++) {
if (table[i].contractStatus=="KILLED") continue;
html += "<tr><td>";
html += (i + 1);
html += "</td> <td>";
html += table[i].id;
html += "</td> <td>";
html += "<a href='/client/bdwareclient.html?self=true&contract="
+ table[i].id + "' target='_blank'>" + table[i].name + "</>";
html += "</td> <td>";
html += table[i].contractStatus;
html += "</td> <td>";
html += table[i].port;
html += "</td><td>";
html += table[i].type;
html += "</td> <td>";
html += table[i].networkType == 0 ? "TCP" : "P2P";
html += "</td><td>";
var consensusType;
switch (table[i].consensusType) {
case 0:
consensusType = "无";
break;
case 1:
consensusType = "PBFT";
break;
case 2:
consensusType = "RAFT";
break;
case 3:
consensusType = "Single";
break;
}
html += consensusType;
html += "</td><td>";
var responseType;
switch (table[i].responseType) {
case 0:
responseType = "ALL";
break;
case 1:
responseType = "MOST";
break;
case 2:
responseType = "FIRST";
break;
}
html += responseType;
html += "</td><td>";
html += table[i].times;
table[i].port;
html += "</td> <td>";
html += table[i].traffic;
html += "</td> <td>";
html += table[i].storage;
html += "</td> <td style='padding:2px 12px 2px 12px'>";
html += "<button onclick='stopContractByID(\"" + table[i].id + "\")' class='btn btn-secondary'>" + "停止</button>"
//table[i].resultCheck;
// html += "</td> <td>";
// html += "<button class='btn btn-outline-secondary' type='button'
// onclick='viewContractInstance("+ table[i].contractID +
// ")'>更多</button>";
html += "</td> </tr>";
console.log("drawConInfoTable");
let html = tableHead;
for (let i = 0; i < table.length; i++) {
html += `<tr>
<td>${i + 1}</td>
<td>${table[i].id}</td>
<td><a href='/client/bdwareclient.html?self=true&contract=${table[i].id}' target='_blank'>
${table[i].name}
</a></td>
<td>${table[i]['contractStatus']}</td>
<td>${table[i].port || '-'}</td>
<td>${table[i].type}</td>
<td>${table[i]['networkType'] ? "P2P" : "TCP"}</td>
<td>${table[i]['consensusType'] ? CONSENSUS_TABLE[table[i]['consensusType']] : '无'}</td>
<!--<td>${table[i].responseType ? RESPONSE_TYPE_TABLE[table[i].responseType] : '-'}</td>-->
<td>${table[i].times}</td>
<td>${table[i]['traffic'] || '-'}</td>
<td>${table[i].storage || '-'}</td>
<td style='padding:2px 12px 2px 12px'>
<button onclick="stopContractByID('${table[i].id}')" class="btn btn-secondary">停止</button>
</td>
</tr>`
}
html += tableTail;
html = "<h5 class='card-title'>合约实例列表</h5>" + html;
$("#ciTabDiv").html(html);
ciTabDiv.html(html);
$("#ciTabDivTab").DataTable(
{
@ -161,7 +147,7 @@ var drawciTable = function (table) {
dataIndex) {
},
"headerCallback": function (thead, data, start, end, display) {
"headerCallback": function (thead/*, data, start, end, display*/) {
$(thead).css("background", primaryColor);
$(thead).css("color", "white");
$(thead).children().css("background", primaryColor);
@ -174,7 +160,7 @@ var drawciTable = function (table) {
"columnDefs": [
{
"targets": 1,
"render": function (data, type, row, meta) {
"render": function (data/*, type, row, meta*/) {
if (data.length > 8)
return "<span title='" + data + "'>"
+ data.substring(0, 8)
@ -185,46 +171,48 @@ var drawciTable = function (table) {
},]
});
};
var stopContractByID = function (contractID) {
$("#dialogBodyDiv").html("是否停止合约ContractID:" + contractID);
}
function stopContractByID(contractID) {
$("#dialogBodyDiv").html("是否停止合约ContractID" + contractID);
showDialog("请确认", function () {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.id = contractID;
global.wssocket.send(JSON.stringify(request));
global.wssocket.send(JSON.stringify({
action: 'killContractProcess',
requestID: new Date().getTime().toString(),
id: contractID
}));
});
};
var drawContractInstanceStatusPie = function (table) {
if ($("#ciStatusPieDiv").css("height") == "0px") {
}
function drawContractInstanceStatusPie(table) {
const ciStatusPieDiv = $("#ciStatusPieDiv")
if (ciStatusPieDiv.css("height") === "0px") {
console.log("drawContractInstanceStatusPie: ignore");
return;
}
$("#ciStatusPieDiv")
.html(
"<div class='col-12' id='ciStatusPieDivCanv' style='width:100%; min-height: 150px; padding: 0px'></div>");
var result = {};
for (var i = 0; i < table.length; i++) {
var obj = table[i];
if (result[obj.contractStatus] == undefined) {
result[obj.contractStatus] = 1;
$(ciStatusPieDiv).html(
"<div class='col-12' id='ciStatusPieDivCanv' style='width:100%; min-height: 150px; padding: 0;'></div>");
const result = {};
for (let i = 0; i < table.length; i++) {
const obj = table[i];
if (!result[obj['contractStatus']]) {
result[obj['contractStatus']] = 1;
} else
result[obj.contractStatus]++;
result[obj['contractStatus']]++;
}
global.result = result;
var dataList = [];
var valDataList = [];
for (var key in result) {
const dataList = [];
const valDataList = [];
for (const key in result) {
dataList.push(key);
var l = {};
l.name = key
l.value = result[key];
valDataList.push(l);
valDataList.push({
name: key,
value: result[key]
});
}
var myChart = echarts.init($("#ciStatusPieDivCanv")[0], 'walden');
var option222 = {
const myChart = echarts.init($("#ciStatusPieDivCanv")[0], 'walden');
const option222 = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
@ -261,35 +249,35 @@ var drawContractInstanceStatusPie = function (table) {
}]
};
myChart.setOption(option222);
};
}
var drawContractInstanceTimesPie = function (table) {
if ($("#ciTimesPieDiv").css("height") == "0px") {
function drawContractInstanceTimesPie(table) {
const ciTimesPieDiv = $("#ciTimesPieDiv");
if (ciTimesPieDiv.css("height") === "0px") {
console.log("drawContractInstanceTimesPie: ignore");
return;
}
$("#ciTimesPieDiv")
.html(
"<div class='col-12' id='ciTimesPieDivCanv' style='width:100%; min-height: 150px; padding: 0px'></div>");
var result = {};
for (var i = 0; i < table.length; i++) {
var obj = table[i];
ciTimesPieDiv.html(
"<div class='col-12' id='ciTimesPieDivCanv' style='width:100%; min-height: 150px; padding: 0;'></div>");
const result = {};
for (let i = 0; i < table.length; i++) {
const obj = table[i];
result[obj.name] = obj.times;
}
global.result = result;
var dataList = [];
var valDataList = [];
for (var key in result) {
const dataList = [];
const valDataList = [];
for (const key in result) {
dataList.push(key);
var l = {};
l.name = key
l.value = result[key];
valDataList.push(l);
valDataList.push({
name: key,
value: result[key]
});
}
var myChart = echarts.init($("#ciTimesPieDivCanv")[0], 'walden');
const myChart = echarts.init($("#ciTimesPieDivCanv")[0], 'walden');
var option222 = {
const option222 = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
@ -326,18 +314,19 @@ var drawContractInstanceTimesPie = function (table) {
}]
};
myChart.setOption(option222);
};
}
var changeContractInstance = function (obj) {
function changeContractInstance(obj) {
let i;
console.log(obj);
global.contractInstance = obj;
console.log(typeof (obj));
showPermissionList(global.contractInstance);
var contract;
for (var i = 0; i < global.contractList.length; i++) {
if (global.contractList[i].id == obj) {
let contract;
for (i = 0; i < global.contractList.length; i++) {
if (global.contractList[i].id === obj) {
contract = global.contractList[i];
global.instance = contract;
global.instanceName = contract.name;
@ -350,79 +339,82 @@ var changeContractInstance = function (obj) {
}
$("#selectContractFunction").html("");
var x = document.getElementById("selectContractFunction");
const x = document.getElementById("selectContractFunction");
x.options.length = 0;
x.add(new Option("选择方法...", " "));
console.log("contract ", contract);
for (var i = 0; i < contract.exportedFunctions.length; i++) {
var option = document.createElement("option");
option.text = contract.exportedFunctions[i].functionName;
option.value = contract.exportedFunctions[i].functionName;
for (i = 0; i < contract['exportedFunctions'].length; i++) {
const option = document.createElement("option");
option.text = contract['exportedFunctions'][i].functionName;
option.value = contract['exportedFunctions'][i].functionName;
x.add(option, null);
}
};
}
var changeMemeryFiles = function (obj) {
function changeMemoryFiles(obj) {
console.log(obj);
global.memoryFile = obj;
};
}
var executeContractWithDynamicResult = function () {
function executeContractWithDynamicResult() {
const argDiv = $("#arg")[0]
console.log("executeContractWithDynamicResult");
var request = {};
const request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractName = global.contractInstance;
request.sequencing = global.instanceSequencing;
request.useP2P = global.useP2P;
request.isDebug = executeContractAsDebug.checked;
var operation = $("#selectContractFunction")[0].value;
if (operation == " " && operation == undefined) {
const operation = $("#selectContractFunction")[0].value;
if (operation === " " && !operation) {
myToast("执行合约", "请选择合约方法!");
return;
}
request.arg = "{\"action\":\"" + operation + "\",\"arg\":\""
+ $("#arg")[0].value + "\"}";
request.arg = `{"action":"${operation}","arg":"${argDiv.value}"}`;
request.pubkey = global.sm2Key.publicKey;
request.withDyanmicAnalysis = true;
request.signature = sm2.doSignature(request.contractID + "|" + operation
+ "|" + $("#arg")[0].value + "|" + global.sm2Key.publicKey,
global.sm2Key.privateKey, {hash: true, der: true});
request.signature = sm2.doSignature(
`${request.contractID}|${operation}|${argDiv.value}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
}
var executeContract = function () {
var request = {};
function executeContract() {
const argDiv = $('#arg')[0];
const request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = global.contractInstance;
var operation = $("#selectContractFunction")[0].value;
if (operation == " " && operation == undefined) {
const operation = $("#selectContractFunction")[0].value;
if (operation === " " && !operation) {
myToast("执行合约", "请选择合约方法!");
return;
}
request.operation = operation;
request.arg = $("#arg")[0].value;
request.arg = argDiv.value;
request.pubkey = global.sm2Key.publicKey;
request.isDebug = executeContractAsDebug.checked;
console.log(request.arg);
request.signature = sm2.doSignature(request.contractID + "|" + operation
+ "|" + $("#arg")[0].value + "|" + global.sm2Key.publicKey,
global.sm2Key.privateKey, {hash: true, der: true});
request.signature = sm2.doSignature(
`${request.contractID}|${operation}|${argDiv.value}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
}
var onExecuteResult = function (obj) {
function onExecuteResult(obj) {
console.log("onExecuteResult obj.data", obj.data);
try {
var result = obj;
var styleTail = "<br>字符串格式";
const result = obj;
let styleTail = "<br>字符串格式";
$("#responseStatus").html("执行状态:" + result.status);
if (result.analysis != undefined) {
if (result['analysis']) {
$("#responseArea")[0].value = "执行结果:" + result.result + "\n动态分析结果:"
+ result.analysis;
+ result['analysis'];
} else {
if (result.result instanceof Object) {
$("#responseArea")[0].value = JSON.stringify(result.result);
@ -430,27 +422,25 @@ var onExecuteResult = function (obj) {
} else
$("#responseArea")[0].value = result.result;
}
$("#responseID").html("请求ID:" + obj.responseID);
$("#responseTime").html("响应时间:" + obj.executeTime + ("ms") + styleTail);
$("#responseID").html(`请求ID:${obj['responseID']}`);
$("#responseTime").html(`响应时间:${obj['executeTime']}ms${styleTail}`);
} catch (e) {
$("#responseStatus").html("执行状态:Fail");
$("#responseStatus").html("执行状态Failed");
$("#responseArea")[0].value = obj.data;
$("#responseID").html("请求ID:" + obj.responseID);
$("#responseTime").html("响应时间:" + obj.executeTime + ("ms"));
$("#responseID").html(`请求ID${obj['responseID']}`);
$("#responseTime").html(`响应时间:${obj['executeTime']}ms`);
}
};
}
var onHashResult = function (obj) {
function onHashResult(obj) {
$("#hashResult").html("数链指纹:" + obj.data);
};
}
var drawCPTable = function (table) {
function drawCPTable(table) {
console.log("drawCPTable");
global.contractprocess = table.data;
if ($("#ciTabDiv").css("height") == "0px") {
console.log("drawciTabDiv: ignore");
if ($("#ciTabDiv").css("height") === "0px") {
console.log("drawCPTableDiv: ignore");
return;
}
var dtLang = {
@ -480,39 +470,39 @@ var drawCPTable = function (table) {
"sSortDescending": ": 以降序排列此列"
}
};
var tableHead = "<table id='cpTabDivTab' class='table display row-border'><thead><tr><th>序号</th><th>PID</th><th>是否泄漏</th><th>启动时间</th><th>CPUUser</th><th>CPUSyss</th><th>resident</th><th>memory</th><th>管理</th></tr></thead><tbody>";
var tableTail = "</tbody></table>";
const tableHead = `<table id='cpTabDivTab' class='table display row-border'>
<thead><tr>
<th>序号</th>
<th>PID</th>
<th>是否泄漏</th>
<th>启动时间</th>
<th>CPUUser</th>
<th>CPUSyss</th>
<th>resident</th>
<th>memory</th>
<th>管理</th>
</tr></thead><tbody>`;
const tableTail = "</tbody></table>";
table = table.data;
console.log("drawciTable");
var html = tableHead;
for (var i = 0; i < table.length; i++) {
html += "<tr><td>";
html += (i + 1);
html += "</td> <td>";
html += table[i].pid;
html += "</td> <td>";
html += table[i].isLeak;
html += "</td> <td>";
html += new Date(table[i].cpuStart).toLocaleString();
html += "</td> <td>";
html += table[i].cpuTotal;
html += "</td> <td>";
html += table[i].cpuSys;
html += "</td> <td>";
html += ((table[i].resident) / (1024 * 1024)).toFixed(2) + "MB";
html += "</td><td>";
html += ((table[i].memsize) / (1024 * 1024)).toFixed(2) + "MB";
html += "</td> <td style='padding:2px 12px 2px 12px'>";
html += "<button onclick='stopContractByPID(\"" + table[i].pid + "\")' class='btn btn-secondary'>" + "停止</button>"
//table[i].resultCheck;
// html += "</td> <td>";
// html += "<button class='btn btn-outline-secondary' type='button'
// onclick='viewContractInstance("+ table[i].contractID +
// ")'>更多</button>";
html += "</td> </tr>";
console.log("drawConInfoTable");
let html = tableHead;
for (let i = 0; i < table.length; i++) {
html += `<tr>
<td>${i + 1}</td>
<td>${table[i].pid}</td>
<td>${table[i]['isLeak']}</td>
<td>${new Date(table[i]['cpuStart']).toLocaleString()}/td>
<td>${table[i]['cpuTotal']}</td>
<td>${table[i]['cpuSys']}</td>
<td>${(table[i]['resident'] / (1024 * 1024)).toFixed(2)}MB</td>
<td>${(table[i]['memsize'] / (1024 * 1024)).toFixed(2)}MB</td>
<td style='padding:2px 12px 2px 12px'>
<button onclick="stopContractByPID('${table[i].pid}')" class='btn btn-secondary'>停止</button>
</td>
</tr>`
}
html += tableTail;
html = "<h5 class='card-title'>合约进程列表</h5>" + html;
html = `<h5 class='card-title'>合约进程列表</h5>${html}`;
$("#cpTabDiv").html(html);
$("#cpTabDivTab").DataTable(
@ -522,7 +512,7 @@ var drawCPTable = function (table) {
dataIndex) {
},
"headerCallback": function (thead, data, start, end, display) {
"headerCallback": function (thead/*, data, start, end, display*/) {
$(thead).css("background", primaryColor);
$(thead).css("color", "white");
$(thead).children().css("background", primaryColor);
@ -535,7 +525,7 @@ var drawCPTable = function (table) {
"columnDefs": [
{
"targets": 1,
"render": function (data, type, row, meta) {
"render": function (data/*, type, row, meta*/) {
if (data.length > 10)
// return "<span title='" + data + "'>"
// + data.substring(0, 10)
@ -547,16 +537,17 @@ var drawCPTable = function (table) {
},]
});
};
var stopContractByPID = function (pid) {
}
function stopContractByPID(pid) {
$("#dialogBodyDiv").html("是否停止PID:" + pid);
showDialog("请确认", function () {
var request = {};
request.action = "killProcessByPID";
request.pid = pid;
global.wssocket.send(JSON.stringify(request));
var request2 = {};
request2.action = "listLeakContractProcess";
global.wssocket.send(JSON.stringify(request2));
global.wssocket.send(JSON.stringify({
action: 'killProcessByPID',
pid: pid
}));
global.wssocket.send(JSON.stringify({
action: 'listLeakContractProcess'
}));
});
};
}

View File

@ -28,10 +28,10 @@ function WSHandler(event) {
onDeleteFile(obj);
break;
case "onStartContract":
onStartContract(obj);
break;
// onStartContract(obj);
// break;
case "onStartContractAsDebug":
onStartContractAsDebug(obj);
onStartContract(obj);
break;
case "onListContractProcess":
onListContractProcess(obj);
@ -140,9 +140,10 @@ function getControlWsUrl(host) {
}
function initWSocket() {
console.log("[nodecenterManagement.js] initWSocket : ");
console.log("[OnlineIDE.js] initWSocket : ");
let host = document.location.host;
let url = getControlWsUrl(global.urlparam && global.urlparam.nodeAddr ? global.urlparam.nodeAddr : host);
let url = getControlWsUrl(
global.urlparam && global.urlparam['nodeAddr'] ? global.urlparam['nodeAddr'] : host);
// console.log("connect ws:" + url);
global.wssocket = createWssocket(url, function () {
getSession();
@ -201,7 +202,7 @@ function onStartContract(data) {
showDialog("部署合约成功", function() {
});
}*/
startResult.innerText = result.status + "(" + data.executeTime + "ms" + ")";
startResult.innerText = `${result.status}(${data['executeTime']}ms)`;
if (result.status !== "Success") {
let body = "<div class='input-group mb-3'>";
body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>";
@ -213,33 +214,33 @@ function onStartContract(data) {
}
}
function onStartContractAsDebug(data) {
// console.log(data);
const result = JSON.parse(data.data);
/* if (result.isInsnLimit) {
global.withEvaluatesAnalysis = true;
$("#dialogBodyDiv").text("此合约在执行时会消耗gas,请在执行前进行预估,根据预估值给出相应的值,建议给出的值大于预估值");
showDialog("部署合约成功", function() {
});
}*/
startResult.innerText = result.status + "(" + data.executeTime + "ms" + ")";
if (result.status !== "Success") {
let body = "<div class='input-group mb-3'>";
body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>";
body += " </div>";
$("#dialogBodyDiv").html(body);
$("#onStartContractFailedContent")[0].value = result.result
showDialog("部署合约失败", function () {
});
}
}
// function onStartContractAsDebug(data) {
// // console.log(data);
// const result = JSON.parse(data.data);
// /* if (result.isInsnLimit) {
// global.withEvaluatesAnalysis = true;
// $("#dialogBodyDiv").text("此合约在执行时会消耗gas,请在执行前进行预估,根据预估值给出相应的值,建议给出的值大于预估值");
// showDialog("部署合约成功", function() {
// });
// }*/
// startResult.innerText = `${result.status}(${data['executeTime']}ms)`;
// if (result.status !== "Success") {
// let body = "<div class='input-group mb-3'>";
// body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>";
// body += " </div>";
// $("#dialogBodyDiv").html(body);
// $("#onStartContractFailedContent")[0].value = result.result
// showDialog("部署合约失败", function () {
// });
// }
// }
function onKillContractProcess(data) {
// console.log(data);
if (data.data === "success") {
listContracts();
}
stopResult.innerText = data.data + "(" + data.executeTime + "ms" + ")";
stopResult.innerText = `${data.data}(${data['executeTime']}ms)`;
}
function onKillAllContract(data) {
@ -275,7 +276,7 @@ function onQueryContractInstanceInfoByDOI(data) {
initContractInstanceInfoArea();
// console.log(data);
$("#contractInstanceInfoTitle")
.html(" (" + data.executeTime + "ms)");
.html(` (${data['executeTime']}ms)`);
global.contractInstanceInfoEditor.setValue(data.data);
let totalLines = global.contractInstanceInfoEditor.lineCount();
@ -292,7 +293,7 @@ function onImportContractInstanceCodeByDOI(data) {
initContractInstanceInfoArea();
// console.log(data);
$("#contractInstanceInfoTitle")
.html(" (" + data.executeTime + "ms)");
.html(` (${data['executeTime']}ms)`);
global.contractInstanceInfoEditor.setValue(data.data);
let totalLines = global.contractInstanceInfoEditor.lineCount();
@ -307,14 +308,12 @@ function onImportContractInstanceCodeByDOI(data) {
global.wssocket.send("{\"action\":\"listProjects\",\"isPrivate\":true}");
}
function onListContractProcess(data) {
// console.log(data);
mainVue.contracts = [];
var list = JSON.parse(data.data);
for (var i = 0; i < list.length; i++) {
if (list[i].contractStatus != "KILLED") {
const list = JSON.parse(data.data);
for (let i = 0; i < list.length; i++) {
if (list[i].contractStatus !== "KILLED") {
mainVue.contracts.push(list[i]);
}
}
@ -359,25 +358,25 @@ function initResponseAndOutputArea() {
}
function onExecuteResult(obj) {
const executeResultTitleEl = $("#executeResultTitle")
const data = obj;
$("#executeResultTitle")
.html(data.status + " (" + obj.executeTime + "ms) 未知格式");
executeResultTitleEl
.html(`${data.status} (${obj['executeTime']}ms) 未知格式`);
if (data.result instanceof Object) {
$("#executeResultTitle")
.html(data.status + " (" + obj.executeTime + "ms) JSON格式");
executeResultTitleEl
.html(`${data.status} (${obj['executeTime']}ms) JSON格式`);
global.responseEditor.setValue(JSON.stringify(data.result));
} else if (typeof data.result == 'string') {
$("#executeResultTitle")
.html(data.status + " (" + obj.executeTime + "ms) 字符串格式");
executeResultTitleEl
.html(`${data.status} (${obj['executeTime']}ms) 字符串格式`);
global.responseEditor.setValue(data.result);
} else {
if (typeof data.result == 'number') {
$("#executeResultTitle")
.html(data.status + " (" + obj.executeTime + "ms) 数值格式");
executeResultTitleEl
.html(`${data.status} (${obj['executeTime']}ms) 数值格式`);
} else if (typeof data.result == 'boolean') {
$("#executeResultTitle")
.html(data.status + " (" + obj.executeTime + "ms) 布尔型格式");
executeResultTitleEl
.html(`${data.status} (${obj['executeTime']}ms) 布尔型格式`);
}
global.responseEditor.setValue(data.result.toString());
}
@ -391,9 +390,9 @@ function onExecuteResult(obj) {
}, {
line: totalLines
});
if (data.analysis && data.analysis.length > 0) {
// displayOutputStr(data.analysis);
}
// if (data['analysis'] && data['analysis'].length > 0) {
// displayOutputStr(data.analysis);
// }
}
function onGenerateReadme(obj) {

923
js/cm.js
View File

@ -1,527 +1,528 @@
var WSHandler = function(event) {
// console.log(event);
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case 'ping':
case 'poing':
break;
case 'onExecuteResult':
onExecuteResult(obj);
break;
case 'onListContractProcess':
onListContractProcess(obj);
break;
case 'onStartContract':
onStartContract(obj);
break;
case 'onKillContractProcess':
logComm(obj);
break;
case 'onKillAllContract':
onKillAllContract(obj);
break;
case 'onOutputStream':
displayOutput(obj);
break;
case 'onSaveFile':
onSaveFile(obj);
break;
case 'uploadNext':
onUploadNext(obj);
break;
case 'sendNextSegment':
global.wssocket.sendNextSegment();
break;
case 'sendSeg':
receiveSeg(obj);
break;
case 'onException':
logException(obj);
break;
case 'onHashResult':
onHashResult(obj);
break;
case 'onDumpContract':
onDumpContract(obj);
break;
default:
displayOutput(obj);
break;
}
} catch (err) {
console.log(err);
}
var WSHandler = function (event) {
// console.log(event);
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case 'ping':
case 'poing':
break;
case 'onExecuteResult':
onExecuteResult(obj);
break;
case 'onListContractProcess':
onListContractProcess(obj);
break;
case 'onStartContract':
onStartContract(obj);
break;
case 'onKillContractProcess':
logComm(obj);
break;
case 'onKillAllContract':
onKillAllContract(obj);
break;
case 'onOutputStream':
displayOutput(obj);
break;
case 'onSaveFile':
onSaveFile(obj);
break;
case 'uploadNext':
onUploadNext(obj);
break;
case 'sendNextSegment':
global.wssocket.sendNextSegment();
break;
case 'sendSeg':
receiveSeg(obj);
break;
case 'onException':
logException(obj);
break;
case 'onHashResult':
onHashResult(obj);
break;
case 'onDumpContract':
onDumpContract(obj);
break;
default:
displayOutput(obj);
break;
}
} catch (err) {
console.log(err);
}
};
var logException = function(obj) {
global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj);
var logException = function (obj) {
global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj);
};
var logComm = function(obj) {
console.log(obj);
var logComm = function (obj) {
console.log(obj);
};
var displayOutput = function(obj) {
displayOutputStr(obj.data);
var displayOutput = function (obj) {
displayOutputStr(obj.data);
};
var displayOutputStr = function(str) {
console.log("[cm.js] displayOutput:" + str);
var displayOutputStr = function (str) {
console.log("[cm.js] displayOutput:" + str);
};
var getControlWsUrl = function(host) {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor";
return prefix + host + path;
var getControlWsUrl = function (host) {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor";
return prefix + host + path;
};
var initWSocket = function() {
var host = getHost();
var url = getControlWsUrl(host);
global.wssocket = createWssocket(url, function() {
listContractProcess();
}, WSHandler);
var initWSocket = function () {
var host = getHost();
var url = getControlWsUrl(host);
global.wssocket = createWssocket(url, function () {
listContractProcess();
}, WSHandler);
};
// ====== wsHandler
var onStartContract = function(obj) {
// console.log(obj);
var result = JSON.parse(obj.data);
var onStartContract = function (obj) {
// console.log(obj);
var result = JSON.parse(obj.data);
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid;
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid;
};
var onExecuteResult = function(obj) {
// console.log(obj);
var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result);
// console.log(data);
var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({
line : 0,
ch : 0
}, {
line : totalLines
});
if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis);
}
var onExecuteResult = function (obj) {
// console.log(obj);
var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result);
// console.log(data);
var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({
line: 0,
ch: 0
}, {
line: totalLines
});
if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis);
}
};
var onListContractProcess = function(obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
var html = "";
var onListContractProcess = function (obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
var html = "";
// $("#tabdiv").html("");
global.contractName2ID = {};
for (var i = 0; i < data.length; i++) {
global.contractName2ID[data[i].name] = data[i].id;
html += "<li class=\"ui-widget-content\">" + data[i].name + "</li>";
// $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text(
// data[i].id));
}
$("#contractList").html(html);
$("#contractList").selectable(
{
stop : function() {
var result = "";
global.selectedContracts = [];
global.selectedContractIndexs = [];
// $("#tabdiv").html("");
global.contractName2ID = {};
for (var i = 0; i < data.length; i++) {
global.contractName2ID[data[i].name] = data[i].id;
html += "<li class=\"ui-widget-content\">" + data[i].name + "</li>";
// $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text(
// data[i].id));
}
$("#contractList").html(html);
$("#contractList").selectable(
{
stop: function () {
var result = "";
global.selectedContracts = [];
global.selectedContractIndexs = [];
$(".ui-selected", this).each(function() {
var index = $("#contractList li").index(this);
global.selectedContracts.push(this.innerText);
global.selectedContractIndexs.push(index);
});
// console.log("[cm.js] selectContractResult:"
// + global.selectedContracts);
}
});
// $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text));
$(".ui-selected", this).each(function () {
var index = $("#contractList li").index(this);
global.selectedContracts.push(this.innerText);
global.selectedContractIndexs.push(index);
});
// console.log("[cm.js] selectContractResult:"
// + global.selectedContracts);
}
});
// $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text));
};
var onSaveFile = function(obj) {
alert("Save file:" + obj.data);
var onSaveFile = function (obj) {
alert("Save file:" + obj.data);
};
var onKillAllContract = function(obj) {
customAlert(obj.data);
var onKillAllContract = function (obj) {
customAlert(obj.data);
};
var onHashResult = function(obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
var onHashResult = function (obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
};
var onDumpContract = function(obj) {
// console.log("DumpResult:" + obj.data);
if (obj.data == "success") {
listDumpMemoryDir();
}
var onDumpContract = function (obj) {
// console.log("DumpResult:" + obj.data);
if (obj.data == "success") {
listDumpMemoryDir();
}
};
// ====== wsHandler done!
var switchContract = function(off) {
// var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id;
var pingObj = {};
pingObj.action = "connectTo";
var switchContract = function (off) {
// var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id;
var pingObj = {};
pingObj.action = "connectTo";
pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj));
pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj));
}
var countChar = function(str, c) {
var ret = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c)
ret++;
}
return ret;
var countChar = function (str, c) {
var ret = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c)
ret++;
}
return ret;
}
var generate = function() {
$.ajax({
url : "./SCManager?action=generatePrivateKey",
dataType : "json"
}).done(function(result) {
if (result.status) {
localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!");
initRest();
}
});
var generate = function () {
$.ajax({
url: "./SCManager?action=generatePrivateKey",
dataType: "json"
}).done(function (result) {
if (result.status) {
localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!");
initRest();
}
});
}
var initGlobal = function() {
window.global = {};
global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100) {
generate();
} else
initRest();
var initGlobal = function () {
window.global = {};
global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100) {
generate();
} else
initRest();
}
var setMainHost = function() {
var mainHost = $("#targetHost")[0].value;
localStorage.setItem("mainHost", mainHost);
var setMainHost = function () {
var mainHost = $("#targetHost")[0].value;
localStorage.setItem("mainHost", mainHost);
}
var initRest = function() {
var mainHost = localStorage.getItem("mainHost");
if (mainHost == undefined) {
localStorage.setItem("mainHost", "39.106.6.6:8080");
mainHost = localStorage.getItem("mainHost");
}
$("#targetHost")[0].value = mainHost;
var initRest = function () {
var mainHost = localStorage.getItem("mainHost");
if (mainHost == undefined) {
localStorage.setItem("mainHost", "39.106.6.6:8080");
mainHost = localStorage.getItem("mainHost");
}
$("#targetHost")[0].value = mainHost;
};
var onUploadNext = function() {
var request = {};
request.action = "startContract";
request.owner = global.privKey;
request.isPartial = false;
request.script = global.toSend;
if (request.script.length > 1024) {
global.toSend = request.script.substr(1024);
request.script = request.script.substr(0, 1024);
request.isPartial = true;
} else {
global.toSend = "";
}
// console.log("Upload nextPart:");
// console.log(JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
var onUploadNext = function () {
var request = {};
request.action = "startContract";
request.owner = global.privKey;
request.isPartial = false;
request.script = global.toSend;
if (request.script.length > 1024) {
global.toSend = request.script.substr(1024);
request.script = request.script.substr(0, 1024);
request.isPartial = true;
} else {
global.toSend = "";
}
// console.log("Upload nextPart:");
// console.log(JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var disposeContract = function(request, host, contractIndex) {
// fileWs.send(JSON.stringify(request));
// console.log("[cm.js] disposeContract:" + host + "-->"
// + JSON.stringify(request));
var wsUrl = getFileWsUrl(host);
var fileWs = new WebSocket(wsUrl);
fileWs.onerror = function(error) {
console.log(error);
};
fileWs.contractIndex = contractIndex;
fileWs.onopen = function(error) {
fileWs.send(JSON.stringify(request));
};
fileWs.currHost = host;
fileWs.zipInfo = request;
fileWs.onmessage = downloadHandler;
var disposeContract = function (request, host, contractIndex) {
// fileWs.send(JSON.stringify(request));
// console.log("[cm.js] disposeContract:" + host + "-->"
// + JSON.stringify(request));
var wsUrl = getFileWsUrl(host);
var fileWs = new WebSocket(wsUrl);
fileWs.onerror = function (error) {
console.log(error);
};
fileWs.contractIndex = contractIndex;
fileWs.onopen = function (error) {
fileWs.send(JSON.stringify(request));
};
fileWs.currHost = host;
fileWs.zipInfo = request;
fileWs.onmessage = downloadHandler;
}
var updateProgress = function(progressIndex, host, progress) {
if (isNaN(progress)) {
console.log("StopHere");
}
var hostMap = global.progressStat.get(progressIndex);
hostMap.set(host, progress);
var total = 0;
for (var j = 0; j < global.hosts.length; j++) {
total += hostMap.get(global.hosts[j]);
}
// console.log("[cm.js] updateProgress:" + total);
$($("#progressBars .progressDiv")[progressIndex]).progressbar({
value : Math.floor(total / global.hosts.length)
});
var updateProgress = function (progressIndex, host, progress) {
if (isNaN(progress)) {
console.log("StopHere");
}
var hostMap = global.progressStat.get(progressIndex);
hostMap.set(host, progress);
var total = 0;
for (var j = 0; j < global.hosts.length; j++) {
total += hostMap.get(global.hosts[j]);
}
// console.log("[cm.js] updateProgress:" + total);
$($("#progressBars .progressDiv")[progressIndex]).progressbar({
value: Math.floor(total / global.hosts.length)
});
};
var downloadHandler = function(obj, wssocket) {
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case "onDownloadContract":
// console.log(JSON.stringify(obj));
updateProgress(this.contractIndex, this.currHost,
obj.executeTime * 0.95);
//console.log("[cm.js] obj.executeTime = " + obj.executeTime * 0.95 + " ; " + obj.executeTime);
if (obj.data == "success") {
console.log("[cm.js] downloadHandler successs");
startContractWithHost(this.currHost, this.zipInfo.fileName,
this.contractIndex);
this.close();
}
break;
case "onStartContract":
updateProgress(wssocket.contractIndex, wssocket.currHost, 100);
wssocket.close();
break;
default:
}
} catch (err) {
console.log(err);
}
var downloadHandler = function (obj, wssocket) {
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case "onDownloadContract":
// console.log(JSON.stringify(obj));
updateProgress(this.contractIndex, this.currHost,
obj.executeTime * 0.95);
//console.log("[cm.js] obj.executeTime = " + obj.executeTime * 0.95 + " ; " + obj.executeTime);
if (obj.data == "success") {
console.log("[cm.js] downloadHandler successs");
startContractWithHost(this.currHost, this.zipInfo.fileName,
this.contractIndex);
this.close();
}
break;
case "onStartContract":
updateProgress(wssocket.contractIndex, wssocket.currHost, 100);
wssocket.close();
break;
default:
}
} catch (err) {
console.log(err);
}
}
var getControlWsUrl = function(host) {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor";
return prefix + host + path;
var getControlWsUrl = function (host) {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor";
return prefix + host + path;
};
var startContractWithHost = function(host, fileName, contractIndex) {
//console.log("[cm.js] host = " + host + " ; fileName" + fileName + " ; contractIndex = " + contractIndex);
var wsUrl = getControlWsUrl(host);
//console.log("[cm.js] this = " + this);
var controller = createWssocket(wsUrl, function() {
// onopen;
var request = {};
request.action = "startContractInTempZips";
request.owner = global.privKey;
request.path = fileName;
request.script = "empty";
controller.send(JSON.stringify(request));
this.contractIndex = contractIndex;
this.currHost = host;
}, downloadHandler);
var startContractWithHost = function (host, fileName, contractIndex) {
//console.log("[cm.js] host = " + host + " ; fileName" + fileName + " ; contractIndex = " + contractIndex);
var wsUrl = getControlWsUrl(host);
//console.log("[cm.js] this = " + this);
var controller = createWssocket(wsUrl, function () {
// onopen;
var request = {};
request.action = "startContractInTempZips";
request.owner = global.privKey;
request.path = fileName;
request.script = "empty";
controller.send(JSON.stringify(request));
this.contractIndex = contractIndex;
this.currHost = host;
}, downloadHandler);
};
var startContract = function() {
global.progressStat = new Map();
for (var i = 0; i < global.selectedProjects.length; i++) {
var map = new Map();
for (var j = 0; j < global.hosts.length; j++) {
map.set(global.hosts[j], 0);
}
global.progressStat.set(global.selectedProjectIndexs[i], map);
}
var startContract = function () {
for (var i = 0; i < global.selectedProjects.length; i++)
for (var j = 0; j < global.hosts.length; j++) {
var request = {};
request.action = "downloadContract";
request.mainHost = $("#targetHost")[0].value;
request.projectName = global.selectedProjects[i].replace(" ", "");
request.fileName = request.projectName + "_" + new Date().getTime()
+ ".ypk";
disposeContract(request, global.hosts[j],
global.selectedProjectIndexs[i]);
}
global.progressStat = new Map();
for (var i = 0; i < global.selectedProjects.length; i++) {
var map = new Map();
for (var j = 0; j < global.hosts.length; j++) {
map.set(global.hosts[j], 0);
}
global.progressStat.set(global.selectedProjectIndexs[i], map);
}
for (var i = 0; i < global.selectedProjects.length; i++)
for (var j = 0; j < global.hosts.length; j++) {
var request = {};
request.action = "downloadContract";
request.mainHost = $("#targetHost")[0].value;
request.projectName = global.selectedProjects[i].replace(" ", "");
request.fileName = request.projectName + "_" + new Date().getTime()
+ ".ypk";
disposeContract(request, global.hosts[j],
global.selectedProjectIndexs[i]);
}
};
var dumpContract = function() {
var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "dumpContract";
pingObj.target = "/memoryDumps/" + global.selectedContracts[i] + "_"
+ new Date().getTime() + ".dyjs";
pingObj.contractID = global.selectedContracts[i];
//console.log("[cm.js] pingObj.target = " + pingObj.target);
//console.log("[cm.js] pingObj.contractID = " + pingObj.contractID);
global.wssocket.send(JSON.stringify(pingObj));
}
var dumpContract = function () {
var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "dumpContract";
pingObj.target = "/memoryDumps/" + global.selectedContracts[i] + "_"
+ new Date().getTime() + ".dyjs";
pingObj.contractID = global.selectedContracts[i];
//console.log("[cm.js] pingObj.target = " + pingObj.target);
//console.log("[cm.js] pingObj.contractID = " + pingObj.contractID);
global.wssocket.send(JSON.stringify(pingObj));
}
};
var loadMemory = function() {
var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "loadMemory";
pingObj.target = "/memoryDumps/" + global.selectedDumps[0];
pingObj.contractID = global.selectedContracts[i];
global.wssocket.send(JSON.stringify(pingObj));
}
var loadMemory = function () {
var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "loadMemory";
pingObj.target = "/memoryDumps/" + global.selectedDumps[0];
pingObj.contractID = global.selectedContracts[i];
global.wssocket.send(JSON.stringify(pingObj));
}
};
var executeContractWithDynamicResult = function() {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
var executeContractWithDynamicResult = function () {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var executeContract = function() {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
var executeContract = function () {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var listContractProcess = function() {
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
var listContractProcess = function () {
global.wssocket.send(JSON.stringify({
action: 'listContractProcess',
filters: 2
}));
};
var killContractProcess = function() {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.name = $("#tabdiv")[0].value;
request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
var killContractProcess = function () {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.name = $("#tabdiv")[0].value;
request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
};
var staticVerify = function() {
var request = {};
request.action = "staticVerifyContract";
// TODO should be pubkey
request.owner = global.privKey;
request.isPartial = false;
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
var staticVerify = function () {
var request = {};
request.action = "staticVerifyContract";
// TODO should be pubkey
request.owner = global.privKey;
request.isPartial = false;
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
};
var downloadContract = function() {
if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html",
"/downLoadServlet?projectName=");
url += projectName;
window.open(url);
var downloadContract = function () {
if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html",
"/downLoadServlet?projectName=");
url += projectName;
window.open(url);
};
var killAllContract = function() {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
var killAllContract = function () {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var customAlert = function(message, title) {
if (!title)
title = 'Alert';
var customAlert = function (message, title) {
if (!title)
title = 'Alert';
if (!message)
message = 'No Message to Display.';
if (!message)
message = 'No Message to Display.';
$('<div></div>').html(message).dialog({
title : title,
resizable : false,
modal : true,
buttons : {
'Ok' : function() {
$(this).dialog('close');
}
}
});
$('<div></div>').html(message).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function () {
$(this).dialog('close');
}
}
});
}
var init = function() {
initGlobal();
initWSocket();
global.hosts = [];
$("#serverList").selectable({
stop : function() {
var result = "";
global.hosts = [];
$(".ui-selected", this).each(function() {
var index = $("#serverList li").index(this);
global.hosts.push(this.innerText);
});
// console.log("[cm.js] selectResult:" + global.hosts);
}
});
var init = function () {
initGlobal();
initWSocket();
global.hosts = [];
$("#serverList").selectable({
stop: function () {
var result = "";
global.hosts = [];
$(".ui-selected", this).each(function () {
var index = $("#serverList li").index(this);
global.hosts.push(this.innerText);
});
// console.log("[cm.js] selectResult:" + global.hosts);
}
});
};
var getRequestParameters = function() {
var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {};
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("=");
if (data.length == 2) {
params[data[0]] = data[1];
}
}
return params;
var getRequestParameters = function () {
var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {};
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("=");
if (data.length == 2) {
params[data[0]] = data[1];
}
}
return params;
};
var initHello = function() {
var param = getRequestParameters();
var type = parseInt(param["type"]);
var template;
switch (type) {
case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 3:
var contractID = param["contractID"];
$.ajax({
url : "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType : "json"
}).done(function(result) {
global.fileContentMap.set(contractID, result.data);
addTab({
"title" : contractID
});
var initHello = function () {
var param = getRequestParameters();
var type = parseInt(param["type"]);
var template;
switch (type) {
case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 3:
var contractID = param["contractID"];
$.ajax({
url: "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType: "json"
}).done(function (result) {
global.fileContentMap.set(contractID, result.data);
addTab({
"title": contractID
});
});
return;
default:
return;
}
global.scriptEditor.setValue(template);
});
return;
default:
return;
}
global.scriptEditor.setValue(template);
};

View File

@ -50,7 +50,7 @@ var onListMemoryFiles = function(obj){
console.log(htm);
$("#selectMemeryFiles").html(htm);
changeMemeryFiles($("#selectMemeryFiles")[0].value);
changeMemoryFiles($("#selectMemeryFiles")[0].value);
};
var transferTo = function(){

View File

@ -1,151 +1,153 @@
var listContractProcess = function() {
console.log("listContractProcess : ");
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
};
var onListContractProcess = function(obj) {
var userManTab = $("#v-pills-contractInstance-tab")[0];
var isActive = (userManTab.getAttribute("aria-selected") == "true");
if (isActive) {
onListContractProcess1(obj);
} else {
onListContractProcess2(obj);
}
};
var changeContractProcess = function(obj) {
global.contractProcess = obj; // 代码管理菜单选中的合约
console.log("oooooooooooo" + global.contractProcess);
//showPermissionList(global.contractProcess);
};
var onListContractProcess2 = function(obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
// $("#contractProcess").editableSelect('clear');
// $("#tabdiv").html("");
global.contractName2ID = {};
//global.permissionNameMap = {};
var name = "";
var htm = "<option selected>选择合约进程</option>";
for (var i = 0; i < data.length; i++) {
// htm += "<option value='" + 0 + "'>" + data[i].name + "</option>";
htm += "<option selected>" + data[i].name + "</option>";
global.contractName2ID[data[i].name] = data[i].id;
//global.permissionNameMap[data[i].name] = data[i].contractPermission;
console.log(htm);
name = data[i].name;
}
//showPermissionList(name);
console.log(htm);
$("#contractProcess").html(htm);
/*
* $("#contractProcess").editableSelect({ effects: 'slide',
* //可选参数default、fade filter: true //false 不过滤,否则选中后其它选项消失 });
*/
/*
* if(data.length > 0){ for (var i = 0; i < data.length; i++) {
* console.log(i); $("#contractProcess").editableSelect('add',
* data[i].name); global.contractName2ID[data[i].name] = data[i].id; //
* $("#tabdiv").append( // $("<option></option>").attr("value",
* data[i].id).text( // data[i].id)); } } if (data.length > 0)
* $("#contractProcess").editableSelect()[0].value = data[0].name;
*/
};
var addTcpNodeUnits = function(data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var unitID = data[i].key;
var nodes = JSON.parse(data[i].value);
var json = {};
json.type = "TCP";
json.key = unitID;
json.value = nodes;
addNodeUnit(json);
}
}
};
var listSelectUnits = function(data) {
console.log(data);
global.units = {};
var htm = "";
if (data.length > 0) {
// data的key是创建人公钥_时间戳,value是nodes的ID
for (var i = 0; i < data.length; i++) {
var unitID = data[i].key;
var nodes = JSON.parse(data[i].value);
var at_ = data[i].key.indexOf("_");
console.log(nodes);
htm += "<option>集群:" + unitID.substring(at_ + 1)
+ "</option>";
global.units[unitID.substring(at_ + 1)] = nodes;
}
}
htm += "<option selected>选择节点集群</option>";
htm += "<option>无</option>";
console.log(htm);
$("#selectUnits").html(htm);
function listContractProcess() {
console.log("listContractProcess : ");
global.wssocket.send(JSON.stringify({
action: 'listContractProcess',
filters: 2
}));
}
var onCancelAuth = function(obj) {
myToast("取消权限", obj.data);
if (obj.data == "success") {
}
};
var setPermission = function(data) {
var request = {};
request.resetContractProcess = data.name;
console.log(request.resetContractName);
request.closePer = data.permission;
request.oldPer = data.oldPermission;
request.isOpen = data.isOpen;
request.action = "setPermission";
global.wssocket.send(JSON.stringify(request));
};
var onSetPermission = function(obj) {
console.log(obj);
function onListContractProcess(obj) {
const userManTab = $("#v-pills-contractInstance-tab")[0];
const isActive = (userManTab.getAttribute("aria-selected") === "true");
if (isActive) {
onListContractProcess1(obj);
} else {
onListContractProcess2(obj);
}
}
var html = "<div class='input-group mb-2'>";
function changeContractProcess(obj) {
global.contractProcess = obj; // 代码管理菜单选中的合约
console.log("oooooooooooo" + global.contractProcess);
//showPermissionList(global.contractProcess);
}
html += "<div class='input-group-prepend'>";
html += "<span class='input-group-text' id='inputGroup-sizing-default'>";
html += "状态保存策略:" + "</span></div>";
html += "<div class='input-group-append'>";
html += "<select id='selectDumpPeriod2' class='custom-select' style='appearance: none; -webkit-appearance: none;'>";
function onListContractProcess2(obj) {
const data = JSON.parse(obj.data);
if(period == "43200000"){
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
}else if(period == "86400000"){
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
}else if(period == "172800000"){
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
}else{
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
}
};
global.contracts = data;
// $("#contractProcess").editableSelect('clear');
// $("#tabdiv").html("");
var onListLeakContractProcess = function(obj){
global.contractName2ID = {};
//global.permissionNameMap = {};
let name = "";
let htm = "<option selected>选择合约进程</option>";
for (let i = 0; i < data.length; i++) {
// htm += "<option value='" + 0 + "'>" + data[i].name + "</option>";
htm += "<option selected>" + data[i].name + "</option>";
global.contractName2ID[data[i].name] = data[i].id;
//global.permissionNameMap[data[i].name] = data[i].contractPermission;
console.log(htm);
name = data[i].name;
}
//showPermissionList(name);
console.log(htm);
$("#contractProcess").html(htm);
/*
* $("#contractProcess").editableSelect({ effects: 'slide',
* //可选参数default、fade filter: true //false 不过滤,否则选中后其它选项消失 });
*/
/*
* if(data.length > 0){ for (var i = 0; i < data.length; i++) {
* console.log(i); $("#contractProcess").editableSelect('add',
* data[i].name); global.contractName2ID[data[i].name] = data[i].id; //
* $("#tabdiv").append( // $("<option></option>").attr("value",
* data[i].id).text( // data[i].id)); } } if (data.length > 0)
* $("#contractProcess").editableSelect()[0].value = data[0].name;
*/
}
function addTcpNodeUnits(data) {
if (data.length > 0) {
for (let i = 0; i < data.length; i++) {
const unitID = data[i].key;
const nodes = JSON.parse(data[i].value);
addNodeUnit({
type: 'TCP',
key: unitID,
value: nodes
});
}
}
}
function listSelectUnits(data) {
console.log(data);
global.units = {};
let htm = "";
if (data.length > 0) {
// data的key是创建人公钥_时间戳,value是nodes的ID
for (let i = 0; i < data.length; i++) {
const unitID = data[i].key;
const nodes = JSON.parse(data[i].value);
const at_ = data[i].key.indexOf("_");
console.log(nodes);
htm += "<option>集群:" + unitID.substring(at_ + 1)
+ "</option>";
global.units[unitID.substring(at_ + 1)] = nodes;
}
}
htm += "<option selected>选择节点集群</option>";
htm += "<option>无</option>";
console.log(htm);
$("#selectUnits").html(htm);
}
function onCancelAuth(obj) {
myToast("取消权限", obj.data);
if (obj.data === "success") {
}
}
function setPermission(data) {
// console.log(request.resetContractName);
global.wssocket.send(JSON.stringify({
resetContractProcess: data.name,
closePer: data.permission,
oldPer: data['oldPermission'],
isOpen: data.isOpen,
action: 'setPermission'
}));
}
function onSetPermission(obj) {
console.log(obj);
let html = "<div class='input-group mb-2'>";
html += "<div class='input-group-prepend'>";
html += "<span class='input-group-text' id='inputGroup-sizing-default'>";
html += "状态保存策略:" + "</span></div>";
html += "<div class='input-group-append'>";
html += "<select id='selectDumpPeriod2' class='custom-select' style='appearance: none; -webkit-appearance: none;'>";
if (period === "43200000") {
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
} else if (period === "86400000") {
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
} else if (period === "172800000") {
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
} else {
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
}
}
function onListLeakContractProcess(obj) {
drawCPTable(obj);
}

View File

@ -1,28 +1,31 @@
var expandOrCollapse = function () {
if ($("#outputNav").hasClass("col-2")) {
$("#outputNav").removeClass("col-2").addClass("col-6");
function expandOrCollapse() {
const outputNavEl = $("#outputNav")
if (outputNavEl.hasClass("col-2")) {
outputNavEl.removeClass("col-2").addClass("col-6");
$("#mainBox").removeClass("col-8").addClass("col-4");
$("#expand").html("收起");
} else {
$("#outputNav").removeClass("col-6").addClass("col-2");
outputNavEl.removeClass("col-6").addClass("col-2");
$("#mainBox").removeClass("col-4").addClass("col-8");
$("#expand").html("展开");
}
};
var listContracts = function () {
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
};
}
var startContract = function () {
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key);
var projectId = $("#selectedProject")[0].value;
var project = global.projects[projectId];
function listContracts() {
global.wssocket.send(JSON.stringify({
action: 'listContractProcess',
filters: 2
}));
}
function startContract() {
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
const projectId = $("#selectedProject")[0].value;
const project = global.projects[projectId];
startResult.innerText = "正在启动合约:" + project;
var request = {};
const request = {};
request.action = "startContract";
request.isPrivate = $("#privateprojecttab").hasClass("active");
@ -38,17 +41,16 @@ var startContract = function () {
request.script = "empty";
}
global.wssocket.send(JSON.stringify(request));
}
};
var startContractAsDebug = function () {
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key);
var projectId = $("#selectedProject")[0].value;
var project = global.projects[projectId];
function startContractAsDebug() {
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
const projectId = $("#selectedProject")[0].value;
const project = global.projects[projectId];
startResult.innerText = "正在以调试模式启动合约:" + project;
var request = {};
const request = {};
request.action = "startContractAsDebug";
request.isPrivate = $("#privateprojecttab").hasClass("active");
@ -64,32 +66,32 @@ var startContractAsDebug = function () {
request.script = "empty";
}
global.wssocket.send(JSON.stringify(request));
}
};
var stopContract = function () {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.name = mainVue.contracts[selectedContract.value].name;
request.id = mainVue.contracts[selectedContract.value].id;
global.wssocket.send(JSON.stringify(request));
};
function stopContract() {
global.wssocket.send(JSON.stringify({
action: 'killContractProcess',
requestID: new Date().getTime().toString(),
name: mainVue.contracts[selectedContract.value].name,
id: mainVue.contracts[selectedContract.value].id
}));
}
var genReadme = function () {
var request = {};
request.isPrivate = global.currentFile.isPrivate;
request.path = global.currentFile.path;
var tmpIndex = request.path.lastIndexOf('/');
var yjsName = request.path.substring(tmpIndex + 1, request.path.length - 4);
function genReadme() {
const request = {
isPrivate: global.currentFile.isPrivate,
path: global.currentFile.path
};
const tmpIndex = request.path.lastIndexOf('/');
const yjsName = request.path.substring(tmpIndex + 1, request.path.length - 4);
request.path = request.path.substring(0, tmpIndex);
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key);
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
for (c of mainVue.contracts) {
for (const c of mainVue.contracts) {
// 这里假设合约名同文件名
if (yjsName == c.name) {
var exportedFunction = c.exportedFunctions;
if (yjsName === c.name) {
const exportedFunction = c.exportedFunctions;
ReadmeFunction = [];
for (let f of exportedFunction) {
let description = "暂无描述";
@ -97,11 +99,11 @@ var genReadme = function () {
readmeFunc.functionName = f.functionName;
readmeFunc.description = description;
for (let anno of f.annotations) {
if (anno.type == 'Param') {
if (anno.type === 'Param') {
readmeFunc.args = anno.args[0];
} else if (anno.type == 'Description') {
} else if (anno.type === 'Description') {
readmeFunc.description = anno.args[0];
} else if (anno.type == 'Result') {
} else if (anno.type === 'Result') {
readmeFunc.result = anno.args[0];
}
}
@ -117,174 +119,168 @@ var genReadme = function () {
}
}
myToast("生成文档失败", "请启动合约并检查合约与文件名是否一致!");
};
}
var genData = function () {
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key);
var value = selectedContract.value;
if (value != undefined && value != "选择合约实例") {
var request = {};
function genData() {
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
const value = selectedContract.value;
if (value && value !== "选择合约实例") {
const request = {};
request.action = "generateDataFromRM";
request.requestID = new Date().getTime() + "_"
+ Math.floor(Math.random() * 10000);
var contract = mainVue.contracts[selectedContract.value];
request.requestID = `${new Date().getTime()}_${Math.floor(Math.random() * 10000)}`;
const contract = mainVue.contracts[selectedContract.value];
request.isPrivate = $("#privateprojecttab").hasClass("active");
request.contractID = contract.id;
request.contractName = mainVue.contracts[selectedContract.value].name;
var arg = {};
if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") {
arg.gasLimit = '1000';
} else {
arg.gasLimit = $('#gasLimit').val();
}
// console.log("[arg.gasLimit]"+arg.gasLimit);
request.pubkey = sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + arg.action
+ "|" + arg.arg + "|" + sm2Key.publicKey, sm2Key.privateKey);
request.arg = JSON.stringify(arg);
request.signature = sm2.doSignature(
`${request.contractID}|${arg.action}|${arg.arg}|${sm2Key.publicKey}`,
sm2Key.privateKey,
{hash: true, der: true});
const gasLimit = $('#gasLimit').val()
request.arg = JSON.stringify({
gasLimit: gasLimit ? gasLimit : '1000'
});
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
}
};
}
function queryContractInstanceDOI() {
global.wssocket.send(JSON.stringify({
action: "queryContractInstanceDOI",
requestID: new Date().getTime().toString(),
name: mainVue.contracts[selectedContract.value].name,
id: mainVue.contracts[selectedContract.value].id
}));
}
var queryContractInstanceDOI = function () {
var request = {};
request.action = "queryContractInstanceDOI";
request.requestID = new Date().getTime() + "";
request.name = mainVue.contracts[selectedContract.value].name;
request.id = mainVue.contracts[selectedContract.value].id;
global.wssocket.send(JSON.stringify(request));
};
function queryContractInstanceInfoByDOI() {
global.wssocket.send(JSON.stringify({
action: 'queryContractInstanceInfoByDOI',
requestID: new Date().getTime().toString(),
doi: contractInstanceDOIInput.value
}));
}
var queryContractInstanceInfoByDOI = function () {
var request = {};
request.action = "queryContractInstanceInfoByDOI";
request.requestID = new Date().getTime() + "";
request.doi = contractInstanceDOIInput.value;
global.wssocket.send(JSON.stringify(request));
};
function importContractInstanceCodeByDOI() {
global.wssocket.send(JSON.stringify({
action: "importContractInstanceCodeByDOI",
requestID: new Date().getTime().toString(),
doi: contractInstanceDOIInput.value
}));
}
var importContractInstanceCodeByDOI = function () {
var request = {};
request.action = "importContractInstanceCodeByDOI";
request.requestID = new Date().getTime() + "";
request.doi = contractInstanceDOIInput.value;
global.wssocket.send(JSON.stringify(request));
};
function openInClient() {
window.open(isBaaS ?
`${location.origin}/client/BaaSClient.html${location.search}` :
`${location.origin}/client/bdwareclient.html?self=true&` +
`contract=${mainVue.contracts[selectedContract.value].id}`);
}
var openinClient = function () {
let url
if (isBaaS) {
url = `${location.origin}/client/BaaSClient.html${location.search}`;
} else {
url = `${location.origin}/client/bdwareclient.html?self=true&contract=${mainVue.contracts[selectedContract.value].id}`
function stopAllContract() {
global.wssocket.send(JSON.stringify({
action: 'killAllContract'
}));
}
function selectContractToExecute() {
const value = selectedContractAtExecute.value;
if (value && value !== "选择实例" && mainVue.contracts[value]) {
mainVue.contractFunctions = mainVue.contracts[value].exportedFunctions;
global.wssocket.send(JSON.stringify({
action: "connectTo",
name: mainVue.contracts[value].name,
id: mainVue.contracts[value].id
}));
}
window.open(url);
};
}
var stopAllContract = function () {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var selectContractToExecute = function () {
var value = selectedContractAtExecute.value;
if (value && value !== "选择实例") {
var exportedFunction = mainVue.contracts[value].exportedFunctions;
mainVue.contractFunctions = exportedFunction;
var pingObj = {};
pingObj.action = "connectTo";
pingObj.name = mainVue.contracts[value].name;
pingObj.id = mainVue.contracts[value].id;
global.wssocket.send(JSON.stringify(pingObj));
}
};
var executeContract = function () {
if (selectedFunction.value == undefined) {
function executeContract() {
if (!selectedFunction.value) {
myToast("调用合约失败", "请选择合约方法");
return;
}
if (selectedContractAtExecute.value == undefined) {
if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约");
return;
}
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key);
var request = {};
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
const request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "_"
+ Math.floor(Math.random() * 10000);
var contract = mainVue.contracts[selectedContractAtExecute.value];
const contract = mainVue.contracts[selectedContractAtExecute.value];
request.contractID = contract.id;
request.operation = contract.exportedFunctions[selectedFunction.value].functionName;
arg = executeContractArgInput.value;
if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") {
request.gasLimit = '1000';
} else {
request.gasLimit = $('#gasLimit').val();
}
const arg = executeContractArgInput.value;
const gasLimit = $('#gasLimit').val()
request.gasLimit = gasLimit ? gasLimit : '1000'
request.pubkey = sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + request.operation
+ "|" + arg + "|" + sm2Key.publicKey, sm2Key.privateKey, {hash: true, der: true});
request.signature = sm2.doSignature(
`${request.contractID}|${request.operation}|${arg}|${sm2Key.publicKey}`,
sm2Key.privateKey,
{hash: true, der: true});
request.arg = arg;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var executeContractWithDynamicResult = function () {
if (selectedFunction.value == undefined) {
}
function executeContractWithDynamicResult() {
if (!selectedFunction.value) {
myToast("调用合约失败", "请选择合约方法");
return;
}
if (selectedContractAtExecute.value == undefined) {
if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约");
return;
}
console.log("executeContractWithDynamicResult");
var request = {};
const request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
var contract = mainVue.contracts[selectedContractAtExecute.value];
const contract = mainVue.contracts[selectedContractAtExecute.value];
request.contractName = contract.id;
var arg = {};
arg.action = contract.exportedFunctions[selectedFunction.value].functionName;
arg.arg = executeContractArgInput.value;
const arg = {
action: contract.exportedFunctions[selectedFunction.value].functionName,
arg: executeContractArgInput.value
};
request.withDyanmicAnalysis = true;
request.arg = "{\"action\":\"" + arg.action + "\",\"arg\":\"" + arg.arg
+ "\"}";
request.pubkey = global.sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + arg.action
+ "|" + arg.arg + "|" + global.sm2Key.publicKey,
global.sm2Key.privateKey, {hash: true, der: true});
request.signature = sm2.doSignature(
`${request.contractID}|${arg.action}|${arg.arg}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var testEvaluates = function () {
if (selectedFunction.value == undefined) {
}
function testEvaluates() {
if (!selectedFunction.value) {
myToast("调用合约失败", "请选择合约方法");
return;
}
if (selectedContractAtExecute.value == undefined) {
if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约");
return;
}
console.log("Evaluates");
var contract = mainVue.contracts[selectedContractAtExecute.value];
const contract = mainVue.contracts[selectedContractAtExecute.value];
var request = {};
request.action = "evaluates";
request.contractName = contract.id;
request.functionName = contract.exportedFunctions[selectedFunction.value].functionName;
request.args = executeContractArgInput.value;
global.wssocket.send(JSON.stringify(request));
};
global.wssocket.send(JSON.stringify({
action: "evaluates",
contractName: contract.id,
functionName: contract.exportedFunctions[selectedFunction.value].functionName,
args: executeContractArgInput.value
}));
}

View File

@ -12,6 +12,7 @@ var expandOrCollapse = function () {
var listContracts = function () {
var request = {};
request.action = "listContractProcess";
request.filters = 2;
global.wssocket.send(JSON.stringify(request));
};
@ -75,7 +76,7 @@ var importContractInstanceCodeByDOI = function () {
global.wssocket.send(JSON.stringify(request));
};
var openinClient = function () {
var openInClient = function () {
var path = document.location.pathname;
path = path.replace("/SCIDE", "");
path = path.replace("/OnlineIDE.html", "");

View File

@ -1,258 +1,258 @@
var WSHandler = function(event) {
// console.log("[scide.js] WSHandler " + event);
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case 'ping':
case 'poing':
break;
case 'onExecuteResult':
onExecuteResult(obj);
break;
case 'onListContractProcess':
onListContractProcess(obj);
break;
case 'onStartContract':
onStartContract(obj);
break;
case 'onKillContractProcess':
logComm(obj);
break;
case 'onKillAllContract':
onKillAllContract(obj);
break;
case 'onOutputStream':
displayOutput(obj);
break;
var WSHandler = function (event) {
// console.log("[scide.js] WSHandler " + event);
data = event.data;
// console.log(" -->" + data);
try {
var obj = JSON.parse(data);
switch (obj.action) {
case 'ping':
case 'poing':
break;
case 'onExecuteResult':
onExecuteResult(obj);
break;
case 'onListContractProcess':
onListContractProcess(obj);
break;
case 'onStartContract':
onStartContract(obj);
break;
case 'onKillContractProcess':
logComm(obj);
break;
case 'onKillAllContract':
onKillAllContract(obj);
break;
case 'onOutputStream':
displayOutput(obj);
break;
case 'onException':
logException(obj);
break;
case 'onHashResult':
onHashResult(obj);
break;
default:
// displayOutput(obj);
break;
}
} catch (err) {
console.log(err);
}
case 'onException':
logException(obj);
break;
case 'onHashResult':
onHashResult(obj);
break;
default:
// displayOutput(obj);
break;
}
} catch (err) {
console.log(err);
}
};// WSHandler()
var logException = function(obj) {
global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj);
var logException = function (obj) {
global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj);
};
var logComm = function(obj) {
console.log(obj);
var logComm = function (obj) {
console.log(obj);
};
var displayOutput = function(obj) {
displayOutputStr(obj.data);
var displayOutput = function (obj) {
displayOutputStr(obj.data);
};
var displayOutputStr = function(str) {
var val = global.outputStreamEditor.getValue();
val += "\n" + str;
global.outputStreamEditor.setValue(val);
var info = global.outputStreamEditor.getScrollInfo();
global.outputStreamEditor.scrollTo(0, info.height);
var displayOutputStr = function (str) {
var val = global.outputStreamEditor.getValue();
val += "\n" + str;
global.outputStreamEditor.setValue(val);
var info = global.outputStreamEditor.getScrollInfo();
global.outputStreamEditor.scrollTo(0, info.height);
};
var checkConnectStatus = function() {
if (global.wssocket.isOpen() != 1) {
if ($("#checkConnect").css("display") == "none") {
$("#checkConnect").fadeIn(800);
} else
$("#checkConnect").fadeOut(800);
} else {
$("#checkConnect").css("display", "block");
$("#checkConnect").css("background-color", "#007FFF");
}
var checkConnectStatus = function () {
if (global.wssocket.isOpen() != 1) {
if ($("#checkConnect").css("display") == "none") {
$("#checkConnect").fadeIn(800);
} else
$("#checkConnect").fadeOut(800);
} else {
$("#checkConnect").css("display", "block");
$("#checkConnect").css("background-color", "#007FFF");
}
};
var initWSocket = function() {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
url = prefix + document.location.host
+ (document.location.pathname.replace("scide.html", "SCExecutor"));
// console.log(url);
global.wssocket = createWssocket(url, function() {
listContractProcess();
listProjects();
}, function(data) {
WSHandler(data);
FileHandler(data);
});
global.filewssocket = global.wssocket;
setInterval(checkConnectStatus, 1000);
var initWSocket = function () {
var prefix = "ws://";
if (document.location.href.startsWith("https"))
prefix = "wss://";
url = prefix + document.location.host
+ (document.location.pathname.replace("scide.html", "SCExecutor"));
// console.log(url);
global.wssocket = createWssocket(url, function () {
listContractProcess();
listProjects();
}, function (data) {
WSHandler(data);
FileHandler(data);
});
global.filewssocket = global.wssocket;
setInterval(checkConnectStatus, 1000);
};
// ====== wsHandler
var onStartContract = function(obj) {
console.log("onStartContract:");
// console.log(obj);
var result = JSON.parse(obj.data);
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid;
var onStartContract = function (obj) {
console.log("onStartContract:");
// console.log(obj);
var result = JSON.parse(obj.data);
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid;
};
var onExecuteResult = function(obj) {
console.log("onExecuteResult:");
// console.log(obj);
var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result);
// console.log(data);
var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({
line : 0,
ch : 0
}, {
line : totalLines
});
if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis);
}
var onExecuteResult = function (obj) {
console.log("onExecuteResult:");
// console.log(obj);
var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result);
// console.log(data);
var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({
line: 0,
ch: 0
}, {
line: totalLines
});
if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis);
}
};
var onListContractProcess = function(obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
var html = "";
$("#tabdiv").editableSelect('clear');
// $("#tabdiv").html("");
global.contractName2ID = {};
for (var i = 0; i < data.length; i++) {
$("#tabdiv").editableSelect('add', data[i].name);
global.contractName2ID[data[i].name] = data[i].id;
// $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text(
// data[i].id));
}
if (data.length > 0)
$("#tabdiv").editableSelect()[0].value = data[0].name;
// $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text));
var onListContractProcess = function (obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
var html = "";
$("#tabdiv").editableSelect('clear');
// $("#tabdiv").html("");
global.contractName2ID = {};
for (var i = 0; i < data.length; i++) {
$("#tabdiv").editableSelect('add', data[i].name);
global.contractName2ID[data[i].name] = data[i].id;
// $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text(
// data[i].id));
}
if (data.length > 0)
$("#tabdiv").editableSelect()[0].value = data[0].name;
// $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text));
};
var onSaveƒe = function(obj) {
alert("Save file:" + obj.data);
var onSaveƒe = function (obj) {
alert("Save file:" + obj.data);
};
var onKillAllContract = function(obj) {
customAlert(obj.data);
var onKillAllContract = function (obj) {
customAlert(obj.data);
};
var onHashResult = function(obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
var onHashResult = function (obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
};
// ====== wsHandler done!
var switchContract = function(off) {
// var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id;
var pingObj = {};
pingObj.action = "connectTo";
var switchContract = function (off) {
// var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id;
var pingObj = {};
pingObj.action = "connectTo";
pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj));
pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj));
}
var countChar = function(str, c) {
var ret = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c)
ret++;
}
return ret;
var countChar = function (str, c) {
var ret = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c)
ret++;
}
return ret;
}
var generateOld = function() {
$.ajax({
url : "./SCManager?action=generatePrivateKey",
dataType : "json"
}).done(function(result) {
if (result.status) {
localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!");
initRest();
}
});
var generateOld = function () {
$.ajax({
url: "./SCManager?action=generatePrivateKey",
dataType: "json"
}).done(function (result) {
if (result.status) {
localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!");
initRest();
}
});
}
var generate = function() {
localStorage.setItem("PrivKey", JSON.stringify(sm2.generateKeyPairHex()));
global.privKey = localStorage.getItem("PrivKey");
var generate = function () {
localStorage.setItem("PrivKey", JSON.stringify(sm2.generateKeyPairHex()));
global.privKey = localStorage.getItem("PrivKey");
}
var initGlobal = function() {
window.global = {};
global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100 || !global.privKey.startsWith("{")) {
generate();
initRest();
} else
initRest();
global.privKey = JSON.parse(global.privKey);
var initGlobal = function () {
window.global = {};
global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100 || !global.privKey.startsWith("{")) {
generate();
initRest();
} else
initRest();
global.privKey = JSON.parse(global.privKey);
}
var initRest = function() {
global.scriptEditor = CodeMirror.fromTextArea($("#contractArea")[0], {
matchBrackets : true,
autoCloseBrackets : true,
lineNumbers : true,
height : "auto",
mode : "application/ld+json",
lineWrapping : true
});
global.responseEditor = CodeMirror.fromTextArea($("#responseArea")[0], {
matchBrackets : true,
autoCloseBrackets : true,
lineNumbers : true,
mode : "application/ld+json",
lineWrapping : true
});
global.outputStreamEditor = CodeMirror.fromTextArea(
$("#outputStreamArea")[0], {
matchBrackets : true,
autoCloseBrackets : true,
lineNumbers : true,
mode : "application/ld+json",
lineWrapping : true
});
global.argEditor = CodeMirror.fromTextArea($("#argArea")[0], {
matchBrackets : true,
autoCloseBrackets : true,
lineNumbers : true,
mode : "application/ld+json",
lineWrapping : true,
height : "auto"
});
var initRest = function () {
global.scriptEditor = CodeMirror.fromTextArea($("#contractArea")[0], {
matchBrackets: true,
autoCloseBrackets: true,
lineNumbers: true,
height: "auto",
mode: "application/ld+json",
lineWrapping: true
});
global.responseEditor = CodeMirror.fromTextArea($("#responseArea")[0], {
matchBrackets: true,
autoCloseBrackets: true,
lineNumbers: true,
mode: "application/ld+json",
lineWrapping: true
});
global.outputStreamEditor = CodeMirror.fromTextArea(
$("#outputStreamArea")[0], {
matchBrackets: true,
autoCloseBrackets: true,
lineNumbers: true,
mode: "application/ld+json",
lineWrapping: true
});
global.argEditor = CodeMirror.fromTextArea($("#argArea")[0], {
matchBrackets: true,
autoCloseBrackets: true,
lineNumbers: true,
mode: "application/ld+json",
lineWrapping: true,
height: "auto"
});
$('#tabdiv').editableSelect({
filter : false
});
$("#tabdiv").on('select.editable-select', function(e) {
// console.log("=====");
// console.log(e);
// console.log(e.target.value);
// TODO;
switchContract();
// switchContract
});
$('#tabdiv').editableSelect({
filter: false
});
$("#tabdiv").on('select.editable-select', function (e) {
// console.log("=====");
// console.log(e);
// console.log(e.target.value);
// TODO;
switchContract();
// switchContract
});
//
//
$('#tabdiv').addClass("ui-selectmenu-button");
$('#tabdiv').addClass("ui-selectmenu-button-closedn");
$('#tabdiv').addClass("ui-corner-all");
$('#tabdiv').addClass("ui-button");
$('#tabdiv').addClass("ui-widget");
$('#tabdiv').addClass("ui-selectmenu-button");
$('#tabdiv').addClass("ui-selectmenu-button-closedn");
$('#tabdiv').addClass("ui-corner-all");
$('#tabdiv').addClass("ui-button");
$('#tabdiv').addClass("ui-widget");
};
// var onUploadNext = function() {
@ -275,196 +275,198 @@ var initRest = function() {
// global.wssocket.send(JSON.stringify(request));
// };
var startContract = function() {
var request = {};
request.action = "startContract";
// TODO should be pubkey
request.owner = global.privKey.publicKey;
request.requestID = new Date().getTime() + "";
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/")) {
request.signature = sm2.doSignature("Fixed|" + request.path + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
request.script = "empty";
} else
request.signature = sm2.doSignature("Fixed|" + request.script + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
var startContract = function () {
var request = {};
request.action = "startContract";
// TODO should be pubkey
request.owner = global.privKey.publicKey;
request.requestID = new Date().getTime() + "";
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/")) {
request.signature = sm2.doSignature("Fixed|" + request.path + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
request.script = "empty";
} else
request.signature = sm2.doSignature("Fixed|" + request.script + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
// console.log("path=" + request.path);
// console.log("[scide.js] startContract() contractid = "
// + $("#tabdiv")[0].value);
global.wssocket.send(JSON.stringify(request));
// console.log("path=" + request.path);
// console.log("[scide.js] startContract() contractid = "
// + $("#tabdiv")[0].value);
global.wssocket.send(JSON.stringify(request));
};
var executeContractWithDynamicResult = function() {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
var executeContractWithDynamicResult = function () {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.privKey = global.privKey;
request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var executeContract = function() {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.pubkey = global.privKey.publicKey;
// contractID + "|" + action + "|" + arg + "|" + requester;
var localArg = JSON.parse(request.arg);
request.signature = sm2.doSignature(request.contractID + "|"
+ localArg.action + "|" + localArg.arg + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var listContractProcess = function() {
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
var executeContract = function () {
var request = {};
request.action = "executeContract";
request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue();
request.pubkey = global.privKey.publicKey;
// contractID + "|" + action + "|" + arg + "|" + requester;
var localArg = JSON.parse(request.arg);
request.signature = sm2.doSignature(request.contractID + "|"
+ localArg.action + "|" + localArg.arg + "|"
+ global.privKey.publicKey, global.privKey.privateKey);
localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request));
};
var killContractProcess = function() {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.name = $("#tabdiv")[0].value;
request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
};
var staticVerify = function() {
var request = {};
request.action = "staticVerifyContract";
// TODO should be pubkey
request.owner = global.privKey;
request.isPartial = false;
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
};
var downloadContract = function() {
if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html",
"/CMManager?action=downloadContract&projectName=");
url += projectName;
window.open(url);
};
var killAllContract = function() {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var customAlert = function(message, title) {
if (!title)
title = 'Alert';
if (!message)
message = 'No Message to Display.';
$('<div></div>').html(message).dialog({
title : title,
resizable : false,
modal : true,
buttons : {
'Ok' : function() {
$(this).dialog('close');
}
}
});
function listContractProcess() {
global.wssocket.send(JSON.stringify({
action: 'listContractProcess',
filters: 2
}));
}
var init = function() {
console.log("init:");
initGlobal();
initWSocket();
var req = localStorage.getItem("persisStatus");
// console.log(req);
req = JSON.parse(req);
if (req != undefined) {
// $("#tabdiv")[0].value = req.contractid;
//global.scriptEditor.setValue(req.script);
}
var req2 = localStorage.getItem("persisArg");
req2 = JSON.parse(req2);
if (req2 != undefined && req2.arg != undefined) {
global.argEditor.setValue(req2.arg);
}
initHello();
var killContractProcess = function () {
var request = {};
request.action = "killContractProcess";
request.requestID = new Date().getTime() + "";
request.name = $("#tabdiv")[0].value;
request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
};
var getRequestParameters = function() {
var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {};
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("=");
if (data.length == 2) {
params[data[0]] = data[1];
}
}
return params;
var staticVerify = function () {
var request = {};
request.action = "staticVerifyContract";
// TODO should be pubkey
request.owner = global.privKey;
request.isPartial = false;
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
};
var getTemplate1 = function(name, list, expiredDate) {
var tem = "contract _cname {\n \t//数据清洗逻辑\n function deleteKeys(result,list){\n\t\tfor (var key in list)\n \t\t\tdelete result[list[key]];\n \t\tfor (var key in result){\n \t\t\tif (typeof result[key] == 'object'){\n \t\t\t\tdeleteKeys(result[key],list);\t\n\t\t\t}\n\t\t}\n \t\treturn JSON.stringify(result);\n\t}\n\n \texport function filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn deleteKeys(result,list);\n\t}\n\t//数据处理逻辑\n\tfunction handle(obj){\n \n }\n\texport function get(arg){\n if (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n\t\tvar result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t\treturn handle(filter(result.response));\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
var downloadContract = function () {
if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html",
"/CMManager?action=downloadContract&projectName=");
url += projectName;
window.open(url);
};
var getTemplate2 = function(name, list, expiredDate) {
var tem = "contract _cname {\n //数据清洗逻辑\n \tfunction inVal(key,list){\n\t\tfor (var i=0;i<list.length;i++)\n \t\t\tif (list[i]==key) return true;\n \t\treturn false;\n\t}\n \tfunction reserveKeys(result,list){\n \t\tvar ret = {};\n\t\tvar hasVal = false;\n \t\tfor (var key in result){\n \t\t\tif (inVal(key,list)) {\n \t\t\t\tret[key] = result[key];\n \thasVal = true;\n\t\t\t}\n \tvar isObject =( typeof result[key] == 'object');\n if (isObject){\n\t\t\t\tvar val = reserveKeys(result[key],list);\n \t\tif (val!=undefined) {\n \t\t\tret[key] = val;\n \t\t\thasVal = true;\n \t\t}\n\t\t\t} \n\t\n\t\t}\n\t\tif (hasVal)\n \t\t\treturn ret;\n\t\telse\treturn undefined;\n\t}\n \tfunction filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn reserveKeys(result,list);\n\t}\n function handle(obj){\n return JSON.stringify(obj);\n }\n //数据处理逻辑\n\texport function get(arg){\n\t\tif (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n var result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t var ret = filter(result.response);\n handle(ret);\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
var killAllContract = function () {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var initHello = function() {
var param = getRequestParameters();
var type = parseInt(param["type"]);
var template;
switch (type) {
case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 3:
var contractID = param["contractID"];
$.ajax({
url : "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType : "json"
}).done(function(result) {
global.fileContentMap.set(contractID, result.data);
addTab({
"title" : contractID
});
});
return;
default:
return;
}
global.scriptEditor.setValue(template);
var customAlert = function (message, title) {
if (!title)
title = 'Alert';
if (!message)
message = 'No Message to Display.';
$('<div></div>').html(message).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function () {
$(this).dialog('close');
}
}
});
}
var init = function () {
console.log("init:");
initGlobal();
initWSocket();
var req = localStorage.getItem("persisStatus");
// console.log(req);
req = JSON.parse(req);
if (req != undefined) {
// $("#tabdiv")[0].value = req.contractid;
//global.scriptEditor.setValue(req.script);
}
var req2 = localStorage.getItem("persisArg");
req2 = JSON.parse(req2);
if (req2 != undefined && req2.arg != undefined) {
global.argEditor.setValue(req2.arg);
}
initHello();
};
var getRequestParameters = function () {
var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {};
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("=");
if (data.length == 2) {
params[data[0]] = data[1];
}
}
return params;
};
var getTemplate1 = function (name, list, expiredDate) {
var tem = "contract _cname {\n \t//数据清洗逻辑\n function deleteKeys(result,list){\n\t\tfor (var key in list)\n \t\t\tdelete result[list[key]];\n \t\tfor (var key in result){\n \t\t\tif (typeof result[key] == 'object'){\n \t\t\t\tdeleteKeys(result[key],list);\t\n\t\t\t}\n\t\t}\n \t\treturn JSON.stringify(result);\n\t}\n\n \texport function filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn deleteKeys(result,list);\n\t}\n\t//数据处理逻辑\n\tfunction handle(obj){\n \n }\n\texport function get(arg){\n if (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n\t\tvar result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t\treturn handle(filter(result.response));\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
};
var getTemplate2 = function (name, list, expiredDate) {
var tem = "contract _cname {\n //数据清洗逻辑\n \tfunction inVal(key,list){\n\t\tfor (var i=0;i<list.length;i++)\n \t\t\tif (list[i]==key) return true;\n \t\treturn false;\n\t}\n \tfunction reserveKeys(result,list){\n \t\tvar ret = {};\n\t\tvar hasVal = false;\n \t\tfor (var key in result){\n \t\t\tif (inVal(key,list)) {\n \t\t\t\tret[key] = result[key];\n \thasVal = true;\n\t\t\t}\n \tvar isObject =( typeof result[key] == 'object');\n if (isObject){\n\t\t\t\tvar val = reserveKeys(result[key],list);\n \t\tif (val!=undefined) {\n \t\t\tret[key] = val;\n \t\t\thasVal = true;\n \t\t}\n\t\t\t} \n\t\n\t\t}\n\t\tif (hasVal)\n \t\t\treturn ret;\n\t\telse\treturn undefined;\n\t}\n \tfunction filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn reserveKeys(result,list);\n\t}\n function handle(obj){\n return JSON.stringify(obj);\n }\n //数据处理逻辑\n\texport function get(arg){\n\t\tif (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n var result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t var ret = filter(result.response);\n handle(ret);\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
};
var initHello = function () {
var param = getRequestParameters();
var type = parseInt(param["type"]);
var template;
switch (type) {
case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 3:
var contractID = param["contractID"];
$.ajax({
url: "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType: "json"
}).done(function (result) {
global.fileContentMap.set(contractID, result.data);
addTab({
"title": contractID
});
});
return;
default:
return;
}
global.scriptEditor.setValue(template);
};