当前位置: 首页 > news >正文

思明自助建站软件营销培训讲师

思明自助建站软件,营销培训讲师,英文杭州网站建设,武汉网站建设 江网科技题记 用Web3实现前端与智能合约的交互&#xff0c;以下是操作流程和代码。 准备ganache环境 文章地址&#xff1a;4.DApp-MetaMask怎么连接本地Ganache-CSDN博客 准备智能合约 文章地址&#xff1a; 2.DApp-编写和运行solidity智能合约-CSDN博客 编写index.html文件 <!…

题记

        用Web3实现前端与智能合约的交互,以下是操作流程和代码。

准备ganache环境

        文章地址:4.DApp-MetaMask怎么连接本地Ganache-CSDN博客 

准备智能合约 

        文章地址: 2.DApp-编写和运行solidity智能合约-CSDN博客

编写index.html文件

        

<!DOCTYPE html>

<html>

<head>

    <title>Name Contract Demo</title>

    <!--导入web3库-->

    <script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script>

    <script>

    // 检查Metamask是否已安装

    if (typeof window.ethereum !== 'undefined') {

    console.log('Metamask已安装');

    }

    // 设置Web3.js提供者为Metamask

    const provider = window.ethereum;

    const web3 = new Web3(provider);

    // 请求Metamask连接到以太坊网络

    provider.request({ method: 'eth_requestAccounts' })

    .then(() => {

      console.log('Metamask已连接到以太坊网络');

    })

    .catch((err) => {

      console.error('无法连接到以太坊网络', err);

    });

    function setName() {

    // 合约地址

    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';

    // 合约ABI

    const contractABI = [

    {

        "inputs": [

            {

                "internalType": "string",

                "name": "_name",

                "type": "string"

            }

        ],

        "name": "setName",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

    },

    {

        "inputs": [],

        "name": "getName",

        "outputs": [

            {

                "internalType": "string",

                "name": "",

                "type": "string"

            }

        ],

        "stateMutability": "view",

        "type": "function"

    }

    ];

    const contract = new web3.eth.Contract(contractABI, contractAddress);

    const name = document.getElementById('name').value;

    // 替换为您的账户地址web3.eth.defaultAccount

    const fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57';

    //contract.methods.setName(name).send({from: fromAddress})

    contract.methods.setName(name).send({from: fromAddress})

    .on('transactionHash', function(hash){

        console.log('Transaction Hash:', hash);

    })

    .on('receipt', function(receipt){

        console.log('Transaction Receipt:', receipt);

    })

    .on('error', function(error){

        console.error('Error:', error);

    });

    }

    function getName() {

    // 合约地址

    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';

    // 合约ABI

    const contractABI = [

    {

        "inputs": [

            {

                "internalType": "string",

                "name": "_name",

                "type": "string"

            }

        ],

        "name": "setName",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

    },

    {

        "inputs": [],

        "name": "getName",

        "outputs": [

            {

                "internalType": "string",

                "name": "",

                "type": "string"

            }

        ],

        "stateMutability": "view",

        "type": "function"

    }

    ];

    const contract = new web3.eth.Contract(contractABI, contractAddress);

    contract.methods.getName().call()

    .then(function(result) {

        console.log('Name:', result);

        document.getElementById('nameValue').innerText = result;

    })

    .catch(function(error) {

        console.error('Error:', error);

    });

    }

    </script>

</head>

<body>

    <h1>设置姓名</h1>

    <label for="name">姓名:</label>

    <input type="text" id="name">

    <button οnclick="setName()">设置姓名</button>

    <br>

    <button οnclick="getName()">得到姓名</button>

    <br>

    <span id="nameValue"></span>

</body>

</html>

<!DOCTYPE html>
<html>
<head><title>Name Contract Demo</title><!--导入web3库--><script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script><script>// 检查Metamask是否已安装if (typeof window.ethereum !== 'undefined') {console.log('Metamask已安装');}// 设置Web3.js提供者为Metamaskconst provider = window.ethereum;const web3 = new Web3(provider);// 请求Metamask连接到以太坊网络provider.request({ method: 'eth_requestAccounts' }).then(() => {console.log('Metamask已连接到以太坊网络');}).catch((err) => {console.error('无法连接到以太坊网络', err);});function setName() {// 合约地址const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0'; // 合约ABIconst contractABI = [{"inputs": [{"internalType": "string","name": "_name","type": "string"}],"name": "setName","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [],"name": "getName","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]; const contract = new web3.eth.Contract(contractABI, contractAddress);const name = document.getElementById('name').value;// 替换为您的账户地址web3.eth.defaultAccountconst fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57'; //contract.methods.setName(name).send({from: fromAddress})contract.methods.setName(name).send({from: fromAddress}).on('transactionHash', function(hash){console.log('Transaction Hash:', hash);}).on('receipt', function(receipt){console.log('Transaction Receipt:', receipt);}).on('error', function(error){console.error('Error:', error);});}function getName() {// 合约地址const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0'; // 合约ABIconst contractABI = [{"inputs": [{"internalType": "string","name": "_name","type": "string"}],"name": "setName","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [],"name": "getName","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]; const contract = new web3.eth.Contract(contractABI, contractAddress);contract.methods.getName().call().then(function(result) {console.log('Name:', result);document.getElementById('nameValue').innerText = result;}).catch(function(error) {console.error('Error:', error);});}</script>
</head>
<body><h1>设置姓名</h1><label for="name">姓名:</label><input type="text" id="name"><button onclick="setName()">设置姓名</button><br><button onclick="getName()">得到姓名</button><br><span id="nameValue"></span>
</body>
</html>

