当前位置:首页 » 《随便一记》 » 正文

智能合约开发遇到的坑_xgocn的专栏

26 人参与  2022年04月14日 14:16  分类 : 《随便一记》  评论

点击全文阅读


网上搜索的资料写的很详细啊,可试验啊试验,始终不成功,

使用Web3.js查询以太币和代币余额以及转账

https://www.jianshu.com/p/496c9d833df9
不用自己同步以太坊节点,直接发起签名交易
https://segmentfault.com/a/1190000014729677
以太坊ERC20 Token标准完整说明
https://blog.csdn.net/diandianxiyu_geek/article/details/78082551?utm_source=gold_browser_extension
最后发现,问题所在是因为网上的资料大部分都是针对私链的,而公链的转账是不一样的。。。啊。。。花费了两天的时间才试验出来
      var myContract = new web3.eth.Contract(apiInterface, contractAddress);
      // console.log(myContract.methods)
     //合约查询账户余额
     myContract.methods.balanceOf(currentAccount).call().then(data => { 
       console.log('from balance:' + data)
     })
//合约转账
  var txData = {
           to: contractAddress,
           value: web3.utils.toWei('0','ether'),//合约转账时,此值需设为0
           gas: this.chainGas,
           gasPrice: this.gasPrice,
           nonce: nonce,
           chainId: this.chainID,
           data: myContract.methods.transfer(toAddress, 10000).encodeABI(),
         }
        web3.eth.accounts.signTransaction(txData, this.curAccount.decryptKey.privateKey)
         .then((data)=>{
          web3.eth.sendSignedTransaction(data.rawTransaction)
            .on('transactionHash', (data)=>{
              console.log('ok')
            })
            .catch((data)=>{
              console.log(data)
            })     
           })
最后附上大神的私链代码供参考:
router.post('/transfer/token/sign.json', function (req, res) {
    const from    = req.body.from;
    const to      = req.body.to;
    
    const symbol  = req.body.symbol;
    const key     = req.body.key;
    var message = {};
    try{
       const abi = fs.readFileSync( __dirname + '/abi/'+symbol+'.abi', 'utf-8');
       const contractAddress = contracts[symbol];
       const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { "from": from});
      contract.methods.balanceOf(from).call().then(function(balance){
          contract.methods.decimals().call().then(function(decimals){
              const amount = new BigNumber(req.body.amount).toFixed(Number(decimals)).toString().replace(".","");
              if(Number(amount) > Number(balance)){
                 message = {"status": false, "code":1, "data":{"error":"balance = " + balance}};
                 logger.error(message);
                 res.json(message);
                 return;
              }
          
             web3.eth.getGasPrice().then(function(gasPrice){
                 var price = Number(gasPrice);
                web3.eth.getTransactionCount(from).then(function(nonce){
                    contract.methods.transfer(from, amount).estimateGas().then(function(gas){
                        var rawTransaction = {
                           "nonce": web3.utils.toHex(nonce),
                           "from": from,
                           "to": contractAddress,
                           "gas": web3.utils.toHex(gas),
                           "gasPrice": web3.utils.toHex(price),
                           // "gasLimit": this.web3.utils.toHex(gasLimit.gasLimit),
                           "value": "0x0",
                           "data": contract.methods.transfer(to, amount).encodeABI()
                        };
                        // console.log(`balance: ${balance}`);
                        // console.log(price);
                        // console.log(gas);
                        // console.log(amount);
                        // console.log(rawTransaction);
                       logger.debug(`/transfer/token/sign.json - gas: ${gas}, price: ${price}, cost: ${gas * price}, balance: ${balance}, amount: ${amount}, value: ${value}`);
                        // console.log(rawTransaction);
                        
                        var privateKey = new Buffer.from(key, 'hex');
                        var tx = new Tx(rawTransaction);
                        tx.sign(privateKey);
                        var serializedTx = tx.serialize();
          
                       web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', function(txhash){
                           message = {"status":true, "code":0, "data":{"txhash":txhash}};
                           logger.info(message);
                           res.json(message); 
                        }); 
                     });
                 });
              });
           });
       });
    }catch(error){
       message = {"status": false, "code":1, "data":{"error":error.message}};
       logger.error(message);
       res.json(message);
    };
    
});

点击全文阅读


本文链接:http://m.zhangshiyu.com/post/38033.html

以太  转账  合约  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最新文章

  • 「爱让我溺毙而亡」小说节选推荐_[羽柔乔羽柔林絮]章节限时抢先看‌
  • 此去经年人未还霍沉洲沈青禾后续结局霍沉洲
  • 山海不相逢内容精选(温逸尘沈衿)_山海不相逢内容精选(温逸尘沈衿)
  • (番外)+(全书)霍沉洲沈青禾此去经年人未还(霍沉洲沈青禾)_(霍沉洲沈青禾此去经年人未还)列表_笔趣阁(霍沉洲沈青禾)
  • (番外)+(全书)霍沉洲沈青禾(此去经年人未还霍沉洲沈青禾)完结_(霍沉洲沈青禾)列表_笔趣阁(此去经年人未还霍沉洲沈青禾)
  • 「重回八零,拒绝替嫁冲喜」章节彩蛋限时释出‌_卫东玉兰苏夏人气小说未删减节选
  • 重生七零祁同伟不再是农民儿子结局+番外纯净版全书免费重生七零祁同伟不再是农民儿子结局+番外纯净版全书免费
  • 傅雅宁的神女老婆,却在背地承欢作乐顾尘傅雅宁全书在线
  • 全文神女老婆,却在背地承欢作乐全局(顾尘傅雅宁)列表_全文神女老婆,却在背地承欢作乐全局
  • (番外)+(全书)此去经年人未还全书+番外+后续免费下载_(沈青禾霍沉洲)此去经年人未还全书+番外+后续列表_笔趣阁(沈青禾霍沉洲)
  • 完结文毁容的姐姐和瞎眼的我离开后,姜家两兄弟悔哭了+后续列表_完结文毁容的姐姐和瞎眼的我离开后,姜家两兄弟悔哭了+后续(林梦婉)
  • 妻子辱我爸受贿自杀,我掏出一等军功章节选推荐_[陈素云辰朋友]小说精彩章节分享

    关于我们 | 我要投稿 | 免责申明

    Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1