Skip to content

Instantly share code, notes, and snippets.

@fmsouza
Created November 7, 2017 12:34
Show Gist options
  • Save fmsouza/0c54f8680e5002524b80a723af2a4a45 to your computer and use it in GitHub Desktop.
Save fmsouza/0c54f8680e5002524b80a723af2a4a45 to your computer and use it in GitHub Desktop.
Transferring tokens in a contract using ethers.js
const ethers = require('ethers');
const { Contract, Wallet, providers } = ethers;
const CONTRACT_ADDRESS = '<contract-address-hash>';
const CONTRACT_ABI = '<contract-abi-json>';
const PRIVATE_KEY = '<private-key-hash>';
const DESTINATION_WALLET = '<destination-address-hash>';
const AMOUNT = '<tokens-amount>';
const PROVIDER = providers.getDefaultProvider();
const wallet = new Wallet(PRIVATE_KEY);
class CustomSigner {
constructor(wallet) {
this.wallet = wallet;
this.provider = PROVIDER;
}
getAddress() {
return Promise.resolve(this.wallet.getAddress());
}
sign(transaction) {
return Promise.resolve(this.wallet.sign(transaction));
}
}
const contract = new Contract(CONTRACT_ADDRESS, CONTRACT_ABI, new CustomSigner(wallet));
const walletAddress = wallet.getAddress();
console.log("Current wallet:", walletAddress);
contract.functions.balanceOf(walletAddress)
.then(({ balance }) => console.log("Balance:", balance.toString()));
const gasLimit = 40000;
const gasPrice = 0xBEBC200; // 1 gwei
const options = { gasLimit, gasPrice };
const provider = PROVIDER;
provider.on(walletAddress, blockNumer => console.log("Balance changed in block", blockNumer));
contract.functions.transfer(DESTINATION_WALLET, AMOUNT, options)
.then(txn => {
console.log("Waiting for confirmation on transaction", txn);
provider.waitForTransaction(txn).then(transaction => {
console.log("Transaction mined:", transaction);
});
provider.on(txn, txon => console.log("Mined transaction:", txon));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment