Показать сообщение отдельно
  #1 (permalink)  
Старый 19.11.2018, 03:32
Новичок на форуме
Отправить личное сообщение для bomj Посмотреть профиль Найти все сообщения от bomj
 
Регистрация: 19.11.2018
Сообщений: 7

Как пользователю внести свои данные в скрипт?
Подскажите пожалуйста, как сделать, чтобы любой пользователь мог самостоятельно ввести данные контракта?
Чтобы в строке 47 кода изменился адрес 0xae4243e2c0f910223323dd2f2fdd16820b69f1d6
на свой любой, допустим на адрес 0x41835eba2075d2452fbedeec25bedbbc61d9b8a1
И при нажатии на кнопку 'Get News' получить новую информацию.

<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://rinkeby.etherscan.io/assets/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="https://rinkeby.etherscan.io/jss/web3.min.js?v=0.20.6"></script>
</head>
<body>
<table><tr><td>
<center>
<button class="knopka" id='btn_5'><a id="my_link" href="https://rinkeby.etherscan.io/writecontract/index.html?a=0xae4243e2c0f910223323dd2f2fdd16820b69f1d6&n=rinkeby"><b><span style="color:black;">Send News</span></b></a></button>
<button type='button' id='btn_5' class="knopka" onclick="ethcall2('getPost', 'input_5','myanswer_5','string', '|string', 'btn_5');">Get News</button>
<div align="left"><b><span id='myanswer_5' style="color:teal"></span></b></div>
</center></body></td></tr></table>

