texts:
In raiden network,
Why do you use a merkle balance proof instead of just a seriliazed list of transactions?

also in the smart contract for the hashlock, you use a merkle tree, whats the purpose of this?


texts: Publicly hosting parity rpc - Provided Host header is not whitelisted

texts:
I setup an ubuntu test server in the cloud with parity installed. My desire is to publicly expose the parity RPC service on port 8545 for testing purposes. Currently, I am ignoring whether this is safe or not.

The parity config.toml file is shown below.  When I navigate to xxx.xxx.xxx.xxx:8545 in the browser I see the following message:

  Provided Host header is not whitelisted.

I was expecting instead to see Used HTTP Method is not allowed. POST or OPTIONS is required. As a sanity check if I turn parity off I get a page not found error.

config.toml

[rpc]
    # Allows Cross-Origin Requests from domain '*'.
    interface = "all"
    cors = "*"
    # Allow connections only using specified addresses.
    hosts = ["", "*"]

Related:

Curl error
Is it safe to do this?


texts:
How the best path is calculated ? Is it a fonction in the smart contract or on the website ?
Because I checked the function swapExactETHForTokens and the path need to be set by the function caller.
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }

If I want to swap programatically, how I'm supposed to know the best path ?


texts: Migrates contract with specific account without hard-code address using truffle and Genache

texts:
Block Builders! I am trying to migrate my two smart contracts using truffle and Genache. I would like to specify the deploying accounts existing locally. However, when I try to migrate the contracts I get error prompt that the provided address being invalid.

Here is my 2_deployed_contracts.js

var Bank = artifacts.require("Bank");
var Client = artifacts.require("Client");

module.exports = function(deployer, accounts) {
  deployer.deploy(Bank, {from: accounts[0], value:
  web3.utils.toWei("30", "ether")}).then((bank)=>{
    return deployer.deploy(Client, bank.address, {from:accounts[1]});
  });
};

and the reported error prompt:

Error:  *** Deployment Failed ***

"Bank" -- Provided address "d" is invalid, the capitalization checksum test
failed, or its an indrect IBAN address which can't be converted..

at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-
deployer/src/deployment.js:364:1
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

Only when I hard code the account address at from field, the migration success. The accounts variable seems not working like most of the other posts suggested. I could not figure it out why, because I thought truffle would inject accounts variable.


texts:
From Ethereum's website (emphasis mine):

  Using Ethereum, you can create a contract that will hold a contributor's money until any given date or goal is reached.
  Depending on the outcome, the funds will either be released to the
  project owners or safely returned back to the contributors. All of
  this is possible without requiring a centralized arbitrator,
  clearing house or having to trust anyone.

Taken literally, this of course is not possible. A toy example may have computationally verifiable goals, but almost all real projects have ambiguous goals. Who's to say whether a goal has been reached or not? Are contributors the eventual judges on that? In that case, doesn't the project owners need to trust the contributors?

Can someone explain the central idea behind this trust-less kickstarter concept?


texts: Where does contract’s call failure behavior is definied in the yellow paper?

texts:
If a contract’s call succeeds then 0x1 is pushed on the stack and 0x0 otherwise.
Where is this behavior defined in the yellow paper ?

Also, are there cases were sending ether isn’t reverted in recipient but 0x0 or nothing is pushed on the stack ?


texts: What is the length of an empty fixed sized array?

texts:
Let's say we initialize a state variable as:

uint[10] public fixed_array;

This is a fixed sized array which is currently empty.

What would fixed_array.length return? 0 or 10?


texts:
Guys I really need your help. I had purchased DAO tokens initially from this address: 0xA54367910EFEBA7B03B0aEcd8fFa62181b612038. I had 9000 tokens. When the attack happened I transfered them to Poloniex wanting to sell them, but I never did. Now when the fork happened, I wanted to withdraw my DAO tokens and convert them back to ETH. I followed this guide

After making all the steps I somehow see 38,000 ETH in my DAO contract in the Wallet, a lot of transactions saying "The DAO - Token transfer" with some huge amount of DAO tokens and no ETH refunded to me.

I really am confused what is going on and scared that I might have done something irrevirsible. Thanks for your help.


texts: Can't call a function in a contract, returning something from another contract

texts:
I use private geth + web3js    (in truffle this works good)

Here is an example worked as expected:

the first contract:

pragma solidity ^0.4.24;
import "./Second.sol";

contract First {
    Second private _oSecond;
    int32 public _nRes1;

    constructor(address oSecond) public payable {
        _oSecond = Second(oSecond);
        _nRes1 = 3;
    }
    function TestError() public {
        _oSecond.State();
        //_oSecond._nRes2();  // the problem call is here
        _nRes1 = 5;
    }
}

the second contract:

pragma solidity ^0.4.24;

contract Second {
    int32 public _nRes2;

    constructor() public {
        _nRes2 = 15;
    }
    function State() public {
        _nRes2 = 17;
    }
}

web3js:

(async () => {
    await first.methods.TestError().send({from: accounts[0]});
    var nRes = await first.methods._nRes1().call({from: accounts[0]});
    console.log(nRes);

    var nRes = await second.methods._nRes2().call({from: accounts[0]});
    console.log(nRes);
})();

The result:
5
17

But if we uncomment string  "//_oSecond._nRes2();" the resul will be wrong:
3
15

No error messages!
In web3js I tried call with promises or callbacks - the same result.
In TestError I tried call different functions instead of _nRes2(), in different order, but result was the same - wrong.
If we call function wich returns Nothing, like State() - all is ok.
If we call function wich returns ANY type of value - all is not ok!
Why? How to fix it?

Geth Version is: 1.8.10-stable
Node js version is: v8.1.0
solc version is: 0.4.24
web3 version is: 1.0.0-beta.35

--- editing ---
My js code after Rob Hitchens answer:

(async () => {
    var cRes = await first.methods.TestError().send({from: accounts[0]});
    await web3.eth.getTransactionReceiptMined(cRes.transactionHash); // well mined!
    sleep.sleep(30); // even 30 seconds of sleeping didn't help

    var nRes = await first.methods._nRes1().call({from: accounts[0]});
    console.log(nRes);  // 3
    var nRes = await second.methods._nRes2().call({from: accounts[0]});
    console.log(nRes);   // 15
})();


texts: Web3 sending custom tokens by using the transfer function. Need to set the from account

texts:
Looking to code WEB3 to be able to send custom tokens out programmatically.

However, I am not sure where to specify the user account that actually sends the token.

This is the code I have thus far. I

var custom_token_address = req.params.customtoken;
  var abi = loadABI();
  var MyContract = web3.eth.contract(abi);
  var myContractInstance = MyContract.at('0x416DFae2FED9B7a282E8beaC750210A7d952204A');

web3.eth.contract(abi).at(custom_token_address).transfer('0x61E28c6d1e5159E2415644FBBE5E0D40542e4C8c', 10000);

Where is is that I set the from account in all of this?

Thank you


texts:
Are there transactions with contract's codes inside it? (for example when a new contract is created or when a user call a method from a contract)

If not, how can ethereum vm know what code to be execute when needed?


texts: Reproducing a Ganache Server across multiple computers

texts:
There are multiple developers on the team and it seems as though we all want to be working on a specific test network with specific public and private keys with a specific number of users who all have a prespecified balance. We have chosen to work with Ganache.
Now I am aware of https://github.com/trufflesuite/ganache-cli options with --account=. This does not allow for the specification of the public key of each user. What is the standard when recreating a network? Am I missing out on something fundamental to this process? What are my options?


texts: Hide return values of a smart contract function

texts:
Let's say that I have a smart contract A with a public function f that can be called by anyone and this public function will return a number. In the smart contract there is also a private function p which returns a list of numbers.

Now if f calls p during its execution and then uses p's return value to generate its return value would every node in the network know the return value of p?

My main goal is to keep the return values of p not accessible by every node in the network


texts: How to continue to watch the `Events` from the point `geth` was closed?

texts:
I have a private Ethereum network. The bootnode(main node)'s goal is to watch Events and if a new Event is generated than trigger a contract's function that I want to run. The key point is triggered contract's function should only called and run once. Please note that the bootnode(main node) does not mine and geth runs inside bootnode(main node).

watch() should be run on geth's background so when new block is deployed latest should also point new deployed block number, since latest block number keep increases.

For example, I am running following solution on geth.

> var theDAOVotedEvent = theDAO.Voted({}, {fromBlock: 1614771, toBlock: 'latest'});
undefined
theDAOVotedEvent.watch(function(error, result){
  console.log(JSON.stringify(result));
  //call a contract's function. (this should called only one time)
});

As I understand, when a new Event is generated, watch() will be called and it will print out on geth console the following example line and call a contract's function.

{"address":"0xbb9bc244d798123fde783fcc1c72d3bb8c189413","args":{"position":false,"proposalID":"11","voter":"0xebbf5d7d649aedde2c27a8b850a2a3862595eb53"},"blockHash":"0x69be968ce90c7e910c149cc80ab1e5f2ae6bdb45f142ee0e6fa181be9d1e106e","blockNumber":1614812,"event":"Voted","logIndex":0,"transactionHash":"0x6b5cab6f7987d7283fdde051c76ace98c9f080bda6dbdf720689fc0c3958005b","transactionIndex":2}
...

[Q] For example the bootnode (main node) restarted and geth closed and re-opened after 5 minutes. At this point, while geth was closed, assume new 20 blocks and 50 new Events are generated. When I re-start geth inside the bootnode's (main node), how could I continue to watch the Events from the block number that bootnode's (main node) was closed?

This approach is similar to use a pipe ("Whatever bytes are sent into the input of the pipe can be read from the other end of the pipe."). For example, when geth is shut down, Events should queued in pipe and when geth is alive again it should continue reading Events from the pipe.

I have come up with the following solution, but since synchronisation is done right after geth is re-open I was not able to run the following code piece before the synchronisation started.

//I think watch() should start from the latest retrieved block's number on bootnode (main node).

latestWatched        = eth.blockNumber;
var theDAOVotedEvent = theDAO.Voted({}, {fromBlock: latestWatched, toBlock: 'latest'});

theDAOVotedEvent.watch(function(error, result){
   console.log(JSON.stringify(result));
   //call a contract's function. (this should called only one time)
});

Thank you for your valuable time and help.


texts:
Has anyone encountered the following scenario on Ropsten:

