web3的一些基本应用

现在越来越普及web3了,对前端或者程序员来说也能算是一扇新的门,大家有时间机会还是应该学学的
前端用web3需要安装下钱包一般是小狐狸,tp等,但是tp其他eth钱包都是基于小狐狸更改的,无疑在唤起时有个先后的区别,一般其他钱包的层级高于小狐狸,浏览器装好钱包后,会给windows注入eth对象(window.ethereum),所以判断是否安装钱包判断是否有该对象即可(window.ethereum && new Web3(window.ethereum)),下面介绍下web3的基本流程和基本的一些方法

  const web3 = window.ethereum && new Web3(window.ethereum)
 
  1.登录的时候一般会先去调用钱包的签名,拿到签名的信息再去调登录接口
   const sign = ()=>{
	  web3.eth.personal.sign(web3.utils.utf8ToHex(nonce), address).then((res)=>{'签名'})
	}
 2.监听切换钱包地址
 const changeAccount = async () => {
  try {
    let res = await window.ethereum.on(
      'accountsChanged',
      function (re: string) {
        if (re[0]) {
          '监听到的钱包地址'
        } else {
          return false;
        }
      },
    );
  } catch (err) {
    console.log(err);
  }
};
3.添加你想添加得网络
addChain = () => {
  window.ethereum
    .request({
      method: 'wallet_addEthereumChain',
      params: [
        {
          chainId: web3.utils.numberToHex(1320),//转换成eth能识别的16进制
          chainName: '网络名',
          nativeCurrency: {
            name: '网络名',
            symbol: '网络消耗的币种', // 2-6 characters long
            decimals: 18,
          },
          rpcUrls: ['网络的rpc'],
          blockExplorerUrls: ['网络的浏览器'],
        },
      ],
    })
    .then((res: any) => {
      console.log(res);
    })
    .catch((res: any) => {
      console.log(res);
    });
};
4.监听网络切换

const netChange =  async () => {
  window?.ethereum.on('chainChanged', (chainId: number) => {
    '监听后得操作'
  });
};

5.获取钱包地址
 try {
    const maskInfo = await window.ethereum.request({
      method: 'eth_requestAccounts',
    });
    return maskInfo[0];
  } catch (e) {
    // message.error('连接钱包失败!');
    return;
  }
 6.返回当前网络id
 try {
    return await web3.eth.net.getId();
  } catch (error) {
    // message.error('获取网络错误!');
    return;
  } 
  7.调用合约方法,首先得生成合约对象
  const 'xxx合约对象' = new web3.eth.Contract('xxx合约abi', 'xxx合约token')
  所有的合约方法都在合约的abi上,除了一些公共的abi得另外写,比如nft的
  合约的方法就两个访问 方式:call 和send,
  send类似post请求需要传参数,它是需要消耗gas的,call类似get请求,不需要传参也不需要消耗
   01.比如查询某个合约用户的奖励:
  try {
    return 'xxx合约对象'.methods.'奖励的方法'(address).call();
  } catch (e) {
    console.log(e, 'inviteReward');
  }
	02.比如用户提取奖励
	const claim = async (
	  {参数}
	) => {
	  try {
	    let res = await 'xx合约对象'.methods.claim(参数).send({
	      from: '你的钱包地址',
	      gas: '500000', //gas和gasprice 一般不用写,钱包自己会生成
          gasPrice: await web3.eth.getGasPrice(),
	    });
	    return res;
	  } catch (err: any) {
	    return false;
	  }
	};
	03.nft一般需要花销网络的代币需要对该钱包进行授权,表示这个币对你钱包地址授权了,可以使用该代币去买卖    nft了
	授权方法
	 try {
    let res = await '代币的合约'.methods
      .approve(
        'nft合约token',
        '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
      )
      .send({
        from: '钱包地址',
        gas: '500000',
        gasPrice: await web3.eth.getGasPrice(),
      });
    console.log(res);
  } catch (err: any) {
    console.log(err);
  }
  
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值