How i make my smart-contract interact with my token? - token

I'm trying to develop a smart-contract where people can publish and get paid by it, i want the person get paid in the token of the platform not in eth. Without using the token the contract works ok, but when i try adding the contract doesn't works.
Thats the Token code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Capped.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Burnable.sol";
contract NewsToken is ERC20Capped, ERC20Burnable {
address payable public owner;
uint256 public blockReward;
mapping(address => bool) public validators;
constructor(uint256 cap, uint256 reward) ERC20("News Token", "NWT") ERC20Capped(cap * (10 ** decimals())) {
owner = payable(msg.sender);
_mint(owner, 70000000 * (10 ** decimals()));
blockReward = reward * (10 ** decimals());
}
function _mint(address account, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
require(ERC20.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
function _mintMinerReward() internal {
_mint(block.coinbase, blockReward);
}
function _beforeTokenTransfer(address from, address to, uint256 value) internal virtual override {
if(from != address(0) && to != block.coinbase && block.coinbase != address(0)) {
_mintMinerReward();
}
super._beforeTokenTransfer(from, to, value);
}
function setBlockReward(uint256 reward) public onlyOwner {
blockReward = reward * (10 ** decimals());
}
function destroy() public onlyOwner {
selfdestruct(owner);
}
function becomeValidator() public {
require(balanceOf(msg.sender)>=1000000 * (10 ** decimals()), "You need at least 1.000.000 tokens to become a validator");
validators[msg.sender] = true;
}
function removeValidator() public {
require(validators[msg.sender], "You are not a validator");
validators[msg.sender] = false;
}
function checkValidator() public view returns (bool){
return validators[msg.sender];
}
modifier onlyOwner {
require(msg.sender == owner, "Only the owner can call this function");
_;
}
function callApprove(address _sender,address _writer, uint256 _amount) public {
_sender.approve(_writer, _amount);
}
}
Thats the Contract code:
//contracts/Web3News.sol
//SPDX-License-Identifier: MIT
import "./paymentManager.sol";
import "./NewsToken.sol";
pragma solidity ^0.8.17;
contract Web3News{
address public writer;
string public title;
string public topics;
string private subject;
string private Autentic = "O artigo e verdadeiro";
string private Fake = "O artigo e Falso";
uint public minimumPayment;
uint public itsAutentic;
uint public itsFake;
mapping(address => bool) public buyers;
//Importa o contrato do NewsToken e do PaymentManager
NewsToken public newsToken;
//PaymentManager public paymentManager;
event LogSecretAccess(address indexed sender);
constructor(address _newsTokenAddr, string memory _title, string memory _topics, string memory _subject, uint _minimumPayment){
writer = msg.sender;
title = _title;
topics = _topics;
subject = _subject;
minimumPayment = _minimumPayment;
newsToken = NewsToken(_newsTokenAddr);
//paymentManager = PaymentManager(_paymentManagerAddr);
}
//Da acesso do conteudo do artigo para quem pagar
//function getAccessToArticle() public payable{
//Verifica no contrato do NewsToken se o usuario tem saldo suficiente para pagar a taxa minima
// require(newsToken.balanceOf(msg.sender) >= minimumPayment, "Not enough tokens.");
//Faz o pagamento do artigo para o contrato do PaymentManager que manda o pagamento ao criador do artigo
//newsToken.approve(address(this), minimumPayment);
//require(newsToken.allowance(msg.sender, address(this)) >= minimumPayment, "You have not approved the contract to transfer the tokens");
// newsToken.transferFrom(msg.sender, writer, minimumPayment);
// buyers[msg.sender] = true;
//paymentManager.payForNews(address(this), minimumPayment);
//}
function getAccessToArticle1() public payable {
require(newsToken.balanceOf(msg.sender) >= minimumPayment, "Not enough tokens");
newsToken.approve(address(this), minimumPayment);
//chamar uma funcao que transfere os fundos do msg.sender pra o contrato?
newsToken.transferFrom(msg.sender, writer, minimumPayment);
//newsToken.transfer(tx.origin, minimumPayment);
buyers[msg.sender] = true;
}
//function getAccessToArticle() public payable {
// require(newsToken.balanceOf(msg.sender) >= minimumPayment, "Not enough tokens.");
//address tokenContractAddress = address(newsToken);
//bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", address(writer), minimumPayment);
//(bool success, bytes memory returnedData) = tokenContractAddress.call(data);
//require(success, "The call to the transfer function was not successful.");
//buyers[msg.sender] = true;
//}
//Puxa o conteudo do artigo para o usuario caso o mesmo tenha pago a taxa minima para acessar o artigo
function readArticle() public returns (string memory) {
//Verifica no contrato do PaymentManager se o usuario se encontra na lista de compradores
require(buyers[msg.sender], "This address haven't purchased the article");
emit LogSecretAccess(msg.sender);
return subject;
}
//Funcao para votar como fakenews
function fakenews(bool _itsAutentic) public {
require(buyers[msg.sender], "This address haven't purchased the article, so it can't vote");
if (_itsAutentic) {
itsAutentic = itsAutentic + 1;
} else {
itsFake = itsFake + 1;
}
}
//Funcao para julgar se e ou nao fakenews. Deve ser ativada somente por um autenticador/delegado
function judgement() public view returns (string memory) {
//Verifica se o endereco que esta chamando a funcao e um autenticador na lista de autenticadores do NewsToken
require(newsToken.checkValidator(), "This address is not a validator");
if (itsAutentic > itsFake) {
return Autentic;
} else {
return Fake;
}
}
//Funcao para punir quem autenticar a noticia de forma erronea
}
I know that the problem is: when calling the transfer method on the token the address that is calling the function is the address of the contract and not the msg.sender, i had try the call(), the delegatecall(), and other methods. It's not clear to me how can i sove that, hopping some one can help me here...

Related

Update Token Information Page

I did the first 2 steps, verifying the contract address, but because I didn't know much about smart contracts before, I also created many wallets,enter image description here now the last step is to verify the signature, I don't know I used the wallet any. . Can anyone guide me to redo or what is possible in my case? Thank you very much alone! help
/**
*Submitted for verification at Etherscan.io on 2017-11-28
*/
pragma solidity ^0.4.17;
/**
* #title SafeMath
* #dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* #title Ownable
* #dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* #dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* #dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* #dev Allows the current owner to transfer control of the contract to a newOwner.
* #param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* #title ERC20Basic
* #dev Simpler version of ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* #title ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* #title Basic token
* #dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
// additional variables for use if transaction fees ever became necessary
uint public basisPointsRate = 0;
uint public maximumFee = 0;
/**
* #dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* #dev transfer token for a specified address
* #param _to The address to transfer to.
* #param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(msg.sender, owner, fee);
}
Transfer(msg.sender, _to, sendAmount);
}
/**
* #dev Gets the balance of the specified address.
* #param _owner The address to query the the balance of.
* #return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* #title Standard ERC20 token
*
* #dev Implementation of the basic standard token.
* #dev https://github.com/ethereum/EIPs/issues/20
* #dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* #dev Transfer tokens from one address to another
* #param _from address The address which you want to send tokens from
* #param _to address The address which you want to transfer to
* #param _value uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(_from, owner, fee);
}
Transfer(_from, _to, sendAmount);
}
/**
* #dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* #param _spender The address which will spend the funds.
* #param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* #dev Function to check the amount of tokens than an owner allowed to a spender.
* #param _owner address The address which owns the funds.
* #param _spender address The address which will spend the funds.
* #return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* #title Pausable
* #dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* #dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* #dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* #dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* #dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract UpgradedStandardToken is StandardToken{
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
contract TetherToken is Pausable, StandardToken, BlackList {
string public name;
string public symbol;
uint public decimals;
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// #param _balance Initial supply of the contract
// #param _name Token Name
// #param _symbol Token symbol
// #param _decimals Token decimals
function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
if (deprecated) {
return StandardToken(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
} else {
return _totalSupply;
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// #param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// #param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
Redeem(amount);
}
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints < 20);
require(newMaxFee < 50);
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(10**decimals);
Params(basisPointsRate, maximumFee);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
// Called if contract ever adds fees
event Params(uint feeBasisPoints, uint maxFee);
}

Applying condition of whitelisted users to sell bep20 token on pancake swap

I want to add one condition in my bep20 token, only whitelisted addresses should be able to sell my token on the exchange. I tried this but it is not working since all addresses are able to sell. Need help in figuring this out, thanks.
pragma solidity ^0.8.7;
contract CHANCE is ERC20, Ownable {
using SafeMath for uint256;
IPancakeV2Router02 public pancakeV2Router;
address public immutable pancakeV2Pair;
mapping (address => bool) public Whitelist;
constructor() ERC20("CHANCE", "CHCE") {
IPancakeV2Router02 _pancakeV2Router = IPancakeV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);
// Create a pancake pair for this new token
address _pancakeV2Pair = IPancakeV2Factory(_pancakeV2Router.factory())
.createPair(address(this), _pancakeV2Router.WETH());
pancakeV2Router = _pancakeV2Router;
pancakeV2Pair = _pancakeV2Pair;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 200000000000 * 10 ** 18);
emit Transfer(address(0), msg.sender, totalSupply());
}
function burn (uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(to == pancakeV2Pair){
require(Whitelist[msg.sender] == true,"Whitelist can mint only!");
super._transfer(from, to, amount);
}
super._transfer(from, to, amount);
}
function whitelist(address _address) public onlyOwner returns (bool){
Whitelist[_address] = true;
return true;
}
}

browser/ballot.sol:102:18: ParserError: Expected '{' but got identifier contract token is ERC20Interface, Owned, SafeMath { ^----^

I get an error msg when trying to compile
ParserError: Expected '{' but got identifier
contract token is ERC20Interface, Owned, SafeMath {
^----^
on line 102 in the code
pragma solidity ^0.4.19;
// --------------------------------------------------------------------
--------
// 'reSTEEM Reward token' token contract
//
// Deployed to : 0xC03fBB28Ce8280B97ecFa7b9a62112d507BA4c0a
// Symbol : rRt
// Name : reSTEEM Reward token
// Total supply: 300000000000000000000000
// Decimals : 18
//
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract reSTEEM Reward token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function reSTEEM Reward token() public {
symbol = "rRt";
name = "reSTEEM Reward token";
decimals = 18;
_totalSupply = 300000000000000000000000;
balances[0xC03fBB28Ce8280B97ecFa7b9a62112d507BA4c0a] = _totalSupply;
Transfer(address(0), 0xC03fBB28Ce8280B97ecFa7b9a62112d507BA4c0a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
Now it I’m getting this error when trying to verify the contract
myc:31:1: ParserError: Function, variable, struct or modifier declaration expected. function safeAdd(uint a, uint b) public pure returns (uint c) { ^
cannot for the life of me figure this out , i'm new to thi If anyone could please help it was be immensely appreciated
The error I see (after fixing a stray newline that breaks one of the comments) is:
browser/Untitled3.sol:101:18: ParserError: Expected '{' but got identifier
contract reSTEEM Reward token is ERC20Interface, Owned, SafeMath {
^----^
That code is invalid... I'm guessing you wanted to name the contract something like "reSTEEM Reward token", but you can't have spaces in an identifier.
Try this instead:
contract reSTEEMRewardToken is ...
You'll then have to fix the same issue in the constructor.

Boolean method not retuning correct value

Ok so I think I'm being a noob because it's a new semester but the method "palindromeTest" always return's false even though the string is equal and the number is a palindrome. (A palindrome example is: (565) 677-6565) (also don't give me the answer outright I want to solve it on my own)
public class IjazZ_PhoneStringPalindrome
{
public static void main(String[] args) throws IOException
{
String phoneNumber;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a phone number in this format (###) ###-####: ");
phoneNumber = br.readLine();
phoneNumber = justNumbers(phoneNumber);
if (palindromeTest(phoneNumber))
{
System.out.println("This phone number is a palindrome!");
}
else
{
System.out.println("This phone number is not a palindrome!");
}
}
public static String justNumbers(String phoneNumber)
{
StringTokenizer st = new StringTokenizer(phoneNumber, " ()-");
StringBuffer number = new StringBuffer();
while(st.hasMoreTokens())
{
number.append(st.nextToken());
}
phoneNumber = number.toString();
return phoneNumber;
}
public static boolean palindromeTest(String pNumber)
{
StringBuffer reversedNumber = new StringBuffer(pNumber);
reversedNumber.reverse().toString();
if(pNumber.equals(reversedNumber))
{
return true;
}
else
{
return false;
}
}
}
You don't assign the value returned by reversedNumber.reverse().toString()to reversedNumber.
Do
String reversedNumberString = reversedNumber.reverse().toString();
And by the way, you can just return
return pNumber.equals(reversedNumber); - the if/else statement is unnecessary.

JFLEX AND CUP, cannot make it work correctly

I'm working with jflex and cup, trying to make a html parser,
but can't make it work correctly,
Netbeans, the compile process dont stop, always continues,
Can't add more "tokens" correctly in the parse tree,
Also can't add space in "TEXTO" , this break the entire tree
lexicoh.jlex
package compiladorhtml;
import java_cup.runtime.*;
%%
%class Lexer
%line
%column
%cup
%{
private Symbol symbol(int type) {
return new Symbol(type, yyline, yycolumn);
}
private Symbol symbol(int type, Object value) {
return new Symbol(type, yyline, yycolumn, value);
}
%}
LineTerminator = \r|\n|\r\n
WhiteSpace = {LineTerminator} | [ \t\f]
texto = [a-zA-Z0-9_]*
%%
<YYINITIAL> {
"::" { System.out.print("<"); return symbol(sym.INI);}
"ENCA" { System.out.print("HEAD>"); return symbol(sym.HEAD);}
"/" { System.out.print("</"); return symbol(sym.FIN);}
{texto} { System.out.print(yytext()); return symbol(sym.TEXTO);}
{WhiteSpace} { /* just skip what was found, do nothing */ }
"&&" { System.out.print(""); return symbol(sym.FINAL); }
}
[^] { throw new Error("Illegal character <"+yytext()+">"); }
sintaticoh.cup
package compiladorhtml;
import java_cup.runtime.*;
parser code {:
public void report_error(String message, Object info) {
StringBuilder m = new StringBuilder("Error");
if (info instanceof java_cup.runtime.Symbol) {
java_cup.runtime.Symbol s = ((java_cup.runtime.Symbol) info);
if (s.left >= 0) {
m.append(" in line "+(s.left+1));
if (s.right >= 0)
m.append(", column "+(s.right+1));
}
}
m.append(" : "+message);
System.err.println(m);
}
public void report_fatal_error(String message, Object info) {
report_error(message, info);
System.exit(1);
}
:};
terminal INI, HEAD, TEXTO, FIN, FINAL;
non terminal Object expr_list, expr_part;
non terminal String expr;
expr_list ::= expr_list expr_part | expr_part;
expr_part ::= expr:e;
expr ::= INI HEAD
| TEXTO
| FIN HEAD
| FINAL;
java Main
public static void main(String[] args) throws IOException, Exception {
//CreateFiles();
//EJECUTAR PARA VER SI FUNCIONA, YA LO VI Y FUNCIONA
File fichero = new File("fichero.txt");
PrintWriter writer;
try {
writer = new PrintWriter(fichero);
writer.print("::ENCA NOMBRE ENCABEZADO /ENCA &&");
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
Lexer thisscanner = new Lexer(new FileReader("fichero.txt"));
parser thisparser = new parser(thisscanner);
thisparser.parse();
}
public static void CreateFiles() {
String filelex = "path\\lexicoh.jlex";
File file = new File(filelex);
jflex.Main.generate(file);
String opciones[] = new String[5];
opciones[0] = "-destdir";
opciones[1] = "path";
opciones[2] = "-parser";
opciones[3] = "parser";
opciones[4] = "path\\sintacticoh.cup";
try {
java_cup.Main.main(opciones);
} catch (Exception ex) {
Logger.getLogger(CompiladorHTML.class.getName()).log(Level.SEVERE, null, ex);
}
}
thanks
I think that you should do this:
for {texto}, since it is a string composed by text and number, you should redefine it in this way:
{texto} { System.out.println (yytext()); return new symbol(sym.TEXTO, new String (yytext())); }
Then, if the program doesn't stop, there could be some problems during the read of the source file.

Resources