You create an account in Geth, and proceed to transfer some ETH to yourself via a faucet.
You unlock the account and proceed to start compiling and running contracts.
Suddenly you find that all your ETHs are gone, transferred to 0x6Ef57BE1168628A2bD6c5788322A41265084408a.

This happened to me and a group of participants during a workshop where in a matter of seconds, all our ETH were stolen.

If you look at the transaction that has happened on this account in Etherscan, it runs in spurts, having small, and sometimes rather considerable amount of ETH transferred to itself.

Wanted to find out if this is something explainable. I realized that the same address 0x6Ef57BE1168628A2bD6c5788322A41265084408a is also found on Rinkeby.


texts: How do I extract the v, r, s values from a signed transaction?

texts: If I have a signed transaction such as 0xf86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83 (taken from https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md), how do I go about extracting the v,r and s values from this without using some external library?


texts: I have recently heard about whiteblock testing platform, however, there is no details on how to build your own test. Do you have any idea about how to use it and how powerful the platform is?


texts: What's a fallback function when using address.send(...)?

texts:
This code is in my contract:

 contract A {
      address x = 0x1234...;
      x.send(10);
 }

What would fallback function in the contract at address 0x1234... look like?

 contract B {
     ...
 }

I can't find any info on these fallback functions except here:


texts:
The most of "decentralized applications" are a "web" application as follows :

Front End (usually JavaScript) => Smart Contract (usually Solidity) => Blockchain (usually Ethereum)

Is this the only schema of a Dapp? And if there is other schema, could you describe another schema of a Dapp?


texts: What is the approximate cost to store a mapping to be used in a contract?

texts:
Given a simple address to address mapping as follows:

mapping (address => address) public matches;

Can someone give me an idea of the cost in ether to store something like this in a solidity contract? I understand that there are gas costs associated with every alteration of the blockchain and storage is expensive but I am having trouble finding estimations of what simple storage like a mapping would cost.

The feasibility of my Dapp idea depends on storing mappings from address to address cheaply. Ideally around 1 cent USD or so. If mappings are more expensive are there any workarounds? Thanks.


texts: How to instantiate a memory-struct and assign it to a storage

texts:
I'm trying to understand the following code from the Solidity documentation:
struct Funder {
    address addr;
    uint amount;
}

contract Crowdfunding {
    struct Campaign {
        address payable beneficiary;
        uint fundingGoal;
        uint numOfFunders;
        uint amount;
        mapping(uint => Funder) funders;
    }

    uint numOfCampaigns;
    mapping(uint => Campaign) campaigns;

    function newCampaign(address payable beneficiary, uint goal) public returns (uint campaignID) {
        numOfCampaigns ++;
        Campaign storage c = campaigns[campaignID]; // this line
        c.beneficiary = beneficiary;
        c.fundingGoal = goal;
    }
}

But, I have three questions:

Why doesn't this line Campaign storage c = campaigns[campaignID]; throw an out-of-range failing assertion? As far as I understand, the instance of Campaign with a matching campaignID doesn't exist in the campaigns array since we're creating a new one.  Is this a way of instantiating a new Campaign struct?

The documentation explains that the reason they're not instantiating a new Campaign struct with campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0) in this case is "because the RHS creates a memory-struct "Campaign" that contains a mapping". But, here also says that "Assignments between storage and memory (or from calldata) always create an independent copy", which seem to mean it's permitted. So, I'm not sure why assigning a memory-struct to a storage is a problem.

Finally, the newCampaign function signature says that it's to return campaignID by stating returns (uint campaignID). But, the executable code doesn't actually return anything.  Is this simply implied that the variable campaignID will be returned?


texts: Explorer for Private Blockchain with Ganache

texts: I set up a private blockchain with ganache in the server. Now I want to view the transactions like in the public blockchain explorer. Locally I use Ganache GUI where I can actually track down everything. How can I do the same for my private blockchain?


texts: Remix -> Function call: Gas required exceeds limit

texts:
I keep gettting a "Gas exceeds limit" on a simple function trying to transfer ERC20 Tokens from one wallet to another. My first question is what is the most efficient way to debug such an error ? Second would be does anyone see anything wrong with my function as it is ?

Here is the error:

Transact to browser/SmartLoan.sol:Loan.sendFunds errored: Gas required exceeds limit: 3000000.  An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that's also the reason of strong gas estimation).

And here is the function that errors when it is called:

    function sendFunds(address dest, uint amount) public {
        if(totalPayments < loanStatics.totalAmount){

            address addressToken = 0xfef45491b96af14c98b81325cbb7a3fbb83bb7a0;
            abstractToken Token = abstractToken(addressToken);
            Token.transferFrom(msg.sender, dest, amount);

            totalPayments = totalPayments.add(amount);
            payments[msg.sender] = payments[msg.sender].add(amount);
            company = dest;
        }

        if(totalPayments == loanStatics.totalAmount){
            status = Status.funded;
        } else {
            status = Status.partially_funded;
        }
        LoanFunded(status, amount);
    }

Here is how I create the contract abstract:

contract abstractToken {
   function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}

UPDATE

Here is a print screen of the console, seems like my transaction doensn't even get created, or at least I don't know how to get the hash for it and therefore I am not sure how to debug it...


texts: What is the "main" difference between consensus mechanism of Bitcoin and Ethereum?

texts:
Bitcoin and Ethereum both use proof-of-work (PoW) consensus mechanism. One of differences between Bitcoin Pow and Ethereum PoW is difficulty level, meaning that while in bitcoin block generation rate is 10 minutes on average, in Ethereum is around 12 seconds on average.

Is there any other major difference between these two PoW algorithm?
For example, does Ethereum use proof-of-stake (PoS) in parallel?


texts:
Ive made a dapp work on my system without a geth node working with metamask. The idea is that every user that comes up to the website has to spend his own gas for the transaction, so in metamask a popup comes up verifying the transaction gas. When I try to run this in Mist browser, no popup nothing comes up(no signing of transaction)..? and then no transaction actually takes place. How is it suppose to work in Mist?? Is the popup actually suppose to come up like metaamask? Will it even pick my web3 instance? It gives this error when I try to a transaction in Mist(runs fine with metamask)...
Any help appreciated. thanks.


texts: How to take a string with variable length decimal places, and convert it to a whole number uint?

texts:
I'm experimenting with writing an ethereum-usd price ticker taking data from the coinmarketcap API using Oraclize's API.

I noticed that Oraclize has a function called parseInt that can be used to remove the numbers after the decimal from a string (such as 10.99) an turn it into the uint 10.

As far as I can tell this ONLY works with strings that have a FIXED length after the decimals. As per CMCs API, the length after the decimal is variable in length. I've noticed it being values such as 1000.99 or 1000.991

I'm unable to figure out how to parse this string of a variable decimal length and turn it into a whole number.


texts: Can unverified contracts expose a public ABI?

texts:
I am trying to understand if there are unverified contracts that come with a public ABI.
I was exploring contracts on Etherscan, and I was only able to find unverified contracts without source code and without ABI. Are all unverified contracts like this? Or is it possible to find unverified contracts with a public ABI?
Thanks in advance


texts: Truffle overwrite MetaMask web3 wrong msg.sender address

texts:
Considering this contract :

pragma solidity ^0.4.7;

contract Test {

    function Test() {
        // constructor
    }

    function getMsgSender() constant returns (address account) {
        account = msg.sender;
    }

}

When I deploy my app with truffle serve and use chrome dbg and run

var t = Test.deployed();
t.getMsgSender().then(function(res) {
    console.log(res.toString())
});

I expect to received my accounts[0] but I received another address which I'm not aware of.

EDIT
As Roland Kofler said on the comment section, it seems that the injected web3 form MetaMask is somehow overwrite by web3 provided by truffle.
When I open another tab and play with the injected web3 from MetaMask :

var testContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"getMsgSender","outputs":[{"name":"account","type":"address"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]);
var test = testContract.new(
   {
     from: web3.eth.accounts[0],
     data: '0x606060405234610000575b5b5b60bd8061001a6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637a6ce2e114603c575b6000565b3460005760466088565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60003390505b905600a165627a7a7230582010d921743656299a4367d73c9ad8249848967aebebbc91093aeb9dce6f74a3380029',
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })
test.getMsgSender(function(error, result) {
    console.log(result.toString()) // Works, accounts[0] as result
});

Is there a way to make things works with truffle ? Where does the address I get from the overwriting cames from ?


texts:
When we look at this block - what does the first number

Hash: 0xfe88c94d860f01a17f961bf4bdfb6e0c6cd10d3fda5cc861e805ca1240c58553

actually mean? How is it calculated?

"Nonce" is the value that is changed during mining, but what is hash?


texts: How to order struct in descending and ascending order?

texts:
I have the following struct used for adding few details. Objective is to sort in descending order. Initially highest totalpoints record will be displayed. I would like to create two buttons

1) Forward - which will fetch highest totalpoints record and again if we click on the same button it should fetch the next highest totalpoints record from the struct.

2) Backward - vice-versa of above.

struct struUser{
    address userAddress;
    uint256 id;
    bytes32 originalKshoplink;
    bytes32 orginalDocumentConvention;
    bool validated;
    uint32 Points;
    uint32 totalPoints;
}

If i add the first record then it will be something like:

UserAddress: 0x000123

Id:1

originalKshoplink :http://kshoplink

originalDocumentConvention :doc1

validated:true

Points:10

totalPoints:10

If i add the second record then it will be something like:

UserAddress: 0x000123

Id:1

originalKshoplink :http://kshoplink

originalDocumentConvention :doc1

validated:true

Points:10

totalPoints:20(earlier 10points + 10points for this record)

This is for one user and i have some similar records for other user. Now i have to write a function which will return the UserAddress and his totalPoints(e.g. 100 totalPoints consider this as base).

Consider the current viewed totalPoints are 100. When i click on forward button it should fetch the next highest UserAddress and his totalPoints(e.g. 90 totalPoints), when i click again on forward button it should fetch the next highest UserAddress and his totalPoints(e.g. 80 totalPoints).

Consider the current viewed totalPoints are 80. When i click on backward button it should fetch second highest UserAddress and his totalPoints(e.g.90 totalPoints) , when i click again on backward it should fetch the third highest userAddress and his totalPoints(e.g. 100 totalPoints).

How should i achieve this in solidity? kindly let me know in case of any queries.


texts: Transferring ERC20 token to a contract using custom function

