智能合约开发遇到的坑

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

使用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);
    };
    
});

猜你喜欢

转载自blog.csdn.net/xgocn/article/details/121570180