Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cli str features #288

Merged
merged 12 commits into from
Sep 27, 2018
130 changes: 82 additions & 48 deletions CLI/commands/ST20Generator.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var readlineSync = require('readline-sync');
var BigNumber = require('bignumber.js');
var moment = require('moment');
var chalk = require('chalk');
const shell = require('shelljs');
var contracts = require('./helpers/contract_addresses');
Expand All @@ -18,7 +19,8 @@ let tokenSymbol;
let selectedSTO;

const STO_KEY = 3;
const regFee = 250;
const REG_FEE_KEY = 'tickerRegFee';
const LAUNCH_FEE_KEY = 'stLaunchFee';
const cappedSTOFee = 20000;
const usdTieredSTOFee = 100000;
const tokenDetails = "";
Expand Down Expand Up @@ -106,73 +108,60 @@ async function setup(){
}

async function step_ticker_reg(){
console.log("\n");
console.log('\x1b[34m%s\x1b[0m',"Token Creation - Symbol Registration");
console.log('\n\x1b[34m%s\x1b[0m',"Token Creation - Symbol Registration");

let alreadyRegistered = false;
let available = false;
let regFee = web3.utils.fromWei(await securityTokenRegistry.methods.getUintValues(web3.utils.soliditySha3(REG_FEE_KEY)).call());

while (!available) {
console.log(chalk.green(`\nRegistering the new token symbol requires 250 POLY & deducted from '${Issuer.address}', Current balance is ${(await currentBalance(Issuer.address))} POLY\n`));
console.log(chalk.green(`\nRegistering the new token symbol requires ${regFee} POLY & deducted from '${Issuer.address}', Current balance is ${(await currentBalance(Issuer.address))} POLY\n`));

if (typeof _tokenConfig !== 'undefined' && _tokenConfig.hasOwnProperty('symbol')) {
tokenSymbol = _tokenConfig.symbol;
} else {
tokenSymbol = readlineSync.question('Enter the symbol for your new token: ');
tokenSymbol = await selectTicker(true);
}

await securityTokenRegistry.methods.getTickerDetails(tokenSymbol).call({}, function(error, result){
if (new BigNumber(result[1]).toNumber() == 0) {
available = true;
} else if (result[0] == Issuer.address) {
console.log('\x1b[32m%s\x1b[0m',"Token Symbol has already been registered by you, skipping registration");
available = true;
alreadyRegistered = true;
} else {
console.log('\x1b[31m%s\x1b[0m',"Token Symbol has already been registered, please choose another symbol");
}
});
}

if (!alreadyRegistered) {
await step_approval(securityTokenRegistryAddress, regFee);
let registerTickerAction = securityTokenRegistry.methods.registerTicker(Issuer.address, tokenSymbol, "");
await common.sendTransaction(Issuer, registerTickerAction, defaultGasPrice);
}
}