texts:
I have a couple of questions related to transferring ERC20 token to a contract.
I am developing a protocol that has its own token to provide incentive mechanisms. For certain operations I need to lock tokens in the protocol contract.
The traditional way is to use approve and then transferFrom. But I want to avoid doing this in two txs (for the UX, for the gas, etc). Doing some research I found a lot of proposals that fixes this: ERC2612 (ERC20 + Permit function), ERC-1363, ERC-777, ERC-1155 and many more.
If I had to choose any right now, I would choose ERC2612 permit function (Uniswap / MakerDAO solution). But I was wondering, why not to whitelist the contract address in the token and use a custom non-standard function to perform the transfer without approval in a single tx. I will attach a simplified token and contract example code below to let you see what I am describing:
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {

    modifier onlyProtocolContract() {
        require(_msgSender() == protocolContract, "Only protocol contract can call this function");
        _;
    }

    modifier onlyOwner() {
        require(_msgSender() == owner, "Only owner can call this function");
        _;
    }

    address owner;
    address protocolContract;

    constructor() ERC20("Token", "TKN") {
        owner = _msgSender();
    }

    function setProtocolContractAddress(address _protocolContract) external onlyOwner() {
        protocolContract = _protocolContract;
    }

    function transferToProtocolContract(address _fromAccount, uint256 _amount) external onlyProtocolContract() {
        _transfer(_fromAccount, protocolContract, _amount);
    }
}

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Token } from "./Token.sol";

contract Protocol {

    using SafeMath for uint256;

    Token token;

    mapping(address => uint256) stakedBalance;

    constructor(Token _token) {
        token = _token;
    }

    function stake(uint256 _amount) external {
        require(token.balanceOf(msg.sender) >= _amount, "Token balance below given staking amount");
        token.transferToProtocolContract(msg.sender, _amount);
        stakedBalance[msg.sender] = stakedBalance[msg.sender].add(_amount);
    }

    function unstake(uint256 _amount) external {
        require(stakedBalance[msg.sender] >= _amount, "Staked tokens below given amount to unstake");
        token.transferFrom(address(this), msg.sender, _amount);
        stakedBalance[msg.sender] = stakedBalance[msg.sender].sub(_amount);
    }
}

I deployed this solution and it works. So, my questions are:

I didn't find anyone implementing this kind of solution. Has something wrong?
I concluded that maybe the wrong thing is implementing a single-tx-solution without caring about being reusable by other contracts (for example exchanges). Taking this into account, what solution do you recommend to adopt?
What do you think about having the described whitelisted contract solution to minimize gas in the protocol and the permit function to allow other contracts to perform the transfer in a single transaction too?

Hope you can help me. Thank you in advance.


texts: Why can't I pass this function's value to a variable?

texts:
This question is related to question

How can I modify bytes32 result to uint?

I'm trying to pass result to variable AA, but AA's value is always 0. Function getTest1 shows the right answer, but I can't pass that answer to variable AA.

contract Test {
    bytes32 lastblockhashused;
    uint lastblocknumberused;
    uint AA;

    function test() {
        lastblocknumberused = (block.number-1)  ;
        lastblockhashused = block.blockhash(lastblocknumberused);
    }

    function getTest1() constant returns (uint) {
        return uint(lastblockhashused) & 0xfff;
    }

    function Test2() {
        AA=(uint(lastblockhashused) & 0xfff);
        return;
    }

    function getTest2AA() constant returns (uint) {
        return AA;
    }
}


texts:
How to run pruned node?
Is this possible with Ethereum?


texts: Possibilities of ERC721 image generation

texts: What image generation techniques could you suggest for a DApp game that utilizes ERC721? I know that CrypoKitties has a unique DNA sequence and different pieces of the sequence correspond to the different pieces of an image. Are there any other possibilities? Specifically, I am interested in the generation of a basketball player image. I am thinking if there is a way to implement this using a generative neural network or something more advanced so that the images will look could and the game will be as less centralized as possible.


texts:
I'm trying to use solc with no success.

I download solc with npm install solc but when I run solc --version the console output is:

command not found.

If I list packages npm list I'm able to see solc@0.3.5.

What's wrong?


texts: Is there a 'default' gas price and does it change when price of ether relative to fiat rises?

texts:
I understand how gas pricing works, so that is not my question.

My question is, as the price of ether relative to fiat (US $) rises, does the 'default' gas price lower (if there is such a thing as the default gas price)?

In other words, three months ago, when ether was priced at $7.50 US$ and a transaction cost X gas (which would translate to Y dollars), would that same transaction cost twice as much today (if ether is at $15.00 US).

I understand that I could send less gas, but that is not the same thing as the default sent gas lowering.


texts: Error: you must provide the json interface of the contract when instantiating a contract object

texts:
That's the error that occurs when I try to test my contract.

Can someone tell me what the problem is?

That's the code for the test:

const assert = require('assert');
const fs = require('fs');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());

const compiledFactory = fs.readFileSync('./ethereum/build/LotteriaFactory.json', 'utf8');
const compiledLotteria = fs.readFileSync('./ethereum/build/Lotteria.json', 'utf8');

let accounts;
let factory;
let lotteriaAddress;
let lotteria;

beforeEach(async () => {
  accounts = await web3.eth.getAccounts();

  factory = await new web3.eth.Contract(JSON.parse(compiledFactory).interface)
  .deploy({ data: (compiledFactory).bytecode })
  .send({ from: accounts[0], gas: '1000000' });

  await factory.methods.createNew('5').send({
    from: accounts[0], //manager
    gas: '1000000'
  });

  const addresses = await factory.methods.active().call();
  lotteriaAddress = addresses[0]; //[LotteriaFactory]

   lotteria = new web3.eth.Contract(
     JSON.parse(compiledFactory).interface,
     lotteriaAddress
   );
});

describe('Lotteria', () => {
  it('deploy a factory and a lottery', () => {
    assert.ok(factory.options.address);
    assert.ok(lotteria.options.address);
  });
});


texts:
I am setting up a private ethereum network (which I have done before), then I noticed that the flags have changed on geth as well as the removal of the genesis flag all together.

I changed the flags accordingly to what is below but when it goes to load up I only get the following message without the console starting up properly.

geth init ./UTSGenesis.json networkid "1100" maxpeers 20 port 3000 console

I0816 09:34:47.826895 ethdb/database.go:82] Allotted 16MB cache and 16
file handles to /home/james/.ethereum/chaindata
I0816 09:34:47.894232 core/genesis.go:92] Genesis block already in
chain. Writing canonical number
I0816 09:34:47.894507 cmd/geth/main.go:300] successfully wrote genesis
block and/or chain rule set: f9deb7b6dc5fda52360cbab7f402b01ca4b76ff3112bdcce7f076d1b374d324c

As you can see, the console wont load up and it just quits out. What am I doing wrong?


texts:
I have read about smart contracts and I am left with some doubts. Every invocation of a function in smart contract is a transaction which costs some ether.A miner chooses a smart contract on blockchain to complete the transaction.My doubts are :

1) If we have many smart contracts written by many developers to serve same purpose in the  blockchain, who will decide that a particular smart contract is best one out of all ? How can miners choose that this smart contract has best logic and rules to be verified against or users tell to use a specific smart contract ?
Ex : If I wanted to verify my certificate using a smart contract, and there are many smart contracts to serve this purpose, which and how does miners choose only one of them to verify ?

2) Suppose, I have mapping data structure in solidity smart contract A and I stored some data say mapping(uint => string) vals and it is stored with 5 values till vals[4] . Now in another transaction , I wanted to access vals[3] or store a new value at another index from the same smart contract by creating a new transaction , is it feasible ?If so, how will miners choose same smart contract everytime ?

3) Can I create a private smart contract in ethereum ? Suppose a Govt institution wants to store its certificates in blockchain using some mapping data structure say mapping(stu_ID => Certificate_ID) and others can only read it or use the same mapping data structute to verify their certificate if it's fake or genuine ?Is it possible ?

4) Can I edit a smart contract in blockchain ?
Suppose I wanted to change some rules or logic of my own smart contract , can I do it ?

forgive me if queries are noobish.

Thank you.


texts:
Very new to Solidity.
Found a intellij plugin in repository, now wondering what is the best way to structure the project?
For example npm js projects usually have have src folder and node_modules then a public folder (compiled, transpiled, minified and built code ends up) or www folder. So what about when i want to code/create a contract for a token Is there any suggested structure to be followed? Best practice? Or should solidity files be stored where the app scr code is? I apologize if my questions are super silly
My understanding so far is that contracts are written once (token code) and the Dapp would use those/distribute/sell/offer ??? But that is very likely a wrong understanding. Any help is appreciated.


texts: I was wondering How does etherscan fetch the number of token holders from a smart contract?


texts: I have compiled test crowdsale smart contract with inheriting from other contracts( like TestToken is MintableToken). The main smart contract consists only of one file, where I described all inheritances, but after compilation, I received many compiled files. How I must to deploy they to network? Or I need to deploy only one smart contract, named "TestTokenCrowdsale"? With Truffle all seems good. But Mist proposes to me to select which smart contract I must to deploy. And i don't know how to be. Can someone help me?


texts: How can I return struct when function is called?

texts:
I'd like to return struct type User. However, when I tried the following getUser function, it returns an error. Is there any way that struct data would be returned from a function?

Contract

struct User{
    uint256 user_id;
    bytes32 name;
    bytes32 address;
    bytes32 birth_day;
}
mapping (uint256 => User) public users;

function getUser(uint256 user_id) constant returns (User) {
        return users[user_id];
}