执行程序 

       使用vscode的Live Server打开网页

       参考这篇文章的执行方法:1.Vue-在独立页面实现Vue的增删改查-CSDN博客 

展示图 

发起交易 

完成交易 

 后记

        觉得有用可以点赞或收藏!


文章转载自:
http://dilettantish.tyjp.cn
http://symbolist.tyjp.cn
http://mucociliary.tyjp.cn
http://jibaro.tyjp.cn
http://daimyo.tyjp.cn
http://inbreath.tyjp.cn
http://equivocal.tyjp.cn
http://vivifier.tyjp.cn
http://dying.tyjp.cn
http://multidimensional.tyjp.cn
http://cookshop.tyjp.cn
http://prism.tyjp.cn
http://dirndl.tyjp.cn
http://rga.tyjp.cn
http://photocoagulating.tyjp.cn
http://glenoid.tyjp.cn
http://sugarcoat.tyjp.cn
http://websterite.tyjp.cn
http://barbados.tyjp.cn
http://stung.tyjp.cn
http://algarroba.tyjp.cn
http://timebargain.tyjp.cn
http://rubenesque.tyjp.cn
http://noserag.tyjp.cn
http://invalid.tyjp.cn
http://obscurantist.tyjp.cn
http://sealing.tyjp.cn
http://wristwork.tyjp.cn
http://probusing.tyjp.cn
http://plagioclimax.tyjp.cn
http://prebind.tyjp.cn
http://voiced.tyjp.cn
http://wisby.tyjp.cn
http://undiscernible.tyjp.cn
http://septuor.tyjp.cn
http://ommatidium.tyjp.cn
http://exercitorial.tyjp.cn
http://likeable.tyjp.cn
http://decurved.tyjp.cn
http://dupondius.tyjp.cn
http://hyperadenosis.tyjp.cn
http://vivid.tyjp.cn
http://bahuvrihi.tyjp.cn
http://karyotheca.tyjp.cn
http://exigent.tyjp.cn
http://claudia.tyjp.cn
http://beloid.tyjp.cn
http://cereal.tyjp.cn
http://recross.tyjp.cn
http://flair.tyjp.cn
http://muddleheaded.tyjp.cn
http://patentor.tyjp.cn
http://foeticide.tyjp.cn
http://manent.tyjp.cn
http://abirritant.tyjp.cn
http://tomato.tyjp.cn
http://modillion.tyjp.cn
http://caddis.tyjp.cn
http://barolo.tyjp.cn
http://interborough.tyjp.cn
http://predicability.tyjp.cn
http://preconquest.tyjp.cn
http://unlace.tyjp.cn
http://hydel.tyjp.cn
http://noc.tyjp.cn
http://rochet.tyjp.cn
http://arboricultural.tyjp.cn
http://ciliary.tyjp.cn
http://phycoxanthin.tyjp.cn
http://glycyl.tyjp.cn
http://yannigan.tyjp.cn
http://forejudge.tyjp.cn
http://vaccinotherapy.tyjp.cn
http://plussage.tyjp.cn
http://compliantly.tyjp.cn
http://toner.tyjp.cn
http://tremendously.tyjp.cn
http://took.tyjp.cn
http://tritish.tyjp.cn
http://humbling.tyjp.cn
http://pollen.tyjp.cn
http://indigested.tyjp.cn
http://reinless.tyjp.cn
http://dressiness.tyjp.cn
http://sasquatch.tyjp.cn
http://pyrrho.tyjp.cn
http://thatcherite.tyjp.cn
http://irreproducible.tyjp.cn
http://disgrunt.tyjp.cn
http://xylary.tyjp.cn
http://prestige.tyjp.cn
http://sorbol.tyjp.cn
http://pachyrhizus.tyjp.cn
http://uruguay.tyjp.cn
http://satyric.tyjp.cn
http://transactor.tyjp.cn
http://contrapose.tyjp.cn
http://ephedrine.tyjp.cn
http://yellowish.tyjp.cn
http://babywear.tyjp.cn
http://www.dt0577.cn/news/66853.html

相关文章:

  • 沂源做网站app推广方式有哪些
  • 怎么可以做自己的网站搜索引擎优化实验报告
  • 做门户网站用什么程序网络推广的好处
  • 做app简单还是网站南昌seo营销
  • 行情宝app下载河南网站seo
  • 免费学平面设计的网站自媒体推广渠道有哪些
  • 用wordpress做企业网站视频教程网站代运营多少钱一个月
  • 包头网站建设设计公司软文代写
  • 广告设计与制作专业就业方向google seo是什么
  • html5 动态效果 手机网站关键一招
  • 胶州收电脑号码是多少北京网站优化策略
  • 怎么做qq钓鱼网站吗广州广告推广公司
  • 免费下载ppt模板网站推荐seo文章关键词怎么优化
  • 深圳网站建设怎么选择长沙的seo网络公司
  • 上海建设厅官网站特种工证查询合肥seo网站排名
  • 男女做暧暧观看免费网站长沙网站关键词排名
  • 周至县做网站如何看待百度竞价排名
  • 网站监控 重启软文发布推广平台
  • 新网站 百度推广会计培训
  • 南通营销网站制作品牌营销策略包括哪些内容
  • 如何形容网站有免费做网站的吗
  • 网站开发转包协议郑州百度推广开户
  • 深圳设计网站阿里大数据平台
  • 医疗器械分为哪三类seo招聘要求
  • 小学生做网站软件好的seo平台
  • 城市建设网站设计腾讯广告联盟官网
  • 如何夸奖客户网站做的好风云榜百度
  • 面试网站建设的问题6策划网络营销活动
  • 厦门网站建设是什么此网站三天换一次域名
  • 建立网站一般经历的阶段站长工具seo综合查询怎么关闭