async function step_approval(spender, fee) {
polyBalance = await polyToken.methods.balanceOf(Issuer.address).call();
let requiredAmount = web3.utils.toWei(fee.toString());
if (parseInt(polyBalance) >= parseInt(requiredAmount)) {
let allowance = await polyToken.methods.allowance(spender, Issuer.address).call();
if (allowance == web3.utils.toWei(fee.toString())) {
return true;
let details = await securityTokenRegistry.methods.getTickerDetails(tokenSymbol).call();
if (new BigNumber(details[1]).toNumber() == 0) {
available = true;
await approvePoly(securityTokenRegistryAddress, regFee);
let registerTickerAction = securityTokenRegistry.methods.registerTicker(Issuer.address, tokenSymbol, "");
await common.sendTransaction(Issuer, registerTickerAction, defaultGasPrice, 0, 1.5);
} else if (details[0] == Issuer.address) {
available = true;
} else {
let approveAction = polyToken.methods.approve(spender, web3.utils.toWei(fee.toString()));
await common.sendTransaction(Issuer, approveAction, defaultGasPrice);
console.log('\n\x1b[31m%s\x1b[0m',"Token Symbol has already been registered, please choose another symbol");
}
} else {
let requiredBalance = parseInt(requiredAmount) - parseInt(polyBalance);
console.log(chalk.red(`\n*****************************************************************************************************************************************`));
console.log(chalk.red(`Not enough balance to Pay the Fee, Require ${(new BigNumber(requiredBalance).dividedBy(new BigNumber(10).pow(18))).toNumber()} POLY but have ${(new BigNumber(polyBalance).dividedBy(new BigNumber(10).pow(18))).toNumber()} POLY. Access POLY faucet to get the POLY to complete this txn`));
console.log(chalk.red(`******************************************************************************************************************************************\n`));
process.exit(0);
}

if (typeof _tokenConfig === 'undefined' && readlineSync.keyInYNStrict(`Do you want to transfer the ownership of ${tokenSymbol} ticker?`)) {
let newOwner = readlineSync.question('Enter the address that will be the new owner: ', {
limit: function(input) {
return web3.utils.isAddress(input);
},
limitMessage: "Must be a valid address"
});
let transferTickerOwnershipAction = securityTokenRegistry.methods.transferTickerOwnership(newOwner, tokenSymbol);
let receipt = await common.sendTransaction(Issuer, transferTickerOwnershipAction, defaultGasPrice, 0, 1.5);
let event = common.getEventFromLogs(securityTokenRegistry._jsonInterface, receipt.logs, 'LogChangeTickerOwnership');
console.log(chalk.green(`Ownership trasferred successfully. The new owner is ${event._newOwner}`));
process.exit(0);
}
}

async function step_token_deploy(){
// Let's check if token has already been deployed, if it has, skip to STO
let tokenAddress = await securityTokenRegistry.methods.getSecurityTokenAddress(tokenSymbol).call();
if (tokenAddress != "0x0000000000000000000000000000000000000000") {
console.log('\x1b[32m%s\x1b[0m',"Token has already been deployed at address " + tokenAddress + ". Skipping registration");
console.log('\n\x1b[32m%s\x1b[0m',"Token has already been deployed at address " + tokenAddress + ". Skipping deployment.");
let securityTokenABI = abis.securityToken();
securityToken = new web3.eth.Contract(securityTokenABI, tokenAddress);
} else {
console.log("\n");
console.log(chalk.green(`Current balance in POLY is ${(await currentBalance(Issuer.address))}`));
console.log("\n");
console.log('\x1b[34m%s\x1b[0m',"Token Creation - Token Deployment");
console.log('\n\x1b[34m%s\x1b[0m',"Token Creation - Token Deployment");

let launchFee = web3.utils.fromWei(await securityTokenRegistry.methods.getUintValues(web3.utils.soliditySha3(LAUNCH_FEE_KEY)).call());
console.log(chalk.green(`\nToken deployment requires ${launchFee} POLY & deducted from '${Issuer.address}', Current balance is ${(await currentBalance(Issuer.address))} POLY\n`));

if (typeof _tokenConfig !== 'undefined' && _tokenConfig.hasOwnProperty('name')) {
tokenName = _tokenConfig.name;
Expand All @@ -195,8 +184,8 @@ async function step_token_deploy(){
divisibility = true;
}

await step_approval(securityTokenRegistryAddress, regFee);
let generateSecurityTokenAction = securityTokenRegistry.methods.generateSecurityToken(tokenName, tokenSymbol, web3.utils.fromAscii(tokenDetails), divisibility);
await approvePoly(securityTokenRegistryAddress, launchFee);
let generateSecurityTokenAction = securityTokenRegistry.methods.generateSecurityToken(tokenName, tokenSymbol, tokenDetails, divisibility);
let receipt = await common.sendTransaction(Issuer, generateSecurityTokenAction, defaultGasPrice);
let event = common.getEventFromLogs(securityTokenRegistry._jsonInterface, receipt.logs, 'LogNewSecurityToken');
console.log(`Deployed Token at address: ${event._securityTokenAddress}`);
Expand Down Expand Up @@ -1126,6 +1115,51 @@ async function currentBalance(from) {
return balanceInPoly;
}

async function selectTicker(includeCreate) {
let result;
let userTickers = (await securityTokenRegistry.methods.getTickersByOwner(Issuer.address).call()).map(function (t) {return web3.utils.hexToAscii(t)});
let options = await Promise.all(userTickers.map(async function (t) {
let tickerDetails = await securityTokenRegistry.methods.getTickerDetails(t).call();
let tickerInfo = tickerDetails[4] ? 'Token launched' : `Expires at: ${moment.unix(tickerDetails[2]).format('MMMM Do YYYY, HH:mm:ss')}`;
return `${t}
${tickerInfo}`;
}));
if (includeCreate) {
options.push('Register a new ticker');
}

let index = readlineSync.keyInSelect(options, 'Select a ticker:');
if (index == -1) {
process.exit(0);
} else if (includeCreate && index == options.length - 1) {
result = readlineSync.question('Enter a symbol for your new ticker: ');
} else {
result = userTickers[index];
}

return result;
}

async function approvePoly(spender, fee) {
polyBalance = await polyToken.methods.balanceOf(Issuer.address).call();
let requiredAmount = web3.utils.toWei(fee.toString(), "ether");
if (parseInt(polyBalance) >= parseInt(requiredAmount)) {
let allowance = await polyToken.methods.allowance(spender, Issuer.address).call();
if (allowance == web3.utils.toWei(fee.toString(), "ether")) {
return true;
} else {
let approveAction = polyToken.methods.approve(spender, web3.utils.toWei(fee.toString(), "ether"));
await common.sendTransaction(Issuer, approveAction, defaultGasPrice);
}
} else {
let requiredBalance = parseInt(requiredAmount) - parseInt(polyBalance);
console.log(chalk.red(`\n*****************************************************************************************************************************************`));
console.log(chalk.red(`Not enough balance to Pay the Fee, Require ${(new BigNumber(requiredBalance).dividedBy(new BigNumber(10).pow(18))).toNumber()} POLY but have ${(new BigNumber(polyBalance).dividedBy(new BigNumber(10).pow(18))).toNumber()} POLY. Access POLY faucet to get the POLY to complete this txn`));
console.log(chalk.red(`******************************************************************************************************************************************\n`));
process.exit(0);
}
}

module.exports = {
executeApp: async function(tokenConfig, mintingConfig, stoConfig, remoteNetwork) {
return executeApp(tokenConfig, mintingConfig, stoConfig, remoteNetwork);
Expand Down
4 changes: 3 additions & 1 deletion CLI/commands/TickerRollForward.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ var abis = require('./helpers/contract_abis');
let remoteNetwork = process.argv.slice(2)[0]; //batch size

///////////////////////// GLOBAL VARS /////////////////////////
const REG_FEE_KEY = 'tickerRegFee';

let ticker_data = [];
let registered_tickers = [];
let failed_tickers = [];
Expand Down Expand Up @@ -78,7 +80,7 @@ async function readFile() {
async function registerTickers() {
// Poly approval for registration fees
let polyBalance = BigNumber(await polyToken.methods.balanceOf(Issuer.address).call());
let fee = await securityTokenRegistry.methods.getUintValues(web3.utils.toHex('tickerRegFee')).call();
let fee = web3.utils.fromWei(await securityTokenRegistry.methods.getUintValues(web3.utils.soliditySha3(REG_FEE_KEY)).call());
let totalFee = BigNumber(ticker_data.length).mul(fee);

if (totalFee.gt(polyBalance)) {
Expand Down
7 changes: 2 additions & 5 deletions CLI/commands/common/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,8 @@ module.exports = {
Issuer = await web3.eth.accounts.privateKeyToAccount("0x" + privKey);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
let accounts = await web3.eth.getAccounts();
Issuer = {
address: accounts[0],
privateKey: require('fs').readFileSync('./privKeyLocal').toString()
};
let privKeyLocal = require('fs').readFileSync('./privKeyLocal').toString()
Issuer = await web3.eth.accounts.privateKeyToAccount("0x" + privKeyLocal);
}
defaultGasPrice = getGasPrice(await web3.eth.net.getId());
}
Expand Down
Loading