Error

  client/lib/contracts/User.sol: Solidity errors: :125:58: Error: Expected type name
  function getUser(uint256 user_id) constant returns (struct User) {


texts: Where can I set the max/total supply of ether for a private ethereum blockchain?

texts: I have created a private ethereum based blockchain and I would like to set the max/total supply and not sure where to do this or how to do this during the genesis block creation.


texts: Trustlessness and Provability in DApp design

texts:
I am looking for suggestions or references on how to build proper trustlessness and provability into my DApps. These are DApp distinctives, but I find that thinking this through is like peeling back an onion.

What factors must be taken into account, and are there any factors that do not necessarily have to be addressed to be a credible DApp? Is provability accomplished just by the fact that the code is visible in the block chain using tools like ether.camp, or should a developer make more demonstrable provisions?

For example, I am contemplating a game contract that can be instantiated by human sponsors in the wild. Once launched, a new player of a given game instance would provide an entrance fee and compete for prizes. I presume the following must be clear:

How funds are trustlessly held and disbursed by code.
That game rules and play elements are contractually controlled.
That all parameters a sponsor can configure are visible along with how they
are set for a given game instance.

But how are things like the following ‘proven’ to be sufficiently ‘trustless’:

That a ‘bad actor’ sponsor cannot exploit a game instance somehow,
say exploiting aggregated player data that might not visible to
players.
That game physics/computations are true and unexploitable.
That the base contract code is beyond manipulation by a sponsor or
the original writer.

To summarize, what factors, principles, or references can anyone suggest for helping with good DApp design in the area of acceptable trustlessness and provability?

Thanks.


texts: Is it possible for 2 transactions from the same address to be mined in the same block?

texts: If I send my ETH from address 0xA, and then immediately send another one also from address 0xA, is it possible for the two to be mined in the same block? Or the second transaction must always be mined in later block?


texts: I got the error when I do 'truffle test' in Truffle tutorial that pet-shop-tutorial

texts:
I'm doing truffle tutorial the pet-shop-tutorial but when I typed truffle test in cmd, I got the error. Here is the error message.
I have no idea how I can fix it and where should I check.
Please help me and if you need to see some code or anything else, please let me know.


texts:
I am able to get gas price data as follows from some oracles (i.e., ethgasstation.info, etherscan.io):

{
   "fast":50.0,
   "fastest":200.0,
   "safeLow":10.0,
   "average":20.0,
   "block_time":13.942307692307692,
   "blockNum":7403346,
   "speed":0.7090284960673774,
   "safeLowWait":13.4,
   "avgWait":1.8,
   "fastWait":0.5,
   "fastestWait":0.5
}

Is there a way to get similar information (including any other gas info) directly from Geth?

From Geth documentation I tried some commands especially related to Gas Price Oracle Options and also the curl that throws errors as follows:

When I run geth with or without options, the results are as follows, probably they are the current network status.

I am new to this and pretty sure I am missing something! Any clue is appreciated.


texts: Testing contract functions with calls from hundreds of accounts

texts:
Do any of the available IDEs support calling functions from hundreds of accounts at once, or, should I write a contract that manages the accounts as contract accounts?
contract Test {

    uint quantity = 100;
    Account[] public accounts = new Account[](quantity);

    constructor() public {
        for(uint i = 0; i < quantity; i++) {
        accounts[i] = new Account();
        }
    }
}

contract Account {
    function testFunction1() public {}
    function testFunction2() public {}
    function testFunction3() public {}
}


texts:
I have Parity working remotely so that I can SSH to my Parity Host and load the UI from another computer. The chrome-extension however is not working...

In the Parity console window, I'm seeing this message over and over:

  Blocked connection from chrome-extension://himekenlppkgeaoeddcliojfddemadig using invalid token.

I'm forwarding ports 8180, 8545 and 8546 through the SSH tunnel in order to get my remote connection working. Is there something else I need to forward to get the chrome extension to work?

Thanks!


texts:
I created a contract with a User struct than contains an age, a first name, and a last name. The function getUser() should return this information for an inputted address. But when I call my getUser() function on an address that has already been set, I get the error:
Uncaught Error: Returned error: VM Exception while processing transaction: revert
Also when I call my countUsers() function it returns "BN { negative: 0, words: [ 7, <1 empty item> ], length: 1, red: null }", when it should just return a "7"
pragma solidity ^0.6.0;

import "./EtherTransfer00.sol";

contract UserAttributes is EtherTransfer00 {
    struct User {
        uint age;
        string fName;
        string lName;
    }

    constructor (address root) EtherTransfer00(root) public {}

    mapping (address => User) public users;
    address[] public userAccts;

    function setUser(address _address, uint _age, string memory _fName, string memory _lName) public {
        users[_address].age = _age;
        users[_address].fName = _fName;
        users[_address].lName = _lName;

        userAccts.push(_address);
    }

    function getUsers() view public returns(address[] memory) {
        return userAccts;
    }

    function getUser(address _address) public view returns (uint, string memory, string memory) {
        return (users[_address].age, users[_address].fName, users[_address].lName);
    }

    function countUsers() public view returns (uint count) {
        return userAccts.length;
    }


texts: I need help with a crowdfunding contract

texts:
This crowdfunding contract is far from complete, I'm still in the process of writing the code and testing each individual function. The approach that I have taken with the getRefund() function seems to work perfectly, however, I'm a little concerned about there being potential collisions as I have mapped all the investor's addresses to the amount of ETH sent to the contract. Is it possible for address A and address B to map to the same index within the mapping? If so, wouldn't this mean that if address A were to claim a refund, wouldn't address A also obtain the funds that were sent from address B?

pragma solidity ^0.4.0;

contract Crowdfunding {

    address private owner;

    mapping (address => uint) investors;

    //Constructor
    function Crowdfunding() {
        owner = msg.sender;
    }

    //Modifiers
    modifier investorsOnly {
        if(investors[msg.sender] == 0) throw;
        _;
    }

    //Events
    event PaymentReceived(uint Amount, address From, address To);
    event WithdrawalClaimed(uint Amount, address From);

    //Functions
    function() payable {
        investors[msg.sender] += msg.value;
        PaymentReceived(msg.value, msg.sender, this);
    }

    function withdrawFunds() {
        suicide(owner);
    }

    function getRefund() investorsOnly {
        uint amount = investors[msg.sender];
        investors[msg.sender] = 0;
        msg.sender.transfer(amount);
        WithdrawalClaimed(amount, msg.sender);
    }
}


texts:
I was syncing the blockchain using Geth and it stopped giving this message:
Failed to write block data to ancient store err="appending unexpected item: want 5704756, have 5704757"
I was using the command: Geth --cache 2048
Can someone explain why this happened? and how to fix it?


texts: Making web3.js work from node server code

texts:
I'm running a geth node on the testnet and trying to run web3.js method from my node server code.

var coinbase = web3.eth.coinbase;
console.log(coinbase);

However, I'm getting a provider not set or valid error. Who exactly is the provider here. Briefly, how do I bind my web3.js to my running geth client?


texts: running eth-net-intelligence-api throws "[eth] =✘= Web3 connection attempt #0 failed"

texts:
I am trying to run eth-netstart in my machine.

I run geth using this command line:

geth --datadir innofactory1/ --syncmode 'full' --port 30312 --rpc --ws --wsorigins "*" --rpccorsdomain '"*"' --rpcaddr 'localhost' --rpcport 8502 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://20c47b4a7bd6d8383f87c1c988e601c7aa27ba7177b25d57e00794d1917c0c992dc37b93dfdf54741633179fd9a96a34fc2687d606ad48e2015ef2d958f3f0fb@10.2.1.124:30310' --networkid 1515 --gasprice '0' --unlock '0x40ee4953da28c4db0f15d671cefc29724ce2b87a' --password innofactory1/password.txt --mine

and I configure the app.json like this:

[
  {
    "name"              : "node-app",
    "script"            : "app.js",
    "log_date_format"   : "YYYY-MM-DD HH:mm Z",
    "merge_logs"        : false,
    "watch"             : false,
    "max_restarts"      : 10,
    "exec_interpreter"  : "node",
    "exec_mode"         : "fork_mode",
    "env":
    {
      "NODE_ENV"        : "production",
      "RPC_HOST"        : "localhost",
      "RPC_PORT"        : "8502",
      "LISTENING_PORT"  : "30312",
      "INSTANCE_NAME"   : "",
      "CONTACT_DETAILS" : "",
      "WS_SERVER"       : "http://localhost:3000",
      "WS_SECRET"       : "secret",
      "VERBOSITY"       : 2
    }
  }
]

but when I run :

npm start app.json

I got this error:
[eth] =✘= Web3 connection attempt #0 failed


texts: Why are getters of public state variables not recognised by interfaces?

texts:
In code like the below, address public balance has an automatic getter function (as can be seen in the corresponding ABI).

However we need to redefine it to avoid the compiler complaining that Test does not fully implement ITest.

Any idea if this is a bug or a feature (and if so why)?

pragma solidity ^0.4.24;

interface ITest {
    function balance() external returns (address);
}

contract Test is ITest {
    address public balance;

    // Why is this function needed?
    function balance() public returns (address) {
        return balance;
    }
}


texts: Parity Kovan shows TX id but 0 balance in Smart Contract


texts: Updated: How to interact "directly" with smart contract via a micro-controller?

texts:
Assume we have a micro-controller and it collects a meta-data (ex. a payload as a string). How this micro-controller can interact "directly" with smart contract to write this data to the blockchain?

Must we use something like Oraclize? Since a smart contract cannot interact directly with an external source.

And also, do we need to install, "necessarily", a Geth or Parity client on this micro-controller?

Is there a practical / existing example for such a scenario?

From my point of view, this micro-controller can collect data and then by calling a function in smart contract (ex. writePayload()) writes data in the blockchain "without" using an oracle such as Oraclize.

Note: According to the comments on this question: Is it possible to call a function of smart contract "without" installing "Geth" or "Parity"? , isn't it easier to use infura as an existing node, instead of installing Geth or Parity ?


texts:
I'm drawing a blank on a simple thing.  I remember that I need to have 30303 open on tcp and udp for the listening and discovery.  And I seem to remember that you need 30304/udp open.

But I'm not finding anythink that confirms this.

Maybe it's 30301, and not 30304 that I have to open for udp?

Can someone remind me?


texts: If you know someone's ethereum address do you effectively know their balance?

texts: Let's say someone pays you, can't they figure out your balance since the ledger is exposed to the public?


texts: What are some resources someone new to this asset class and crytocurrencies can use to understand the language and terminology used in describing it?  Like any area of interest, understanding the terminology is both the barrier and the key to being involved in it.  Thank you.


texts: ETH transaction stuck perpetually pending

texts:
I have a ETH Wallet on myetherwallet.com that I have sent ETH to my coinbase account successfully many times before, but my last attempt yesterday to send all of my current wallet value to my coinbase ETH doesn't seem to be working. When I go to my ETH wallet on myetherwallet and try to send from myetherwallet.com, which is address 0x19973A4e9b5d841BBb97018b39EA6f2188Dbd04b to my coinbase ETH wallet, which is 0x5e212b287169673f37968E152c1Da68e888E61aA it says on etherscan that it is pending, but it has been doing that for almost a full day now and nearly every time I go and check it on etherscan, I noticed the timer resets too; which seems odd to me since past transactions I've done successfully have kept a running time from when I actually started the transaction instead of resetting nearly each time I view it...

https://etherscan.io/tx/0xb873a2f66e87127b3e27973c26edb0ab3524ec73b7fd618a1c0ec049f32078cf

My Google searches on this situation have been fruitless I have just not seen this happen before as every time I have done this in the past, the transaction started getting block confirmations right away and I received an email from coinbase that the transaction has started almost immediately and neither of these have happened yet this time and I'm a little concerned about this.

Any help and suggestions I could get on this would be appreciated.

-Thanks


texts: Getting error on refreshing page react dapp using drizzle?

texts:
I am working on a dapp, it is working fine but one problem I am facing and it stuck my development. Please solve this if anyone knows how to do this and may be I am missing something??
PROBLEM
when refreshing page it throws these errors:

Uncaught TypeError: Cannot read property 'contracts' of null.

Uncaught TypeError: Cannot destructure property 'transactions' of
'drizzleData.drizzleState' as it is null.

when I am creating components and rendering it, it works fine but as I refresh the page, it throws those errors...
CODE
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Drizzle } from "@drizzle/store";
import PetShop from "./contracts/PetShop.json";
import { DrizzleContext } from '@drizzle/react-plugin';
import App from './App';

const options = {
     contracts: [PetShop],
     web3: {
       fallback: {
         type: "ws",
         url: "ws://127.0.0.1:7545",
       },
     },
   };

   const drizzle = new Drizzle(options);
   console.log('in index: ', drizzle);

   ReactDOM.render(
    <React.StrictMode>
      <DrizzleContext.Provider drizzle={drizzle}>
          <App />
      </DrizzleContext.Provider>
    </React.StrictMode>,
    document.getElementById('root')
  );

App.js
import React, { useContext } from 'react';
import { DrizzleContext } from '@drizzle/react-plugin';
import { GeneratePet } from './components/GeneratePet';

const App = () => {
  console.log('in app drizzle context:', DrizzleContext);
  const drizzleData = useContext(DrizzleContext.Context);
  console.log('in app drizzle data:', drizzleData);

  if (!drizzleData.initialized)
"Drizzle Loading..."
;

  return (

Hello Dapp World

      <GeneratePet />

  )
}

export default App;

GeneratePet.js
import React, { useState, useContext } from 'react'
import { DrizzleContext } from '@drizzle/react-plugin';

export const GeneratePet = () => {
    const [stackId, setStackId] = useState(null);
    const drizzleData = useContext(DrizzleContext.Context);

    const [petName, setPetName] = useState('');
    const [contentHash, setContentHash] = useState('');
    const [petPrice, setPetPrice] = useState('');
    const [tokenURI, setTokenUri] = useState('');

    const txStatus = () => {
        console.log('generate pet:', drizzleData)
        const { transactions, transactionStack } = drizzleData.drizzleState;
        const txHash = transactionStack[stackId];

        if (!txHash) return null;
        return `Transaction status: ${transactions[txHash] && transactions[txHash].status}`;
    };

    const setValue = async (petName, contentHash, petPrice, tokenURI) => {
        const { drizzle, drizzleState } = drizzleData;
        const contract = drizzle.contracts.PetShop;

        const stackId = await contract.methods["generatePet"].cacheSend(petName, contentHash, petPrice, tokenURI, {
            from: drizzleState.accounts[0],
        });
        setStackId(stackId);
        };

        return (

                <input type='text' onChange={(e) => {setPetName(e.target.value)}} value={petName} placeholder='enter pet name' />

                <input type='text' onChange={(e) => {setContentHash(e.target.value)}} value={contentHash} placeholder='enter content hash' />

                <input type='text' onChange={(e) => {setPetPrice(e.target.value)}} value={petPrice} placeholder='enter pet price' />

                <input type='text' onChange={(e) => {setTokenUri(e.target.value)}} value={tokenURI} placeholder='enter pet uri' />

                <button onClick={() => {setValue(petName, contentHash, petPrice, tokenURI)}}>Generate New Pet</button>

{txStatus()}

    )
}


texts: There are two GPUs recognized as Nvidia-smi commends, and I have completed installing drivers and CUDA9, but as shown in the second picture, only one GPU is recognized and mined in the Ethminer. Somebody help me.


texts: How concatenate encodeWithSignature with another data type to external call?

texts: There are a abi.encodeWithSignature("foo((bytes))", info), but in addition to calling the function in another contract I want to send more data as an address to retrieve with msg.data, for example. It is possible?


texts:
I am trying to set up my first test ethereum application. I started with the full ethereum get which took 10 hours to sync and found I needed Ether. I am trying to model an idea. I used

 geth --datadir Simons-MacBook-Pro:documents New Folder With Items init Simons-MacBook-Pro:documents private testnet.json --networkid 3156 --nodiscover --maxpeers 0 console

to build a new testbed. But it is still going 30 minutes later. I am not sure what this command is doing and whether it is doing a full sync. I though my json file would limit the creation.


texts: is there any difference between a call from contract and web3js?

texts:
What is the difference between call made from a contract and web3. I was going through an example and in coments it was mentioned not to make a call from within the contract. Shouldnt calling from a contract and web3 equally expensive?

   This method MUST NEVER be called by smart contract code. First, it's
     fairly
    ///  expensive (it walks the entire Persons array looking for persons
    belonging to owner),
         ///  but it also returns a dynamic array, which is only supported
       for web3 calls, and
     ///  not contract-to-contract calls.
  function tokensOfOwner(address _owner) public view returns(uint256[]
     ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
    // Return an empty array
  return new uint256[](0);
} else {
  uint256[] memory result = new uint256[](tokenCount);
  uint256 totalPersons = totalSupply();
  uint256 resultIndex = 0;

  uint256 personId;
  for (personId = 0; personId <= totalPersons; personId++) {
    if (personIndexToOwner[personId] == _owner) {
      result[resultIndex] = personId;
      resultIndex++;
    }
  }
  return result;
}
}