<script>
    $('#overlay', window.parent.document).hide();
    jQuery(window).load(function () {
        $('#overlay').fadeOut("slow");
        
        var obj = window.parent.document.getElementById('readcontractiframe');
        parent.resizeIframe(obj, 0); 
    });
    function getcontractabi(contractaddress) {
        
            $.post("https://Rinkeby.etherscan.io/api",
        
                {
                    module: "contract",
                    action: "getabit",
                    address: contractaddress
                },
                function (data, status) {
                    console.log("contractAbi = " + data)
                });
    }

    var Web3 = require('web3');
    
    var web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io"));
    
    var version = web3.version.api;
    console.log(version); 
    var MyContract;
    var myContractInstance;
    try {
        MyContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"getPost","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newPost","type":"string"}],"name":"setPost","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]);
        myContractInstance = MyContract.at("0xae4243e2c0f910223323dd2f2fdd16820b69f1d6");
    }
    catch (err) {
        console.log(err.message);
    }    
    function ethcall2(strMethodName, strInputElementName, strOutputElementName, strOutputtype, strOutputFieldNames, strBtnName) {        
   
        var functionNametoCall = "myContractInstance." + strMethodName;
        var result;
        try {
            var strparas;
            var elms = document.querySelectorAll("[id=" + strInputElementName + "]");
            //console.log("elms.length = " + elms.length);            
            for (var i = 0; i < elms.length; i++) {
                if (i == 0) {
                    strparas = "'" + add0xforAddress(Escape(elms[i].value)) + "'"
                } else {
                    strparas = strparas + ",'" + Escape(elms[i].value) + "'"
                }
                if (elms[i].value == '') {
                    document.getElementById(strInputElementName).focus();                   
                    alert('Input value cannot be empty');
                    return false;
                }
            }
            showLoading(true, strBtnName);

            new Function(functionNametoCall + "(" + strparas + ", function(err, res){ if (err) {result = err;} else { result = res; } showMessage('" + strMethodName +"',result,'" + strOutputElementName+"','" + strOutputFieldNames +"','"+ strBtnName +"');   });")();

           // result = eval(functionNametoCall + "(" + strparas + ");");
           
           // $('#overlay').show();
        }
        catch (err) {
            //$('#overlay').show();
            result = "" + err + "";
            showLoading(false, strBtnName);
        }
        //setTimeout(function () {
        //    $('#overlay').show();
        //}, 2500);
       
        //document.getElementById(strOutputElementName).innerHTML = "<br><br> [&nbsp;<b>" + strMethodName + "</b> method Response ]<br>" + formatmultipleoutputs(result, strOutputFieldNames) + "<br>";
             
    }

    function showMessage(strMethodName, result, strOutputElementName, strOutputFieldNames, strBtnName) {
        
        document.getElementById(strOutputElementName).innerHTML = "<br><br> [&nbsp;<b>" + strMethodName + "</b> method Response ]<br>" + formatmultipleoutputs(result, strOutputFieldNames) + "<br>";
        showLoading(false, strBtnName);  
    }

    function showLoading(isShow, strBtnName) {
        
        if (isShow) {
            $(" <img id='waiting_" + strBtnName + "' class='waitingImg' src='https://etherscan.io/images/ajax-loader2.gif' style='margin-left:5px;' alt='Loading' />").insertAfter($('#' + strBtnName));
            $('#' + strBtnName).prop('disabled', true);
        } else {
            $('#' + strBtnName).prop('disabled', false);
            $('#waiting_' + strBtnName).remove(); 
        }
    }

    function Escape(val) {
        return val.replace(/'/g, "\\u0027");
    }

    function formatmultipleoutputs(strVal, strOutputFieldNames) {
        var strAnswer = '';
        //console.log("strVal = " + strVal);
        //console.log("strOutputFieldNames = " + strOutputFieldNames);
        //console.log("strVal.length = " + strVal.length);
        if (strOutputFieldNames.includes(';') == true) {
            var res_2 = strOutputFieldNames.split(';');
            for (i = 0; i < strVal.length; i++) {
                var tmparray = res_2[i].toString().split('|');
                strAnswer = strAnswer + "&nbsp;<font color='green'><i class='fa  fa-angle-double-right'></i></font> ";
                if (res_2[i] != null && res_2[i].toString() != '') {
                    strAnswer = strAnswer + " <b>" + tmparray[0] + "</b> &nbsp; <font color='silver'><i>" + tmparray[1] + "</i></font> <b>:</b> &nbsp;"
                }
                strAnswer = strAnswer + formatresult(strVal[i].toString(), tmparray[1]) + "<br>";
            }
        } else {
            strAnswer = strAnswer + "&nbsp;<font color='green'><i class='fa  fa-angle-double-right'></i></font> ";
            if (strOutputFieldNames != '') {
                var tmparray = strOutputFieldNames.toString().split('|');
                strAnswer = strAnswer + " <b>" + tmparray[0] + "</b> &nbsp; <font color='silver'><i>" + tmparray[1] + "</i></font> <b>:</b> &nbsp;";
                strVal = formatresult(strVal.toString(), tmparray[1])
            }
            strAnswer = strAnswer + replaceAll(strVal, ",", "<br>&nbsp;<font color='green'><i class='fa  fa-angle-double-right'></i></font> ") + "<br>";
        }
        return strAnswer;
    }

    function htmlEncode(value) {
        return $('<div/>').text(value).html();
    }
    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(find, 'g'), replace);
    }
    function formatresult(strResult, resulttype) {
        if (resulttype.startsWith('uint')) {
            return toFixed(strResult);
        } else if (resulttype == 'string') {
            return htmlEncode(strResult);
            //return hex_to_ascii(strResult);
        } else if (resulttype == 'address') {
            if (strResult != '0x0000000000000000000000000000000000000000') {
                return "<a href='/address/" + strResult + "' target='_blank'>" + strResult + "</a>";
            } else {
                return htmlEncode(strResult);
            }
            //} else if (resulttype == 'bool') {
            //    return Boolean(remove0x(strResult));
        } else {
            return htmlEncode(strResult);
        }
    }
    function hex_to_ascii(str1) {
        var hex = str1.toString();
        var str = '';
        for (var n = 0; n < hex.length; n += 2) {
            str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
        }
        return str;
    }
    function extractaddress(str1) {
        if (str1.length > 40) {
            str1.substr(str1.length - 40)
        }
        return str1;
    }
    function remove0x(str1) {
        if (str1.startsWith("0x") == true) {
            str1 = str1.substr(str1.length - str1.length + 2);
        }
        return str1;
    }
    function add0xforAddress(straddress) {
        straddress = straddress.trim();
        if (straddress.startsWith("0x") == false && straddress.length == 40) {
            straddress = "0x" + straddress;
        }
        return straddress;
    }
    function toFixed(x) {
        if (x.indexOf("e+") !== -1) {
            var value = web3.toBigNumber(x);
            x = value.toString(10);
        }
        return x;
    }     
    setTimeout(function () {
       
    }, 0);

</script>

</html>

Последний раз редактировалось bomj, 28.12.2018 в 19:14.
Ответить с цитированием