2

I'm trying to make a simple token transfer app using Web3.js and Angular all i want is to transfer some tokens from an address A to an address B. So, I made two functions in an angular service , the first one gets the balance of the actual account(it works) and the second one makes the transfer but it doesn't work and i don't know how to use it. I'm using Metamask on Chrome and Web3 0.20.3 (angular 6.0.3)

this is my code

 import { Injectable } from '@angular/core';

import Web3 from 'web3';

const web3 = new Web3(window.web3.currentProvider);

declare let require: any;
declare let window: any;

let tokenAbi = [
  //long ABI JSON not included to make the code shorter
]

@Injectable({

})
export class Web3ServiceService {
  private _account: string = null;
  private _web3: any;

  private _tokenContract: any;
  private _tokenContractAddress: string = "0x0b0A241E6331358D1777cBeF0240b8C462f3F7a2";

  constructor() {
    if (typeof window.web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      this._web3 = web3;// new Web3(window.web3.currentProvider);
      this._web3.version.getNetwork((err, netId) => {
        switch (netId) {
          case "1":
            console.log('This is mainnet');
            alert('Please connect to the Rinkeby network ');
            break
          case "2":
            console.log('This is the deprecated Morden test network.');
            alert('Please connect to the Rinkeby network ');
            break
          case "3":
            console.log('This is the ropsten test network.');
            break
          default:
            console.log('This is an unknown network.');
            alert('Please connect to the Rinkeby network ');
        }
      });
      if (this._web3.version.getNetwork !== '3') {
        console.log(this._web3.version.getNetwork);        
      } 
      } else {
      console.warn(
        'Please use a dapp browser like mist or MetaMask plugin for chrome'
      );
     }

    this._tokenContract = this._web3.eth.contract(tokenAbi).at(this._tokenContractAddress);
  }


  private async getAccount(): Promise<string> {
    if (this._account == null) {
      this._account = await new Promise((resolve, reject) => {
        this._web3.eth.getAccounts((err, accs) => {
          if (err != null) {
            alert('There was an error fetching your accounts.');
            return;
          }

          if (accs.length === 0) {
            alert(
              'Couldn\'t get any accounts! Make sure your Ethereum client is configured correctly.'
            );
            return;
          }
          resolve(accs[0]);
        })
      }) as string;

      this._web3.eth.defaultAccount = this._account;
    }

    return Promise.resolve(this._account);
  }

  public async getUserBalance(): Promise<number> {
    let account = await this.getAccount();

    return new Promise((resolve, reject) => {
      let _web3 = this._web3;
      this._tokenContract.balanceOf.call(account, function (err, result) {
        if(err != null) {
          reject(err);
        }
        resolve(result);
      });
    }) as Promise<number>;
  }  

  public async sendAFC(): Promise<any> {
    let account = await this.getAccount();

    return new Promise((resolve, reject) => {
      let _web3 = this._web3;
      let account2 = "0x169f0C8D07ECcD28DC9AA9998D61584CC9054C96";
      this._tokenContract.methods.transfer(account, 500).send({from: account, gas:10000},function (err, result) {
        if(err != null) {
          reject(err);
        }
        resolve(result);
      });
    }) as Promise<any>;
  } 
}

My app.component.ts file code

import { Component } from '@angular/core';
import {Web3ServiceService} from './service/web3-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public balance: number;
  public result:any;
  status: string;

  constructor(private cs: Web3ServiceService) {
    cs.getUserBalance().then(balance => this.balance = balance);

  }

  setStatus = message => {
    this.status = message;
  };

}

I don't know how to use the SendAFC() function in the component

Please if my code is too messed up ,i'll be thankful if you can just tell me how to do the transfer between two accounts using Web3 and angular

thank you in advance

  • What error are you receiving when you attempt to call sendAFC() ? – Zack McGinnis May 29 '18 at 21:05
  • I didn't even call it , i don't know how to do it i guess my code is messed up so i'm just lookin for a solution to transfer tokens between two accounts – Mounir Ilyass May 30 '18 at 1:45
  • I am using truffle and getting many abi's which one should I use? this is the code I am using for my token. github.com/bokkypoobah/… – shantanu chandra Sep 19 '18 at 17:24
1

What are you using account2 for? Looks like you are trying to transfer 500 tokens to the very same account calling the transaction (account).

  • the account opened in Metamask is admin account which holds a couple of tokens , the account2 is the another account that i created on metamask. getBalance works and it returns the number of tokens held by the Admin but i don't know how to transfer those tokens from admin to account2 , i need a method or a code ... thankks ! – Mounir Ilyass May 30 '18 at 1:48
  • When calling the method you are specifying from:account, and you are also sending the tokens to account. So basically you are sending the tokens from and to the same account, that’s why you might not be seeing any difference in token balance – pabloruiz55 May 30 '18 at 1:50
  • i fixed it , there is a button that executes a function sendToken() when i click on it this is the sendToken() code ----------------------------------------------------------------------------- sendToken(){ console.log("start") this.cs.sendAFC().then(result => this.result = result); console.log(this.result); } ----------------------------------------------------------------------------- but i got an error – Mounir Ilyass May 30 '18 at 3:03
  • I can't post the whole error in the comment but it starts with core.js:1598 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'transfer' of undefined TypeError: Cannot read property 'transfer' of undefined. at web3.service.ts:104 at new ZoneAwarePromise (zone.js:891) at Web3Service.<anonymous> (web3.service.ts:101) at step (app.module.ts:16) at Object.next (app.module.ts:16) at fulfilled (app.module.ts:16) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388) at Object.onInvoke (core.js:4062) – Mounir Ilyass May 30 '18 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.