texts:
I have created an ERC-20 token with basic functionalities and it works fine and as expected. Now I want to add require() for error handling for frozen accounts.

require(!frozenAccount[_from]);
require(!frozenAccount[_to]);

I am using above in my internal function but it gives me an error as below

I am new to solidity and programming. Plz help me with this.

Below is my complete code for internal function

 /**
 * Internal transfer, only can be called by this contract
 */
function _transfer(address _from, address _to, uint _value) internal {
    // Prevent transfer to 0x0 address. Use burn() instead
    require(_to != 0x0);
    // Check if the sender has enough
    require(balanceOf[_from] >= _value);
    // Check for overflows
    require(balanceOf[_to] + _value >= balanceOf[_to]);

    require(!frozenAccount[_from]);
    require(!frozenAccount[_to]);

     // Save this for an assertion in the future
    uint previousBalances = balanceOf[_from] + balanceOf[_to];
    // Subtract from the sender
    balanceOf[_from] -= _value;
    // Add the same to the recipient
    balanceOf[_to] += _value;
    emit Transfer(_from, _to, _value);
    // Asserts are used to use static analysis to find bugs in your code. They should never fail
    assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}

//Declared Variables at the contract beginning

contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 3;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;

// Constructor function

constructor (
    uint256 initialSupply,
    string tokenName,
    string tokenSymbol
) public {
    totalSupply = initialSupply * 10 ** uint256(decimals);  // Update total supply with the decimal amount
    balanceOf[msg.sender] = totalSupply;                // Give the creator all initial tokens
    name = tokenName;                                   // Set the name for display purposes
    symbol = tokenSymbol;                               // Set the symbol for display purposes
}

// declared frozen account

mapping (address => uint256) public frozenAccount;

Is this the right way ?


texts:
can A call approve B to spend token though A have no tokens in his account?
does function approve require to check balance of A?


texts: Remote geth node failing to retrieve past events

texts:
I have set up a remote geth node on AWS as a web3 provider for my DApp.

The geth node is initialized with the following command (for testnet) as a daemon service:

[Unit]
Description=Ethereum go client

[Service]
ExecStart=/usr/bin/geth --testnet --port 30311 --rpc --rpcport 8549 --rpcaddr 0.0.0.0 --rpccorsdomain "*" --rpcapi "eth,web3,net" --lightserv 25 --lightpeers 50

[Install]
WantedBy=default.target

I then fetch events with the following command, where fromBlock = contract creation block:

const getPastEvents = async (event, fromBlock, callback) => {
  const pastEvents = await event({}, { fromBlock, toBlock: 'latest' }).get();
  callback(pastEvents);
};

If I use the remote geth node as the web3 provider, it fetches the most recent of that event (e.g. LogEvent), but it doesn't fetch the whole history of events.

If I use a local geth node, it fetches all of the events.

I also tried a third party remote node, whose documentation said it was configured the same way, using the same geth command as I have above.  And that one manages to fetch all events also.

Let me know if anyone has any ideas on why my node set up is not retrieving the full events history. Thanks.


texts: What's the cause of low hashrate on Radeon RX 580 4GB?

texts:
I've just started mining Ethereum Classic with Sapphire Nitro+ Radeon RX 580 4GB and lolMiner. While some people have reported that the hashrate should be about 30 MH/s, on my system it doesn't go beyond 14 MH/s (as reported by lolMiner). So the question is: why?
The motherboard is very old. It's an ASUS Commando with 4GB of DDR2 RAM. I hoped that the transfer of data between the RAM and the GPU is minimum and, thus, the quite low speed of the memory bus doesn't affect the hashrate significantly. But now my doubts are stronger.
Other details:

OS is Windows 7 64bit (updates up to 2017 are installed).
The most recent AMD GPU driver is installed.
The system has only one graphics card, which is also used for display.
GPU-Z reports that "CPU clock = 1411 MHz", "Memory clock = 1750 MHz", "GPU Load = %100", "Dedicated Memory Used = 3936 MB", "Dynamic Memory Used = 217 MB", and "Memory Controller Load = %68".


texts:
Following this example: http://remix.readthedocs.io/en/latest/tutorial_mist.html

I'm trying to run mist via command line, but I get: command not found.

I can run geth console, how to do run mist command line? Is there another package I need to brew install / npm down ?

Thanks.


texts:
By default there are 24 confirmations but I am running a testnet with just 3 miners and I would like to change this number bucause it makes not sense to have 24. I have been checking transactionConfirmationBlocks on the following way:

