Search code examples
solidityweb3jstruffle

How it manage private keys with truffle?


I'm trying send tokens in mi custom contract which is deployed in ropsten. Also, I'm working with truffle and truffle-contract 1.1.11 library. My doubt is, how should I sign transactions inside the environment of truffle?

On other hand, if it possible, I would like know how is truffle managing the private keys, because when I set up the project on local ganache blockchain all my stuff works. When I try to sign a transaction from another address different from the contract deploy address, it just magically guest private keys. This of course is in ganache but the problem is in ropsten.

pragma solidity ^0.5.0;

import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";

contract CustomToken is ERC20Pausable, ERC20Burnable, ERC20Mintable, ERC20Detailed {

    constructor () public ERC20Detailed("CustomToken", "CT", 2) { }

    // some functions who call super.function(), this reproduces default behavior of a base ERC20 token

}
const contract = require('truffle-contract');

const customtoken_artifact = require('../build/contracts/CustomToken.json');
let CustomToken = contract(customtoken_artifact);

module.exports = {

    sendCoin: function(amount, sender, receiver, callback) {
        let self = this;

        CustomToken.setProvider(self.web3.currentProvider);

        let custom;

        CustomToken.deployed().then(function(instance) {

            custom = instance;

            return custom.transfer(receiver, amount, {from: sender});

        }).then(() => callback("202"))
            .catch(function(e) {
                console.log(e);
                callback("400 " + e);
            });
    },
};

Finally, I expect know how is truffle managing the private keys or when I should sign the transaction.


Solution

  • To sign transactions in Truffle you can use HDWalletProvider:

    https://www.npmjs.com/package/@truffle/hdwallet-provider

    You can configure it in your truffle-config.js