const options = {
   transactionConfirmationBlocks: 3
}

var web3 = new Web3(new Web3.providers.WebsocketProvider(provider_string, options));

I am not getting errors, but when I make a transaction it is still making 24 confirmations. if I check the number of confirmations (web3.eth.transactionConfirmationBlocks) is still 24. What is the right way to set the number of confirmations?


texts: Do we need to spend Gas to move ERC20 token inside a bip32/HD wallet

texts: I just wondering to know in order to move erc20 token inside a bip32/HD wallet from child to parent to we need to spend any gas? (example: imagine I made a HD wallet which supporting ERC20 tokens and my HD wallet structure has a parent and 10  child, if one of child receive few ERC20 token from an ICO  under his/her public key  and want to move/transfer it to parent public key does he needs to spend any Gas in ETH or same token ?


texts: I would like to add strings into bytes32. What is the maximum number of letters bytes32 can have?


texts:
my question specially is that how this lottery opens and closes.
is there any admin that have to initiate states of the lottery manually?
i saw their smart contract and i think there might be an admin
i want to know that is that a automatic method that works without any admins? or its mandatory to have an admin to call that functions to initiate or change states or smthng?
thanks in advance


texts: Error when deploying contract to Mainnet but not Testnet

texts:
I built and have tested a contract on the Ropsten testnet but when I tried to deploy to the mainnet the transaction was reverted. not sure what the reasoning was I tried not spending all that much to deploy it so not sure if that was cause or not.
Using Remix IDE for deployment.
Transaction ID: 0x47bbe74d09559298b973348b7c41b4363977ccaea5ad33ced5904c16f5fffaeb
https://etherscan.io/tx/0x47bbe74d09559298b973348b7c41b4363977ccaea5ad33ced5904c16f5fffaeb
Fail with:

A Status code indicating if the top-level call succeeded or failed
(applicable for Post BYZANTIUM blocks only)


texts: What are sha3Uncles and why are they mostly same for all blocks

texts:
I was looking at sha3Uncles in my chain and found it to be constant throughout. After looking at the example response to JSON RPC requests, I found the same value:

0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347

Moreover, when I traversed etherscan, I found this value to remain more or less constant throughout blocks.

Question:

What are sha3uncles? And why do they mostly have a constant value?

An existing similar question what is Sha3Uncles? does not explain clearly as to how this particular hash was calculated, or where it came from?


texts: Contract Call Web3 Error could not unlock signer account

texts:
I am using react for interacting with my HelloWorld Smart Contract:

var ETHEREUM_CLIENT = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
var helloworldcontractABI = <the json string>

var hellowordlcontractAddress = '0xffe299f7b09f53d716a0898b4454b3c53fb5c2e1'
var helloworldcontract =  ETHEREUM_CLIENT.eth.contract(helloworldcontractABI).at(hellowordlcontractAddress)

In my contract i have a method getValue - which returns an integer

When i call the following lines i get some errors:

  var value
  console.log(value)
  value = helloworldcontract.getValue()
  console.log(value)

Uncaught Error: Error: could not unlock signer account

What is here the problem? When i try the same scenario in truffle it works fine - so the contract is ok


texts: Do events only work on an instance of a contract?

texts: Does a contract address have to specified to watch for an event?  Or, can I register an event handler for every time contracts of a certain type are transacted?


texts:
Just wondering if there is a time limit that has to be reached between transfers from Coinbase to MyEtherWallet. Trying to send 0.1 ETH from Coinbase and I get to enter the destination address, the sending message pops up but then closes again without completing. Last transaction went through just over an hour ago. Something to do with transaction hashes?

Edit: I'm an eejit, the transaction fee was pushing me over the amount of ETH I had on Coinbase. Lesson learned.


texts: How to detect what instruction caused "truffle test" to result in "invalid opcode" error?

texts:
I wrote a test for my contract and it returns invalid opcode as a result.
Full output:

1) Contract: FPCoin1 One can purchase tokens for ether:
 Error: VM Exception while processing transaction: invalid opcode
  at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:37312:16)
  at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:220420:36
  at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:204149:9
  at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:205574:13)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:73069:18)
  at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:73359:12)
  at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:73514:12)
  at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:73474:24)

It tells me no particular information which instruction or line caused the problem.
Is it possible to actually see what went wrong?


texts: Integration between Multiple Enterprise Blockchains (Hyperledger, Quorum, Corda) -- Through the use of Ethereum oracles?

texts:
Many organisations are running proof of concepts with different enterprise blockchain technologies -- Quorum, Corda and Hyperledger.

Understand that most efficiency gains can be unlocked only when everyone adopts a single blockchain -- is this contestable?

If history is of any guide at all, the future will be one of multiple blockchain technologies.

Reconciliation across multiple systems is streamlined via the use of blockchain. If one needs to reconcile between 2 blockchain nodes (say, one Quorum node and another hyperledger node), the efficiency gains are lost.

Hyperledger Node will make an REST/JSON API call to Quorum and vice versa. How then can one reconcile both transactions on each ledgers which reside on different networks? Should one perform this integration via Oracles or?


texts: Just synced a node, but want to use docker instead, can I moved synced db into container?

texts:
I just synced a node using geth fastsync and it took several days.

But I just decided I want to use this computer's resources differently and run my ethereum environment from a docker container

I like the prebuilt ones, but even if I compose an environment myself, is there any way to prevent resyncing from scratch? Perhaps a way to copy geth's parsed blocks and states into it?


texts: How to immediately close ethclient.Client RPC sockets so they don't linger in TIME_WAIT status on server?

texts:
My server is running out of available sockets while I am using goroutines (limited to 100 concurrently) because once a goroutine finishes the ethclient.Client socket stays open in TIME_WAIT status for too long, instead of closing immediately after it has returned the required data, as is mentioned in this issue comment.

After about 30000 sockets are sitting in TIME_WAIT then my app fails. Sockets are closed faster on macOS 10.13 than on Ubuntu 14.04 it seems, as the problem is less common on a Mac.

The golang net package allows you to set SO_LINGER to 0 via setLinger but I don't see a similar option for ethclient.Client but maybe I am missing something


texts: Access the result of _; inside a modifier to change state machine common pattern

texts:
I'm implementing the State Machine for a specific case where the nextSate() depends on the execution of the method, as realistic State Machine. The code follows:
contract Transaction {
enum C_facts {
    Inital,
    Requested,
    Promissed,
    Declined,
    Declared,
    Accepted,
    Rejected
}
C_facts public c_fact = C_facts.Inital;
modifier atCFact(C_facts _c_fact) {
    require(
        c_fact == _c_fact,
        "Function cannot be called at this time."
    );
    _;
}
function nextCFact() internal {
    c_fact = C_facts(uint(c_fact) + 1);
}
modifier transitionNext()
{
    _;
    nextStage();
}

Now I want to apply the transitionNext() to a function that depending on its execution it is set for different states. Do you know how could I achieve this? I need a way to get the success or unsuccess of the execution at the _; of transitionNext() but I'm not sure how to do it...


texts: Can't connect to GETH node on the network

texts:
I run a light node on a windows 10 machine on my network with the command:
geth --syncmode="light" --cache=4096 -http --http.port 8545 --http.corsdomain "*" -http.api "eth,web3,personal" console

The windows 10 machine has the local IP address of 192.168.1.28
When I run a web3 request through the windows machine using the endpoint: http://localhost:8545 it works perfectly. Once I run the same request on another machine on the network using the endpoint http://192.168.1.28:8545 the request won't go through.
Any way I can resolve this issue?
Thanks for the help


texts: Determining value of variable: How to check the value of Log in the new version of Remix IDE

texts:
I am getting problem in understanding the working of the latest version of Remix IDE. I want to see the value of variable (i.e. Val). I am trying to run the following code:
   pragma solidity ^0.5.1;
   contract Test{
      uint8 Val = 0;
      event LogFunction(uint8);
      function testFunc() public returns (uint8) {
         Val++;
         emit LogFunction(Val);
         return Val;
      }
  }

I am getting following output when I click on deploy:
When I click on the deploy button I am getting following output:

creation of Test pending...    [vm] from: 0x5B3...eddC4to:
Test.(constructor)value: 0 weidata: 0x608...10032logs: 0hash:
0x711...faece

I have chosen Ether as the value but why I am getting wei data above?
When I click on the green  tick sign, I am getting the following:

status    true Transaction mined and execution succeed  transaction
hash  0x711e1fd9cd945e3d218ff11c00db230105ccad6c7daa1690447b0fe3174faece
contract address  0x0fC5025C764cE34df352757e82f7B5c4Df39A836
from  0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
to    Test.(constructor)   gas    3000000 gas   transaction cost  131940 gas
execution cost    57372 gas
hash  0x711e1fd9cd945e3d218ff11c00db230105ccad6c7daa1690447b0fe3174faece
input 0x608...10032   decoded input   {}   decoded output  -   logs   []
value 0 wei

Please guide me how to check the logs? Why the value is '0', even though I am incrementing?
Zulfi.


texts: Mining is taking too much cpu memory( i.e more than 100% of one core), how to reduce it?

texts:
What I have
 1. I have step up four private blockchain of ethereum.
 2. when i start mining on one core( miner.start(1) ) , it is taking too much cpu memory( i.e 100% or more)

What I Want
 1. Mining should take less memory
 2. I have to run four instance of geth on a system, connected to each other( in a peer)


texts: C# how to compute Keccak256 to match Solidity?

texts:
I have a simple Solidity function as below:

function testKeccak(uint8[] buffer) public pure returns (bytes32) {
    return keccak256(abi.encodePacked(buffer));
}

Testing the keccak256 hash using library from: https://github.com/modulexcite/CEX

But they yield different results.

var In = "54686973206973206A75737420612074657374"; // Assume this is a byte[], otherwise the code won't compile
Web3 w = new Web3("http://localhost:8545/");
Contract c = w.Eth.GetContract("My ABI", " My Contract Address");
var r = c.GetFunction("testKeccak").CallAsync<byte[]>(In).Result;

//Expected = 68D0D86DF8DCA7ABDAD4DA5986F7E33FA7637EE85775A64AE965E10E3841923E
//Received = FC3B317A9FB7A02E6FF7A1839EEA04A21C30D9CD15B3414FA7431F09DEEC9D9D

May I know if there is any C# library out there which can get the correct Keccak256 hash when compared to Solidity?


texts:
what are the pros and cons of each of these ethereum clients: geth, parity, infura?
I want to compare them from a theoretical point of view


texts:
window.getProjectId = function() {
Bidding.deployed().then(function(instance) {
  instance.projectReturn({}, function(error,result) {
    if(!error)
      var pid = (result.args.projectId);
       getPro(pid); });
   })

}

In the above code when the getprojectID function is called for first time the event projectReturn is triggered for one time when called second time the event is also triggered for two times like this it is going  on increasing can anybody help on this. I am using truffle and testprc


texts: Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"

texts:
I can't work out how to modify this...When I change pure to view I get a different error:

function balanceOf(address _owner) public pure returns (uint256 balance) {
    return balances[_owner];
}

changing to view gives this error:

Overriding function changes state mutability from "pure" to "view".
    function balanceOf(address _owner) public view returns (uint256 balance) {
    ^
Spanning multiple lines.


texts: Error: filter not found - when watching for latest blocks

texts:
Found block 3258499
Found block 3258502
Found block 3258587
Error: filter not found
    at Object.InvalidResponse (/home/ubuntu/node_modules/web3/lib/web3/errors.js:35:16)
    at /home/ubuntu/node_modules/web3/lib/web3/requestmanager.js:255:40
    at Array.filter (native)
    at /home/ubuntu/node_modules/web3/lib/web3/requestmanager.js:252:12
    at XMLHttpRequest.request.onreadystatechange (/home/ubuntu/node_modules/web3/lib/web3/httpprovider.js:118:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/ubuntu/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/home/ubuntu/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/home/ubuntu/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/home/ubuntu/node_modules/xhr2/lib/xhr2.js:469:24)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:186:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

I receive the above error when using this filter. Note that it works successfully for several blocks before failing

var filter = web3.eth.filter({toBlock:'latest', address: '0xexampleaddress', 'topics':[web3.sha3('Trade(uint256,address,uint256,address)')]});

filter.watch(function(error, logs) {
  console.log('Found block' + logs.blockNumber);
}


texts: Debugging amount of funds needed to deploy +network state unknown error on Ropsten

texts:
Wrote a simple contract. Attempting to deploy to testnet and get error.

eth --testnet --fast --rpc --rpcapi eth,net,web3,personal

truffle.js config:

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },
    ropsten: {
      network_id: 3,
      host: "127.0.0.1",
      port: 8545,
      from: "0xd060fa165f3ff5f506c5391aa07bc57599d053c7",
      gas: 4000000
    }
  }
};

then cd into my directory,

truffle migrate --network ropsten

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... undefined
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: insufficient funds for gas * price + value

How do I debug what the delta between my funds & required funds for deployment is?

Why is "network status unknown" showing?

EDIT: tried with

geth --rpc --rpcapi eth,net,web3,personal --testnet --fast --bootnodes "enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303" console

INFO [01-29|17:52:23] Starting peer-to-peer node               instance=Geth/v1.7.2-stable/darwin-amd64/go1.9.2
INFO [01-29|17:52:23] Allocated cache and file handles         database=/Users/quantum/Library/Ethereum/testnet/geth/chaindata cache=128 handles=1024
INFO [01-29|17:52:23] Initialised chain configuration          config="{ChainID: 3 Homestead: 0 DAO: <nil> DAOSupport: true EIP150: 0 EIP155: 10 EIP158: 10 Byzantium: 1700000 Engine: ethash}"
INFO [01-29|17:52:23] Disk storage enabled for ethash caches   dir=/Users/quantum/Library/Ethereum/testnet/geth/ethash count=3
INFO [01-29|17:52:23] Disk storage enabled for ethash DAGs     dir=/Users/quantum/.ethash                              count=2
INFO [01-29|17:52:23] Initialising Ethereum protocol           versions="[63 62]" network=3
INFO [01-29|17:52:23] Loaded most recent local header          number=0 hash=419410…ca4a2d td=1048576
INFO [01-29|17:52:23] Loaded most recent local full block      number=0 hash=419410…ca4a2d td=1048576
INFO [01-29|17:52:23] Loaded most recent local fast block      number=0 hash=419410…ca4a2d td=1048576
INFO [01-29|17:52:23] Loaded local transaction journal         transactions=0 dropped=0
INFO [01-29|17:52:23] Regenerated local transaction journal    transactions=0 accounts=0
INFO [01-29|17:52:23] Starting P2P networking
INFO [01-29|17:52:25] UDP listener up                          self=enode://97d8bd87fff8bce0721e6ac15e967ac36f0b238bf44605db363c1fd73ef4860edb0c22f68da3c476d456624f5f3b9da29205f10a5c058f66c5d607282b208544@[::]:30303
INFO [01-29|17:52:25] RLPx listener up                         self=enode://97d8bd87fff8bce0721e6ac15e967ac36f0b238bf44605db363c1fd73ef4860edb0c22f68da3c476d456624f5f3b9da29205f10a5c058f66c5d607282b208544@[::]:30303
INFO [01-29|17:52:25] IPC endpoint opened: /Users/quantum/Library/Ethereum/testnet/geth.ipc
INFO [01-29|17:52:25] HTTP endpoint opened: http://127.0.0.1:8545


texts: How to check transferfrom and burnfrom function in remix?

texts:
I am creating simple ERC20 token which involves functions like

transfer
burn
totalsupply
transferFrom
burnFrom

How can I check function transferFrom and burnFrom from remix browser because it involves approve and allowance and whenever I run these function I am getting error .
Here is my contract

```

pragma solidity ^ 0.4.21;

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 MyFirsttoken is ERC20Interface {

    address public owner;
    uint256 totalsupply;
    string tokenname;
    string tokensymbol;
    uint8 decimal;

    event Burn(address,uint256 amount);

    mapping(address=>uint256)public balances;
    mapping(address =>mapping(address=>uint256)) internal allowed;

    function MyFirsttoken(uint256 tokensupply, string symbol, string name){

    owner = msg.sender;
    totalsupply = tokensupply;
    tokenname =   name;
    tokensymbol = symbol;
    balances[owner] = totalsupply;
    }

    function totalSupply() public constant returns(uint){
        return totalsupply;
    }

    function balanceOf(address tokenholder)public constant returns(uint256 balance){
        return balances[tokenholder];
    }

    function transfer(address tos,uint amount) public returns(bool)  {
    require(amount <= balances[msg.sender]);
    balances[msg.sender]-= amount;
    balances[tos] +=amount;
    emit Transfer(msg.sender,tos,amount);
    }

    function transferFrom(address from, address to ,uint256 tokens)public returns (bool success){
        uint256 allowedbalance = allowance(from ,to);
        require(tokens <= allowedbalance);
        balances[from] -= tokens;
        balances[to] += tokens;
        emit Transfer(from,to,tokens);
    }

    function allowance(address tokenOwner, address spender) public constant returns(uint){
        return allowed[tokenOwner][spender];
    }

    function approve(address spender,uint256 amount) public returns(bool success){
        allowed[msg.sender][spender]=amount;
        emit Approval(msg.sender,spender,amount);
    }

    function burnabletoken(uint256 burnableamount)returns (bool){
        require(msg.sender == owner);
        require(balances[msg.sender]>=burnableamount);
        balances[msg.sender] -= burnableamount ;
        totalsupply -= burnableamount;
        emit Burn(msg.sender,burnableamount);

    }

    function burnfrom(address from , uint256 burnableamount){

        require(balances[from] >= burnableamount);
        require(burnableamount <= allowed[from][msg.sender]);
        allowed[from][msg.sender] -= burnableamount;
        balances[from] -= burnableamount;
        totalsupply -= burnableamount;
        emit Burn(from,burnableamount);

    }

}

```


texts: How can I pack two int16 into a single byte32?

texts:
I have a contract that makes use of cartesian coordinates. My initial thought is to map a single location (x,y) to a value/struct. I would like to define any given pair of coordinates by a single byte32 that can be converted back into coordinates. Ex:

int16 x, int16 y;
byte32 key = coordinatesToBytes32(x, y);

and vise-versa:

[x, y] = bytes32ToCoordinates(key);

After jumping into solc@^0.5.0 I discovered you can no longer explicitly  convert between these types which made it difficult for me to cast, mask, shift, and run bitwise operations. For reference, here is where I made it to (note the solidity version):

pragma solidity ^0.4.17;

contract CoordinateUtils {
    function coordinatesToBytes32(int16 x, int16 y) internal pure returns(bytes32) {
        return (bytes32(x) << 16 & 0xFFFFFFFF) | bytes16(y);  // left shift extends negative so we mask out
    }
    function bytes32ToCoordinates(bytes32 b) internal pure returns(int16 x, int16 y) {
        return (int16(b >> 16), int16(b));
    }
}

Also, I am open to other suggestions on the storage of cartesian related values if this seems inefficient.


texts: How you can have real-time database modifications if transactions require acceptance by all others

texts: I'm trying to understand the current implementation of smart contracts and transactions and am wondering about real-time behavior. I read that it can take up to 10 minutes for a transaction to become part of a block, and read here that "you have to create a so-called transaction which has to be accepted by all others". So I don't see how you could have real-time transactions and built say a Todo list application where each time you created a todo it would instantly save to the database and upon refresh would be there, and it would charge the user per todo (let's say) immediately. Wondering if this is possible, or if it's been considered, or why it's not possible, or how you would handle a situation like this.


texts: Why is "modifier lock()" needed in UniswapV2Pair smart contract?

texts:
In UniswapV2Pair.sol(https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol), modifier lock() seems to be used to get lock and release lock. And it is used in almost all the external functions of UniswapV2Pair.sol.
    uint private unlocked = 1;
    modifier lock() {
        require(unlocked == 1, 'UniswapV2: LOCKED');
        unlocked = 0;
        _;
        unlocked = 1;
    }

But I don't know why lock is needed in solidity smart contract. Is it used to execute function in sequence , just like "synchronized" in java? In my understanding, in the context of Ethereum, transactions in a block are executed one by one, which means that they are executed in sequence natively. Since they are impossible to be executed in parallel, why lock is needed?
Hopefully some expert can help me understand this. Thanks in advance.


texts: I have one little question. Suppose I have private key of user in ionic app. Is this enough to make transactions using infura API and web3?


texts:
Is it possible to truffle migrate only one specific file?

I found this on the internet: https://github.com/trufflesuite/truffle-migrate/issues/23

but truffle migrate -from 2 starts to migrate from file 2_... and goes then to the next.
My goal is to migrate only file 2_...


texts: Minimum transaction value on token in solidity

texts:
Is there a way of setting a minimum transaction value on token in solidity?
The point is that for transaction (purchase) to happen, the value has to be of some equivalent of ETH (say 0.2). Always. Smaller transactions should not happen. Is that possible somehow?


texts: How does truffle get the address of the contract only by it's name?

texts:
When executing the command

truffle(develop)> let instance = await MetaCoin.deployed()

How does truffle get the address of the contract that is deployed ?


texts: withdraw Ether from an exchange to a smart contract...!

texts:
ralated to this topic Can I withdraw Ether from exchanges to a contract wallet?
I have a question that how exchange understand which address is a contract and how doesn't pay gas more than 21000...?


texts:
I've installed truffle and related software on my office PC. I've set the proxy server for node.js.

The truffle init got the following error. Is it proxy issue?

H:\work\eth> truffle.cmd init
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at exports._errnoException (util.js:1018:11)
    at TLSWrap.onread (net.js:568:26)


texts: Blockchain Hark Fork System Impact - risk assessment and mitigation plan

texts:
I am exploring on System Impact risk assessment and mitigation plan during a block chain (ex –Ethereum) hard fork.

1) What happens to the deployed smart contracts when a hard fork occurs?

2) Does complete state data (along system event log data) also available on the newly forked chain?

3) If yes, do we also get the complete state of each smart contract on Both Chain?

4) If someone decides to continue to with existing chain, Do they / their users require performing any additional steps before continuing with their dapp?

5) If someone decides to continue with New Chain, what is expected from him and his users?

Answer: I believe, Yes their users should connect to new Chain (like we do using Metamask). any other pointers?

6) What are the known risks for Dapps systems running Ethereum as backend infrastructure in any of such hard fork?

6.1) Is there any good guide for mitigation plan on these risks (For production ready app)?

7) During BTC to BCH OR ETH to ETC (or any other famous harkfork), did we observe any such downtime or any other risk?

Regards
Dev


texts:
I followed this answer to connect Mist to testrpc: https://ethereum.stackexchange.com/a/10109/5995

The command to start Mist with arguments doesn't work on OS X so I tried this instead, which doesn't work either (Mist opens on testnet): open -a /Applications/Mist.app/Contents/MacOS/Mist --args rpc localhost:8545

How can I get this working?


texts: It is possible to export Tx Hash to a .txt file?

texts:
As above: It is possible to export a Tx Hash to a .txt file ?

For Example :
I'm using Geth Java console, I make a Transaction from my Account receving

  "0x123456789"

It is possible to send "0x123456789" to txhash.txt ?

Further Informations:
I usually started with

geth --datadir C:\Users\BulldogBud\AppData\Roaming\Ethereum\testnet\chaindata --networkid 3 console 2>>log.txt

then

web3.personal.unlockAccount("0x9876", "mypassword", 24*3600 ) In order to keep the account open from Java console without all the "Sync messages". In this way after the web3.personal.sendTransaction() command, how can I pass the Tx Hash out of the Java console?

Thank you in advance!


texts: Setup Parity PoA network compatible with truffle framework deployment mechanizm

texts:
The question from the title kind of wraps around the real problem but it is actually what I'm having trouble making work. I'm trying to setup production PoA network so using all the flags made for development purpose will not work for me.

The exact problem I'm having is described in this question with zero answers. Once I try truffle deploy it hangs forever. I've tried setting up local network step by step fallowing this tutorial from official parity wiki and also tried this pre-setuped docker-compose solution and it behaves the same. I kind of understand that there is (or was) something called Trusted Signer but I don't understand where it fits in Parity operated ecosystem...is it on node, separate entity or whatever it is? I noticed it is referenced together with parity-ui which has been abandoned by parity team. Clarification on trusted signer topic would be much appreciated!

I kind of narrowed down this problem to the JSON RPC function truffle uses when deploying. It uses eth_sendTransaction which creates the problem. When I copy the whole RPC call and use personal_sendTransaction and provide password as last parameter, transaction is mined.

Sorry for the block of text, hope someone knows how to solve this, if it's even possible.

So is there a way, node configuration or something, to make this work?


texts: Creating add transaction and seal block from mix localhost on button click

texts:
When we open mix we have 3 windows. The first shows contract, the second shows the front end and the third shows the blocks and transaction while we create a new block or approve transaction.

How can I create a buttons in the second window in order that, when clicking on "add", transaction blocks are added and transaction are approved without the need to go in the third window to click on the plus sign and manually approve pending transaction ?


texts: How to check when erc20 token was received in certain address

texts: i am hosting a node and fully sync it. how i can call its api endpoints to figure out when DGX is received in certain wallet addresses.


texts: Using other then uint256 number types as mapping keys

texts:
Working on contract optimization and found that I actually do not need use uint256 everywhere. Mostly I am using uint32 or even uint16, even payment amount could be packed into 32 bits with reasonable limitations.

But generally I see that I cannot do anything with mapping keys - despite of data size, absolutely any uint less then 256 bits makes insert operation more expensive then with uint256. For instance, insertion to the following mappings cause next gas usage:

mapping (uint => uint) vals;       // Insertion cost 25669
mapping (uint64 => uint) vals64;   // Insertion cost 26061
mapping (uint12 => uint) vals;     // Insertion cost 25885

Why this happens?

Does it makes sense at least to change data types in structs so make it fit into 256 bits?

UPD: Yeah, it looks like INSERT (SSTORE) operation always reserve 256 bits for inserted data type. But if data stored in arrays decreasing its size gives small benefit:

contract A4Contract {
    uint256[] vals;
    uint64[] vals64;

    // 1: 40544
    // 2: 25544
    // 3: 25544
    function insert(uint256 value) public {
        vals.push(value);
    }

    // 1: 40820 creates array, reserves 256 bits chunk and insert 64 bits
    // 2: 10870 - insert 64 bits into already reserved 256 bits
    // 3: 10870 - insert 64 bits into already reserved 256 bits
    // 4: 10870 - insert 64 bits into already reserved 256 bits
    // 5: 25820 reserves next 256 bits
    // 6: 10870 - insert 64 bits into already reserved 256 bits
    // 7: 10870 - insert 64 bits into already reserved 256 bits
    // 8: 10870 - insert 64 bits into already reserved 256 bits
    // 9: 25820 reserves next 256 bits
    function insert64(uint64 value) public {
        vals64.push(value);
    }
}

So, finally mapping is suitable only to hold something by address or something packed into uint256 and accessed with full set of packed data (to re-create key and get value from mapping).


texts: tokenInstance.balanceOf is not a function

texts:
It happen when use truffle test,

and here my DappTokenSale file:

var DappToken = artifacts.require('./DappToken.sol');
var DappTokenSale = artifacts.require('./DappTokenSale.sol');

contract('DappTokenSale', function(accounts) {
    var tokenInstance;
    var tokenSaleInstance;
    var admin = accounts[0];
    var buyer = accounts[1];
    var tokenPrice = 1000000000000000;
    var tokensAvailable = 750000;
    var numberOfTokens;

    it('Initializes the contract with the correct values', function() {
        return DappTokenSale.deployed().then(function(instance) {
            tokenSaleInstance = instance;
            return tokenSaleInstance.address
        }).then(function(address) {
            assert.notEqual(address, 0x0, "has contract address");
            return tokenSaleInstance.tokenContract();
        }).then(function(address) {
            assert.notEqual(address, 0x0, "has token contract address");
            return tokenSaleInstance.tokenPrice();
        }).then(function(price) {
            assert.equal(price, tokenPrice, 'token price is correct');
        });
    });

    it('facilitates token buying', function(){
        return DappToken.deployed().then(function(instance) {
            tokenInstance = instance;
            return DappTokenSale.deployed();
        }).then(function(instance){
            tokenSaleInstance = instance;
            return tokenInstance.transfer(tokenSaleInstance.address, tokensAvailable, {from: admin})
        }).then(function(receipt){
            numberOfTokens = 10;
            return tokenSaleInstance.buyTokens(numberOfTokens, { from: buyer, value: numberOfTokens*tokenPrice})
        }).then(function(receipt) {
            assert.equal(receipt.logs.length, 1, 'triggers one event');
            assert.equal(receipt.logs[0].event, 'Sell', 'should be the "Sell" event');
            assert.equal(receipt.logs[0].args._buyer, buyer, 'logs the account that purchased the tokens');
            assert.equal(receipt.logs[0].args._amount, numberOfTokens, 'logs the number of tokens purchased');
            return tokenSaleInstance.tokensSold();
        }).then(function(amount){
            assert.equal(amount.toNumber(), numberOfTokens, 'increments the number of tokens sold');
            return tokenInstance.balanceOf(buyer);
        }).then(function(balance) {
            assert.equal(balance.toNumber(), numberOfTokens);
            return tokenInstance.balanceOf(tokenSaleInstance.address);
        }).then(function(balance){
            assert.equal(balance.toNumber(), tokensAvailable - numberOfTokens);
            return tokenSaleInstance.buyTokens(numberOfTokens, { from: buyer, value: 1});
        }).then(assert.fail).catch(function(error) {
            assert(error.message.indexOf('revert') >= 0, 'msg.value must equal number of tokens in wei')
            return tokenSaleInstance.buyTokens(800000, {from: buyer, value: numberOfTokens*tokenPrice})
        }).then(assert.fail).catch(function(error) {
            assert(error.message.indexOf('revert') >= 0, 'cannot purchased more than available token');
        });
    });

    it('end token sale', function() {
        return DappTokenSale.deployed().then(function(instance){
            tokenInstance = instance;
            return DappTokenSale.deployed();
        }).then(function(instance){
            tokenSaleInstance = instance;
            return tokenSaleInstance.endSale({from:buyer });
        }).then(assert.fail).catch(function(error){
            assert(error.message.indexOf('revert' >= 0, 'must be admin to end sale'));
            return tokenSaleInstance.endSale({from: admin});
        }).then(function(receipt){
            return tokenInstance.balanceOf(admin);
        }).then(function(balance){
            assert.equal(balance.toNumber(), 999990, 'return all unsold dapp tokens to admin')
            return tokenSaleInstance.tokenPrice();
        }).then(function(price) {
            assert.equal(price.toNumber(), 0,'token price was reset')
        });
    });
    });