texts: net.peerCount is zero: Two miners are not connected

texts:
I'm trying to build a local private blockchain of Ethereum in my own PC using Geth v1.9.15-stable-0f77f34b. I have installed Geth in a virtual machine with Ubuntu 18.04 OS using VMware Workstation Pro. I want to create two miners inside the virtual machine. Each runs in different terminal, I have follow this steps:
1)create two nodes:
geth --datadir node1 account new
geth --datadir node2 account new

2)genesis.json
{
    "nonce": "0x0000000000000042",
    "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x",
    "gasLimit": "0x8000000",
    "difficulty": "0x400",
    "config": {},
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x3333333333333333333333333333333333333333", "alloc": { }
}

3)initialize genesis:
geth --datadir node1 init ./genesis.json
geth --datadir node2 init ./genesis.json

4)To enable nodes I use:
geth --identity "name_of_your_node" --rpc --rpcport "8000" --rpccorsdomain "*" --datadir mode1 --port "30303" --nodiscover --rpcapi "db,eth,net,web3,personal,miner,admin" --networkid 1900 --nat "any"

geth --identity "name_of_your_node" --rpc --rpcport "8001" --rpccorsdomain "*" --datadir mode2 --port "30301" --nodiscover --rpcapi "db,eth,net,web3,personal,miner,admin" --networkid 1900 --nat "any"

5)Interconnect nodes:
geth attach http://127.0.0.1:8001
geth attach http://127.0.0.1:8000

6)Make Node1 as an admin node, I use this code to find info:
admin.nodeInfo
{
  enode: "enode://b378a4f7d9454811a89954cb97bb19589564a8e1ef24ebda07c25c2ae2a8acf35c4c14b2fd84d2a0cf92b1586eff0ea592de5f8effb0e08b1616917edf3306f1@100.69.54.149:30303?discport=0",
  enr: "enr:-JO4QI-9oLlq2ZVbjMfEry_Kk7VJ65divD9HL7jFC3tl2WwkbTc6Bc4sIqaD9MTKAEQuDfWqSw_bwoy2nqy5MAfYgssHg2V0aMrJhPxk7ASDEYwwgmlkgnY0gmlwhGRFNpWJc2VjcDI1NmsxoQOzeKT32UVIEaiZVMuXuxlYlWSo4e8k69oHwlwq4qis84N0Y3CCdl8",
  id: "fb25937ad7ced1cf77a820fc34f93d42135cf2760508db94dd56c2ca05bb92b5",
  ip: "100.69.54.149",
  listenAddr: "[::]:30303",
  name: "Geth/name_of_your_node/v1.9.15-stable-0f77f34b/linux-amd64/go1.14.2",
  ports: {
    discovery: 0,
    listener: 30303
  },
  protocols: {
    eth: {
      config: {
        byzantiumBlock: 4370000,
        chainId: 1,
        constantinopleBlock: 7280000,
        daoForkBlock: 1920000,
        daoForkSupport: true,
        eip150Block: 2463000,
        eip150Hash: "0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0",
        eip155Block: 2675000,
        eip158Block: 2675000,
        ethash: {},
        homesteadBlock: 1150000,
        istanbulBlock: 9069000,
        muirGlacierBlock: 9200000,
        petersburgBlock: 7280000
      },
      difficulty: 17179869184,
      genesis: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
      head: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
      network: 1900
    }
  }
}

7)another node I use this code to connect to node 1:
admin.addPeer("enode://b378a4f7d9454811a89954cb97bb19589564a8e1ef24ebda07c25c2ae2a8acf35c4c14b2fd84d2a0cf92b1586eff0ea592de5f8effb0e08b1616917edf3306f1@100.69.54.149:30303?discport=0")
true

8)but the nodes are not connected:
> net.peerCount
0
> net.listening
true

Have I missed something? please help?
I have another question: why the IP in admin.nodeInfo is "100.69.54.149", it's not my IP how to change that?


texts: I written an ERC20 token contract, now I have to use my token in another contract for transaction amount. How?

texts:
Taking help of openzepplin, in making ERC20 token , I now have to use this token in multiple contracts for various use.
So, how do I code my ERC20 token into other contracts, so that at time of amount transfer, metamask will send tokens ( not eth).
Any query, please do let me know & I'll share immediately.


texts: Why Does web3py Need Provider to Initialize Contract?

texts:
The two steps to create a contract instance in web3.py are --

w3 = web3.Web3(WebsocketProvider('https://ropsten.infura.io/v3/...'))
contract = w3.eth.contract(address=address, abi=abi)

Why must I supply a provider to create the contract? Initially I thought web3.py will fetch information from the network, but inspecting contract shows nothing --

(Pdb) contract.bytecode

My question in other words is: As I only need the contract skeleton for offline use and don't need to interact with the chain directly through the contract methods, is there a way to create a contract without needing to supply a provider endpoint?


texts: How long does it take for ETH to pass from one account to another on test-net?

texts:
I've used this service to send me 1ETH on test network. Service worked, it has even given ID of transaction, but ETH has not arrived to my mist wallet in 5 mins. Is it expected to work so slow?

Thanx.


texts: What exactly is an extended public/private key?

texts:
How do they differ per derivation level? For example is the extended public key of the master node equivalent for all intents and purposes as a depth 3 node's extended public key?

Therefor can I generate an address on the masternode public extended key? Will that be a valid address?


texts: Deploy multiple contracts with dependencies - Truffle

texts:
Say I have two contracts, an oracle and a reader.  How do I test (or even deploy) them both?

    contract Oracle {
        struct DocumentStruct{bytes32 name; uint value;}
        mapping(bytes32 => DocumentStruct) public documentStructs;

        function StoreDocument(bytes32 key,bytes32 name, uint value) returns (bool success) {
            documentStructs[key].value = value;
            documentStructs[key].name = name;
            return true;
        }
    }

contract Reader {
      address public oracleID;
      Oracle d;
  function Reader(address OAddress){
      d = Oracle(OAddress);
      oracleID = OAddress;
          }
 struct DocumentStruct{bytes32 name; uint value;}
  function RetrieveData(bytes32 key) public constant returns(uint) {
    DocumentStruct memory doc;
    (doc.name,doc.value) = d.documentStructs(key);
    return doc.value;
  }
    }

So Since the reader needs an Oracle address in the starting function, is there a way to do this in Truffle (what does the deploy_contracts.js look like?)  And how I just write tests to see if I can store documents and then read it?


texts: Trying to get my ERC tokens from etherscsan back into my etherwallet

texts:
How can I get my Erc-20 tokens back into my Etherwallet.  they show up in my Etherscan, but they are not in my Etherwallet.

I had to get a new computer, because Microsoft tried to download a new version of windows 10, and fdailed leaving me to get a new computer.

I have my Metamask seed, and I can see my exact tokens and balance, in etherscan, which everything looks to be in order, but I cannot get them to show in my etherwallet

I wish there was somebody I could see in person about this that knows about this, buty any help you may be able to give would be great thanks

Bret Kubin
Kubs69@gmail.com


texts: ipfs.infura.io for IPFS gateway and pinning

texts: I'm using Infura API for initializing IPFS. IPFS uses garbage collector to clean 2 weeks old unpinned data in public gateway. So, if I'll pin my hash is it possible that IPFS will still delete my information from server because I'm using public gateway?


texts: Geth's golang contract bindings need "RPC subscription features that are still under review" to process event logs. What are those features?

texts:
The documentation for Geth's golang contract bindings start out with

  Please note, events are not yet implemented as they need some RPC subscription features that are still under review.

What subscription features are needed, in order to implement events?

I'm asking because I'd like to assess the feasibility of making golang's contract bindings a full-fledged unit testing environment for solidity, and integration testing environment for solidity/go interactions. I was able to use the bindings for a project recently, and they were great: I could run thousands of tests before truffle could even get its boots on.


texts: how to send parameters to smart contract while deploying using metamask

texts:
I am trying to deploy a smart contract using BrowserSolc and Metamask. and deployed successfully when the contract doesn't have constructor parameters but now I am trying to deploy with the constructor parameter but unable to do it.

How to add a parameter to the send_ethTransaction method

const source = "pragma solidity 0.4.24;contract SujiToken { string public name = 'Suji';    string public symbol = 'SUJI';  string public standard = 'Suji Token v1.0'; uint256 public totalSupply; event Transfer(     address indexed _from,      address indexed _to,        uint256 _value      );  event Approval(     address indexed _owner,     address indexed _spender,       uint256 _value      );  mapping(address => mapping(address => uint256)) public allowance;   mapping(address => uint256) public balanceOf;   constructor(uint256 _amount) public{ require(_amount >0,'amount should be greater than zero');      totalSupply = _amount;      balanceOf[msg.sender] = totalSupply;    }   function transfer(address _to, uint256 _value) public payable returns (bool success){       require(balanceOf[msg.sender] >= _value);       balanceOf[msg.sender] -= _value;        balanceOf[_to] += _value;       emit Transfer(msg.sender,_to,_value);       return true;    }   function approve(address _spender, uint256 _value) public returns (bool success){       allowance[msg.sender][_spender] = _value;       emit Approval(msg.sender,_spender,_value);      return true;    }   function transferFrom(address _from, address _to, uint _value) public returns (bool success) {      require(_value <= balanceOf[_from]);        require(_value <= allowance[_from][msg.sender]);        balanceOf[_from] -= _value;     balanceOf[_to] += _value;       allowance[_from][msg.sender] -= _value;     emit Transfer(_from, _to, _value);      return true;    }}"
BrowserSolc.loadVersion("soljson-v0.4.24+commit.e67f0147.js", async(compiler) => {
    // console.log(compiler);
    optimize = 1;
    var result = compiler.compile(source,optimize);
    console.log(result);
    var byteCode = result.contracts[':SujiToken'].bytecode;
    // console.log(byteCode);
    if(window.ethereum){
        var web3 = new Web3(ethereum);
        await ethereum.enable();
        const params = {
            "type" : "ERC20",
            "from": ethereum.selectedAddress,
            "gasPrice": "750000", // 10000000000000
            "data": "0x"+byteCode
        };
        ethereum.sendAsync({
            method: 'eth_sendTransaction',
            params: [params],
            from: ethereum.selectedAddress, // Provide the user's account to use.
        }, function (err, result) {
            console.log(result);
            if(result){
                $('input[contract_hash]').val(result.result);
                //$('form').submit();
            }
        })
        // ethereum.send
        // console.log(window.web3);
    }else{
        console.log("Non ethereum browser has been detected");
    }
});

this is the code i am trying to implement.


texts:
For whatever reason, when I attempt to set an instance of a contract in a javascript file, I get the following message in my console:

Uncaught TypeError: web3.eth.Contract is not a constructor

At first, I suspected I had a problem with properly setting my Web3 instance, but when I run:

console.log(web3);

The console shows that I the web3 instance is set.

I try and set my the contract instance using the following code:

const myContract = new web3.eth.Contract([//json array]);

Any tips for solving this?


texts:
What's the correct way to multiply a number in ray (1e27) with a number in wad (1e18) to get the result in wad? E.g., I have an interest rate [ray] and a balance [wad] that I am multiplying to get a balance [wad].
I'm using DS-Math
uint256 amount = wmul(balances[owner], rate);

I'm seeing the result come out to 1000000000000000000000000000000 (1e27 / ray)
Should I just divide by 1e9 or is there a better, out-of-the-box way?


texts:
I have a smart contract that holds a token balance, let's call it Token A, users may send this smart contract Token B to receive Token A, they do so by specifying the amount of Token A they would like to receive and the smart contract would automatically calculate the amount of Token B they will have to spend based on a pre-defined ratio.

The problem is, on the front-end, I would like the users to be able to specify the amount of Token B they would like to spend instead of the amount of Token A they would like to receive, so I create a function to convert the user input amount of Token B to Token A, it goes something like this:

function convertBtoA(uint amountB) returns (uint) {
  return totalA.mul(amountB).div(totalB);
}

The user submits the result of that function, then the smart contract converts the amount back to Token B to determine the payout using another function:

function convertAtoB(uint amountA) returns (uint) {
  return totalB.mul(amountA).div(totalA);
}

However, the result of this function would sometimes be slightly different from the original user input amount, for example:

# given totalA == 195738239776775570; totalB == 59744193591648150
convertBtoA(50000000000000000) # output == 163813609331349736
convertAtoB(163813609331349736) # output == 49999999999999999

In the example above, the original user input is 50000000000000000 and the result of the conversion done by the smart contract is 49999999999999999. My question is, is there a way to guarantee the conversion of Token A to Token B and back to Token A to result in the same number it starts with every time?

Note: I can't feed the user input amount of Token B directly to the contract without conversion to Token A because this contract is sometimes used to pay out Token B by receiving Token A, in which case, I would like the user input to be specified in Token A.


texts: how to covert a string to a ether address (20 bytes)?

texts:
I have tried to use sha3 but it return error since invalid address. Here is my code. The sha3 returns 32 bytes address. I wonder is there other function that returns 20 bytes .
var to_add = web3.sha3(str);
web3.eth.sendTransaction({from: '0xC5b0f45d8533909a80eA45Ed2FC42bd36C1Cccac', data:str,to:to_add},function(err, transactionHash)


texts: Ethereum POS economics question about gravitating all ether supply to stake

texts:
Please, dispel my doubts about POS, miners rewards and too strong incentives to participate in it that could lead to almost total supply of ether locked in stake.

So, we have:

Et - total Ether supply at time t.

St - total Ether at stake at time t.

Rt - reward that goes to stakers at the end of time t (which could be defined as some sort of function F: Rt = F(St), it doesn’t matter now).

IR - inflation rate of Ether due to increasing supply.

IR = Et+1 / Et - 1 and Et+1 = Et + Rt. (big simplification here because of a lag with which the miners would spent their reward on market which should lead to inflation afterwards, but it doesn’t matter here).

IR = Et+1 / Et - 1 = (Et + Rt) / Et - 1 = Rt / Et.

Simultaneously miners interest rate for the same period is:

MR = Rt / St.

Therefore, MR > IR while S < E.

I mean that miners would get constantly higher than inflation rate while ether at stake is less than total supply.

Then, if it is relatively friction-less to stake ether, and if it is really safe to do this, this looks like a perfect bond: everybody could participate and get rate higher than inflation with no risk.

If there were something like this in financial markets, then, no doubts, soon all the money supply would be in such bonds.

If there is not enough risk of losing S, this builds a strong incentive to rise S till it reaches E: S → E. All ether would be at stake which freezes the economics. I mean something like negative deflation effects which leads to major crisis. Nobody wants to spend any wei, because what you lose is not just this wei, but a guaranteed inflation-free income on top of it. You have no motive to make any business and take risks if you could simply put all money at a deposit which is by definition yields you more than inflation.

I have tried to find any answer and excuse me in advance if I missed something. For now I have found only something in this paper: “Incentives in Casper the Friendly Finality
Gadget”. From the paper there would several risk types:

Loosing private keys, but this don’t count, this is general risk of using cryptocurrencies, stake it or not.
losses due to network latency and timeouts which could be mitigated by mining in pools.
Presence of malicious miners which leads to NPCP/NCCP (see paper) penalties. But what if there would be no malicious miners? And anyway, in the long run there would be two types of situations for honest miners: either NPCP/NCCP penalties would be such that you constantly lose money and you opt out,  either you still get higher than inflation income on average.

So the question is that I see a strong market incentive to put all ether at stake and no force to prevent the situation when S→E and complete disappointment after.

As I see now there could be only two types of such forces: different issuance model or some difficult-to-calculate-in-advance risks to put money at stake.

Of course this is relevant to the time of complete mass adoption of Ethereum. But still.

Update

I have found this paper: https://docs.google.com/document/d/1Xf_iHGI51Lp6nVHPZo0SdUw60-NA6YJUvk2s-eYaxLE

citation 1:

  maxDeposit - the maximum deposit allowed to become a proof of stake
  validator. If you want to deposit more, you must purchase multiple
  slots. Set to 50000

citation 2:

  Alongside this, another question is how to target the minimum entry
  size and a possible entry fee. One approach is to auction entries,
  thereby resolving many preference revelation issues and allowing
  targeting a fixed PoS participation rate, but at the cost of
  introducing or exacerbating selfish-mining attacks.

If I understand them correctly, there is talk about entry fee to become a validator/validator candidate (thus participate in issuance) which could be defined by market. Looks like this is the thing that will balance the incentives to be full in.


texts: How to subscribe to newly minted blocks?

texts:
I am trying to figure out the most efficient way to poll latest blocks.
I found that there is a newBlockHeaders event that I can subscribe to using web3js.
What is not clear to me is how to track the number of confirmations?
The premise of the question is that I want to find an efficient way to get events for a large number of transactions. My thinking is that I need to:

Observe and filter pendingTransactions
Observe newBlockHeaders
Use getBlock to identify all transactions in the block
Once I find pendingTransactions mentioned in getBlock, use getTransactionReceipt to find transaction logs.

The question is thus: Is newBlockHeaders sufficient for my use case or is it possible that transactions included in block might not have receipt / might not go through?


texts:
wrapper class to instantiate other classes

contract WrapperCreator {

    function WrapperCreator() {
    }

    function createTopic(string name, bytes32[] resultNames, uint256 endBlock)
        returns (Topic tokenAddress)
    {
        return new Topic(name, resultNames, bettingEndBlock);
    }
}

test cases for WrapperCreator

pragma solidity ^0.4.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/WrapperCreator.sol";

contract TestWrapperCreator {
    bytes32[3] resultNames;

    function beforeEach() {
        resultNames = new bytes32[](3);
        resultNames[0] = "first";
        resultNames[1] = "second";
        resultNames[2] = "third";
    }

    function testConstructor() {
        WrapperCreator wrapperCreator = WrapperCreator(DeployedAddresses.WrapperCreator());
        Topic testTopic = wrapperCreator.createTopic("test", resultNames, 1000000);

        Assert.equal(testTopic.getResultName(0), "first", "Expected result name matches");
    }
}

I get the following errors:

,../test/TestWrapperCreator.sol:11:23: TypeError: Type bytes32[] memory is not implicitly convertible to expected type bytes32[3] storage ref.
        resultNames = new bytes32[](3);
                      ^--------------^
,../test/TestWrapperCreator.sol:19:60: TypeError: Invalid type for argument in function call. Invalid implicit conversion from bytes32[3] storage ref to bytes32[] memory requested.
        Topic testTopic = eventCreator.createTopic("test", resultNames, 1000000);


texts: Tallying Majority Consensus From Nested Struct

texts:
How do I tally the votes of a nested struct to find out majority consensus?

as an example, if we have following scenario below; I want to create a function which allows me to calculate whether majority consensus among voters is "Yes" for true.

pragma solidity 0.5.10;

contract Consensus {

    struct Vote {
        address voter;
        bool yes;
        string comment;
    }

    struct ConsensusResult {
        Vote[] collectiveVotes;
    }

    mapping (bytes32 => ConsensusResult) votes;

    function addVote(bytes32 _voteID, bool _vote, string memory _comment) public {
        uint _length = votes[_voteID].collectiveVotes.length;
        votes[_voteID].collectiveVotes.length++;

        Vote storage v = votes[_voteID].collectiveVotes[_length];
        v.voter = msg.sender;
        v.yes = _vote;
        v.comment = _comment;
    }
}


texts: Would Ethereum have lower transaction fees with the same usage as Bitcoin?

texts:
As of today, the transaction fees and transaction processing time in Ethereum are much lower than Bitcoin, but I am wondering if this is due to better technology or not.

If Ethereum suddenly took on all the traffic of Bitcoin and the market has some time to stabilize would the same problems appear in Ethereum? If not, is this because of different parameters (e.g. a different blocksize) or fundamentally different technology?


texts: Transactions created using web3.py are not being seen on the Ethereum blockchain

texts:
I'm trying to use web3.py with infura.io to send ethereum tokens from one address to another.
This returns to me a transaction ID. But it never goes on to the blockchain when I check it. I have used high gas amount but it still doesn't work (The transaction id isn't present on the blockchain as per etherscan.io and also as per web3.py functions)

I tried a few other ways of signing the transaction but they didn't work either.

Please help me make this work. Thank you.

import web3
import time
w = web3.Web3(web3.HTTPProvider('https://mainnet.infura.io/12345678'))

# gas example
gas_limit = 250000
gas_price = 60

transaction = {
    'to':to_addr,
    'from':from_addr,
    'value':int(eth_amount*(10**18)),
    'gas':gas_limit,
    'gasPrice':int(gas_price*(10**9)),
    'chainId':1,
    'nonce':int(time.time())
    }
signed_transaction = w.eth.account.signTransaction(transaction, key)
transaction_id = w.eth.sendRawTransaction(signed_transaction.rawTransaction)

print ('\nhttps://etherscan.io/tx/{0}'.format(transaction_id.hex()))


texts:
Do they have a lifespan?
Can they be deleted?
Have there been any cases of errors with logging or logs not being written?

I'd like to know if I can rely on logs and build application logic on top of them.

Example use case: Querying transfer logs of a specific token contract to build a list of accounts that hold a token balance.


texts: Is there an api for etherscan and rinkeby websocket? I've checked the link below https://etherscan.io/apis#websocket but see no way of accessing websockets in rinkeby. Is there a way to test the web socket etherscan api on rinkeby to see my test transactions go through?


texts: Ethereum smart contract update, transactions and events

texts:
I have a question about versioning of smart contracts in Ethereum. Lots of articles have been written about how to decouple your logic and data, how to use interfaces when referencing other contracts, how to use generic key value stores to store data and retrieving it through library functions in a strongly typed way.

What about querying transactions and event log from old versions of the smart contract? Transactions and emitted events cannot be migrated. They are immutable. And perhaps you need to keep track of them in the client app for history. Events can be added, removed or have their signature changed in different contract versions. How do you deal with querying and decoding transaction input and event data for multiple versions of a contract?


texts: How to estimate the cost to call a Smart Contract method?

texts:
After succesfully deployed this Smart Contract on Ethereum testnet

https://testnet.etherscan.io/address/0x27c042342C9ba937214117e11A4970A6145034cB

is it possible to calculate how much gas is going to take to invoke a given method of the Smart Contract?

Reading How to estimate gas for a function without any input parameter? and How much does it cost to use a contract? and What are the limitations to estimateGas and when would its estimate be considerably wrong? didn't help me as expected...

This is how to instantiate the Smart Contract on geth console command line:

// creation of contract object
var aContract = web3.eth.contract([ { "constant": true, "inputs": [], "name": "queryNumEscrows", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "escrowId", "type": "uint256" } ], "name": "queryStatus", "outputs": [ { "name": "status", "type": "uint256", "value": "0" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "seller", "type": "address" }, { "name": "thirdParty", "type": "address" } ], "name": "start1", "outputs": [ { "name": "escrowId", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "escrowId", "type": "uint256" } ], "name": "revoke", "outputs": [ { "name": "amount", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "escrowId", "type": "uint256" } ], "name": "release", "outputs": [ { "name": "amount", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "seller", "type": "address" }, { "name": "thirdParty", "type": "address" } ], "name": "start", "outputs": [ { "name": "", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [], "name": "kill", "outputs": [], "type": "function" } ]);

// initiate contract for an address
var sc = aContract.at('0x27c042342C9ba937214117e11A4970A6145034cB');

// view code
eth.getCode(sc.address);

Now, I want to send this transaction to the Smart Contract, but I would like to previously know how much gas is it going to take:

sc.start.sendTransaction("0x90e8682b63d7922a3e942d4bbd4c88095634a17b", "0x47978a69f410d0f61850c92acdb0d4c464d70937", {from:"0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d", value:"0x3b9aca00"});

to avoid this message:

"Warning! Error encountered during contract execution [Out of gas]".

I guess the following json-rpc method should be used:

https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas

I have read at docs that:

When calling SCs => data: DATA - (optional) Hash of the method signature and encoded parameters.

But don't get how to encode method name, parameters and ABI in data field. Any idea?

Or is there any other way round to tackle this issue?

Thx.


texts: How to read responses from calls to contract methods made using web3.js?

texts:
I have built a contract which provides a simple method for storing some data in a property of my contract on the blockchain.

I can interface with my contract using web3.js and I have no issue doing so.

The problem is that I only want to be able to set the property if it has NOT already been set. As such the contract method checks for a zero value and returns an arbitrary error code ("0001") if it has already been set. If it has not been set "0000" is returned.

When I execute the method (through javascript) my callback is immediately called. The result contains the transaction hash for an as of yet unmined transaction. When the transaction is mined there are no further calls to the callback, and at no point is the error code (mentioned above) made available asynchronously within my javascript code.

As such I can not update my interface accordingly when there is an 'error'.

I can poll the transaction hash and check for the point at which it is mined, but because even in the error case the transaction is mined, this is of little use.

web3.js loses a lot of its utility if there is no way of discerning the response of mining a transaction on the blockchain. Have I missed something?

Thanks


texts: What is the fastest way to implement the find first set algorithm in Solidity?

texts:
As per Wikipedia, a find first algorithm is:

a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least significant bit position.

This is also known as the "count trailing zeros" algorithm. What is the fastest way to implement it in Solidity?


texts: I read that whenever you are performing arithmetic operations in a function of a smart contract, you should use SafeMath library. What is the reason for using SafeMath library? Also, what are the advantages and disadvantages of this library during arithmetic operations?


texts: How to get private keys on Truffle from Ganache accounts

texts:
Doing some ERC-735 tests on truffle+ganache I got stuck when creating claim signatures. They need to be signed from my ganache account, but I don't know its private key. The code to be used is this:

const messageToSign = "hello world";
const privateKey = "43f2ee33c522046e80b67e96ceb84a05b60b9434b0ee2e3ae4b1311b9f5dcc46";
var msgHash = EthUtil.hashPersonalMessage(new Buffer(messageToSign));
var sig = EthUtil.ecsign(msgHash, new Buffer(privateKey, 'hex'));
var signatureRPC = EthUtil.toRpcSig(sig.v, sig.r, sig.s)
console.log(signatureRPC);

As explained on Sign data with private key inside a truffle test file there was a method to sign messages from Truffle using:

let signedMessage = await web3.personal.sign("data", accounts[0])

but it is now deprecated, it throws "Method personal_sign not supported" error, so a solution seems to be an explicit signing using private key (code above).

How can I get the private key from ganache? or even better, can I get the private key from truffle?


texts:
Consider we need to determine an expiry date for a contract such that after this date the contract will be destroyed as follows:

uint256 public expiryDate;

constructor(uint256 duration)
        public
        payable
    {
        owner= msg.sender;
        expiryDate = now + duration;
    }

function destryContract() public {
        require(now >= expiryDate);
        selfdestruct(owner);
    }

Now, consider we need to calculate the exact duration for this expiry date, for example, we want to distroy the contract exactly after one month.

How to calculate the value of the duration variable as an integer?


texts: What does add(source, 32) do in solidity?

texts:
I understand what add() does. It used used in the assembly to perform additions. My question is why are we adding 32 here? What is the purpose of doing so?
The full code is here


texts: Cannot verify a particular smart contract code on Etherscan with optimization enabled

texts:
I've already deployed many smart contracts to Ropsten testnet and successfully verified them in Etherscan, but today I encountered one contract which doesn't get verified through all my attempts. This is a simplified version of a bigger contract the code of which I was trying to verify.

Smart contract with the similar code and optimization enabled was successfully verified.
Smart contract with the below code and same compiler setting does not get verified on Etherscan for some reason.
Etherscan's Verify Contract Code (version 2.0) doesn't help either.
I've tried to deploy the contract both with Truffle and Remix IDE, with optimization enabled (runs = 200) using compiler version v0.4.23+commit.124ca40d.
I've provided expanded description on the issue in this GitHub gist.

I appreciate any help or hints regarding this issue. Big thank you.

Code which doesn't get verified in Etherscan:

pragma solidity 0.4.23;

contract TEST {

    string public someVal;
    string public someVal2;

    bytes32 public signature1 = keccak256(
        "address TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST",
        "bytes TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST"
    );
    bytes32 public signature2 = keccak256(
        "address TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST",
        "bytes TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST"
    );
    bytes32 public signature3 = keccak256(
        "address TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "address TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST",
        "bytes TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST TEST TEST TEST TEST",
        "uint256 TEST TEST TEST TEST"
    );

    constructor (string val, string val2) public {
        someVal = val;
        someVal2 = val2;
    }

}


texts: As of Feb 2016, how big is the ethereum blockchain size and its monthly growth rate? Does the blockchain implement anything with pruning to reduce its size in the near future?


texts: flag provided but not defined: -ethstats

texts:
I am trying to work with rinkeby testnet and I downloaded rinkeby.json genesis file and successfully created genesis block now i am trying to run this command to sync all blocks but I am facing this error. Help!

geth --networkid=4 --datadir=$HOME/.rinkeby --cache=512 --ethstats='yournode:Respect my authoritah!@stats.rinkeby.io' --bootnodes=enode://a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf@52.169.42.101:30303


texts: What Hierarchical Deterministic (HD) wallets are available for Ethereum?

texts:
A Hierarchical Deterministic (HD) wallet has some nice features such as easier backup (instead of needing to backup multiple keystore files and the passwords for each of them).

Are there any implementations of an HD wallet for Ethereum?


texts:
How to create a contract  address  to automatically  send tokens to ETH address  and also how can I also be able to get the ETH from the contract  address  to my ETH wallet (I am the contract creator)

I mean for example
BOB sends 1ETH , BOB will receive 1000Tokens automatically

Also me (owner of the contract)  can get the 1ETH too.

P. S : if it can't be done is their any source code I can be able to use to do it  on a website


texts: How to get new transaction hash after user speed up the transaction

texts:
Hello Everyone
When a transaction starts and finishes we are able to get the information via getTransactionReceipt and the other functions that provided with web3.
When a user speeds up the transaction, new transaction starts but we do not know this hash.
How to get the new transaction hash?


texts:
Will the Jaxx mobile wallet support ethereum after Byzantium hard fork, after 16th October 2017?
If not what other mobile wallet should I use for my ethers?

Thank you,


texts: Why is this function indirectly changing a uint variable?

texts:
I'm having an issue with a smart contract I've created where variables are being affected by a function that does not access them. I am using Remix to test this.

//Solidity Version
pragma solidity ^0.4.0;

//Contract Code
contract TicTacToe{

//Struct for cell
struct Cell {
    uint row;
    uint column;
    address played;
}

//Struct for game board
struct GameBoard {
    bool gameWon;
    address _player1;
    address _player2;
    Cell[] board;
}
//These variables are being affected due to newGame();
uint private numberOfGames = 0; //I set this to private and created a getter (getGameNum()), but same occurs if public.
GameBoard[] public _games; //This is also being affected - newGame() will fill the array, even though only one item is being pushed.

//Publig getter for numberOfGames uint.
function getGameNum() public returns(uint){
    return numberOfGames;
}

//Function that creates an array. This will eventually add it to _games but until issue is resolved, I'm leaving it.
function newGame() public {
    //Create a temporary board (to be pushed later)
    GameBoard tempBoard;
    //Fill attributes of board
    tempBoard._player1 = msg.sender;
    tempBoard._player2 = msg.sender;
    tempBoard.gameWon = false;

    uint counter = 0;
    //For each row
    for (uint row = 1; row <= 3; row++) {
        //For each column
        for (uint column = 1; column <= 3; column++) {
            tempBoard.board.length++;
            tempBoard.board[counter].row = row;
            tempBoard.board[counter].column = column;
            tempBoard.board[counter].played = 0x0;
            counter++;
        }
    }
}
}

"numberOfGames" is correctly set to 0 on contract creating (you can verify this using getGameNum() ). However, when newGame() is called, the value is changed to 295530007198671819985454669347690311693110848207872.
Likewise, the _games array is filled when the newGame() function is called, even when the function doesn't interact with that array.

Any reason why this would be happening?


texts: how to interact with Back-end of a dapp?

texts:
I am trying to build a dapp but I am having problems. My idea is: I have a front-end written in html / css and a backend implemented with web3.js thanks to which it is possible to connect to a blockchain node. is this reasoning correct?
Now how does a user connect to my dapp? Should you use a wallet?


texts: 'Transaction nonce is too low. Try incrementing the nonce.' while following truffle tutorial

texts:
I ran into a nonce error on the last leg of this tutorial : https://www.trufflesuite.com/boxes/flashloan-box
I also supplemented the tutorial with this video on yt(fyi b/c some of the code comes from there as well) : https://www.youtube.com/watch?v=aYSGeVkCWXU&t=1s
*note that I funded the contract prior
truffle(kovan)> amount = web3.utils.toWei('1000')
'1000000000000000000000'

set the asset variable to the txn hash of the curreny DAI coin
truffle(kovan)> asset = '0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD'

Everything was going stellar until I tried to execute the flashloan itself:
truffle(kovan)> f.flashloan(asset, amount)
Uncaught:
{
  code: -32010,
  message: 'Transaction nonce is too low. Try incrementing the nonce.'
}
truffle(kovan)>

How should I address the nonce issue? I read in some post from 2020 that there was an advanced user option in the works to manipulate it, but I didn't find any follow up on that.
Thank you for your time
*Edit
I updated the migration file and then forked a branch from the main net using the following command:
ganache-cli --fork https://mainnet.infura.io/v3/YOUR_INFURA_KEY -i 1
This solves the primary issue of this thread so I will close it


texts:
I have started geth using below:

geth --rpc --rpccorsdomain * --rpcport 8545 --rpcapi personal,web3,eth,net

and this is my web3.js code:

<script src="/bower_components/web3/dist/web3.min.js"></script>
<script type="text/javascript">
    function send() {
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        }
        if(!web3.isConnected()) {
            console.log('not-connected');
        } else {
           console.log('connected');
        }
    }
</script>

first console.log said "not-connected" and got an error: Error: CONNECTION ERROR: Couldn't connect to node http://localhost:8545.


texts: How to call smart contract functions with an address stored in hardware wallet?

texts: Is there a way to call smart contract functions with an address stored in hardware wallet? If so, please let me know how. Thanks.


texts: Deploy ERC20 token first while still developing the main contract?

texts: Would there be any issues if I deploy the ERC20 token first while still developing the main contract that will give utility to the said ERC20 token? Also, on the main contract, how do I reference the deployed ERC20 token, can I just hard code the token address? Thanks


texts: How does online wallets handle ERC20 tokens behind the scenes?

texts:
Described in the title: How do online wallets handle ERC20 tokens behind the scenes?

Or centralised exchanges in that matter. Are they simply communicating with the ethereum blockchain to generate an account and then storing the private key for each user?

Hopefully someone can give an in-depth answer to this question and the technicalities behind.


texts: Chainlink Alarm Clock fullfill method never called?

texts:
Working with the Chainlink Alarm Clock, my fulfill() method seems to never get called. So for the docs example (below), votingLive is never set back to false after time is up. Everything else works and I've gotten to this point with both rinkeby and kovan oracles in remix and locally all with the same issue.
Issue...
No time delay is being added, and function not executed.
Code...
pragma solidity ^0.6.0;

import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";

contract ChainlinkTimedVote is ChainlinkClient
{
  uint private oraclePayment;
  address private oracle;
  bytes32 private jobId;
  uint private yesCount;
  uint private noCount;
  bool private votingLive;
  mapping(address => bool) public voters;

  //only the contract owner should be able to start voting
  address payable owner;
  modifier onlyOwner {
  require(msg.sender == owner);
  _;
  }

  constructor() public {
      setPublicChainlinkToken();
      owner = msg.sender;
      oraclePayment = 0.1 * 10 ** 18; // 0.1 LINK
      //Rinkeby alarm oracle
      oracle = 0x7AFe1118Ea78C1eae84ca8feE5C65Bc76CcF879e;
      jobId = "4fff47c3982b4babba6a7dd694c9b204";
      //initialize votes
      yesCount = 0;
      noCount = 0;
      votingLive = false;
  }

  function startVote(uint voteMinutes) public onlyOwner {
      Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
      req.addUint("until", now + voteMinutes * 1 minutes);
      //Start voting window then submit request to sleep for $voteMinutes
      votingLive = true;
      sendChainlinkRequestTo(oracle, req, oraclePayment);
  }

  //Callback for startVote request
  function fulfill(bytes32 _requestId) public recordChainlinkFulfillment(_requestId) {
      //$voteMinutes minutes have elapsed, stop voting
      votingLive = false;
  }

  //Increments appropriate vote counter if voting is live
  function vote(bool voteCast) public {
    require(!voters[msg.sender], "already Voted!");
    //if voting is live and address hasn't voted yet, count vote
      if(voteCast) {yesCount++;}
      if(!voteCast) {noCount++;}
      //address has voted, mark them as such
      voters[msg.sender] = true;
   }

   //Outputs current vote counts
  function getVotes() public view returns (uint yesVotes, uint noVotes) {
      return(yesCount, noCount);
  }

  function isVotingLive() public view returns (bool) {
      return votingLive;
  }

  //Lets user know if their vote has been counted
  function haveYouVoted() public view returns (bool) {
      return voters[msg.sender];
  }
}

Thoughts...
Maybe I'm building the request wrong?
      Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
      req.addUint("until", now + voteMinutes * 1 minutes);

Flipping
      votingLive = true;
      sendChainlinkRequestTo(oracle, req, oraclePayment);

to
      sendChainlinkRequestTo(oracle, req, oraclePayment);
      votingLive = true;

I'm also noticing no time delay is being added.


texts: Off-the-chain rules vs. on-chain-rules when designing a DAO

texts:
Imagine such DAO, where there are two actors:

Business
Partners

What a business can do are:

Issue a certificate to partners, which uses certain off-the-chian logic to evaluate the traits of the partners,
Advertise to all partners a JobPost available from the business, the JobPost may need 1 or many partners to fill in.

To fill a JobPost:

Either a parter can apply for it bidding with a competitive rate,
Or the busienss can offer/hunt for `partner actively.

Once the JobPost is filled, a WorkContract is signed where certain amount of token is locked and can be released to the partners when either triggered by business or timeout (in block time)

The philosophical question is, should the decision of filling the JobPost made off-the-chain by the entity represents (holding the private key) the business, or the filling rules itself should be part of the original JobPost itself.

Technically we can do both. But if we use blockchain, to what extent we want to use the blockchain, is another way to generalize the question.

Hope it is a understandable question!


texts: Does the Metamask password need to be kept very secure?

texts:
My Metamask password is not as secure as it could be, as the same password has been used elsewhere.

Am I right in thinking that the password is only used locally in the Chrome plugin, and more than that is needed (seed words or private key) to access my account?

What is the best way for me to change the password?


texts: How to get transactions on only one Ethereum address?

texts:
Imagine this scenario:

ACME company is selling a service for 1 AcmeToken to their users.

When a user wants to buy the service, ACME company generates a new Eth address for the user, so there is an association between EthereumAddresses and Users in the company database.

Unfortunately, this common scenario has one problem:

When the company wants to withdraw the tokens from all the addresses they generated, the company may spend a lot of ETH to cover GAS price costs.

So, I trasformed the scenario in this way:

The company receives all the tokens on one single Ethereum address and asks the transaction hash to the user, but.. in this way the user could take old transactions hashes to the same address, so I'm not considering proceeding this way so safe and secure.

How would you identify a single transaction in a safe way without creating a lot of addresses?


texts: Please help define "public economic consensus" used by Vitalik Buterin

texts:
In a recent paper titled, "Ethereum Platform Review: Opportunities and Challenges for Private and Consortium Blockchains" by Vitalik Buterin, he mentions the notion of public economic consensus.

Can anyone help explain the definition of this term / notion and how it differs from something like public goods and common resources within economics? Is it synonymous with the idea of Proof of Work / Proof of Stake or is it different?

The paragraph it comes from is here:

  The Ethereum platform was originally conceived in November 2013 with
  the goal of creating a more generalized blockchain platform, combining
  together the notion of public economic consensus via proof of work (or
  eventually proof of stake) with the abstraction power of a stateful
  Turing-complete virtual machine in order to allow application
  developers to much more easily create applications that benefit from
  the decentralization and security properties of blockchains, and
  particularly avoid the need to create a new blockchain for each new
  application.

I am just looking for a better understanding of this concept and any reference / source material you can point me towards.


texts: Truffle Console: No error but the output of attacker is always zero

texts:
I am trying to do a tutorial available at:
medium justdev
I have created modified contracts which are stored here:
commands and the contract code
In the contracts folder, 3 files are stored (Attacker.sol, Victim.sol and Migration.sol) and migrations folder contains *.js files. I have also stored all the required commands in the file: commands.odt or in the commands.txt file.
I am able to run all the commands related to both the victim and the attacker but the output for the balance of attacker is always zero as shown below:
>Attacker.deployed().then(contract => attacker = contract); "Testing Attacker"
'Testing Attacker'
truffle(development)> balance3 = await web3.eth.getBalance(attacker.address)
undefined
truffle(development)> web3.utils.fromWei(balance3, "ether")
'0'
truffle(development)> attacker.attack()
{ tx:
truffle(development)> balance3 = await web3.eth.getBalance(attacker.address)
undefined
truffle(development)> web3.utils.fromWei(balance3, "ether")
'0' (still Zero)

Again there is no error, but balance for the attacker is always zero.
Somebody please guide me.
Zulfi.


texts: Truffle serve not finding css and javascript files

texts:
the directory is getting served wrong in truffle and I can't figure out where to change it....

The terminal response is...

Couldn't find file at .//app/app.js.

My build file.......

module.exports = {
          build: {
            "index.html": "index.html",
            "app.js": [
              "javascripts/app.js"
            ],
            "app.css": [
              "css/app.css"
            ],
            "images/": "images/"
          },
          rpc: {
            host: "localhost",
            port: 8545
          }
        };

My index.html file .......

    <link href="./css/app.css" rel='stylesheet' type='text/css'>
    <script src="./javascripts/app.js"></script>


texts: What is the command PUSH29 010..00 in solidity compiled bytecode?

texts:
If you take a look to the bytecode of several contracts compiled from solidity you can notice that in the first ".data" basic block there is this command:

PUSH29 0100000000000000000000000000000000000000000000000000000000

For instance, this simple contract contains this command:

pragma solidity^0.4.24;
contract test {
   function f(int8 x) public pure returns (int8) {
     return x+1;
   }
}

What is the purpose of this command?


texts:
Is transaction "status" flagged inside the block when it's mined?
Like if a transaction is mined but failed due to out of gas or not meeting contract conditions, is the transaction marked as "failed" as part of the raw hexadecimal block?


texts: How can I use a Presale JSON file to keep my ETH long-term in cold storage and sell my ETC seperately?

texts:
I received Ether during the Pre-sale in June 2014 and received a JSON file and have the password. I have never tried to access these funds. I found out that I should have ETC & ETH due to the hard-fork in 2016 due to the DAO hack. My question is, what is the safest way to keep the ETH and sell the ETC or trade it for more ETH in July 2017?

Some posts mentioned to Split the funds by firstly creating a new ETC & ETH account by using something like My Ether Wallet (MEW). I then need to access the funds via the JSON file on the ETC & ETH blockchains seperately in MEW. On each chain (ETH & ETC) you then need to move the funds from the presale wallet to the new ETH & ETC accounts. Due to EIP-155 My Ether Wallet (MEW) should have replay protection so it should be as simple as that. Is this logic flawed in anyway? I am very worried that I do something wrong and lose any of the ETH or ETC. What would be the steps if I had to do this process via the official Ethereum Wallet on www.ethereum.org (Geth I think) or Mist?

If I keep the JSON file for another few years without accessing the funds will I still be able to access it or is it better to split it? I was thinking of getting maybe a hardware wallet if it is required to split it.


texts: Is the solidity compiler missing a check? Constant function updates state

texts:
I have found a very interesting behaviour of the EVM and probably a missing check in solidity compilation.

Consider the following code:

contract RootContract {
    Simple public s;
    string public data;
    function RootContract() { s= new Simple();}
    function getSimpleData() constant returns(string out) {
        s.fillData(this);
        out=data;
    }
    function setData(string d) {data=d;}
}

contract Simple  {
    string public data;
    function setData(string d ){data=d;}
    function fillData(RootContract r) public {r.setData(data);}

}

The function getSimpleData is "constant" and therefore should not allow to modify any state data. But it calls Simple.fillData, that in turns call RootContract.setData.

But it compiles, and it works, except that the root contract data is not set, but the Simple contract data gets returned by the getSimpleData constant function.

> var comp=eth.compile.solidity("import '/Users/guenole/Ethereum/sources/Simple.sol';")
> var root=comp['/Users/xxx/sources/Simple.sol:RootContract']
> var RContract=contract(root.info.abiDefinition)
> var RContract=eth.contract(root.info.abiDefinition)
> var R=RContract.new( {from: eth.coinbase, data: root.code, gas:1000000})
> R.address // after mining
"0x51ecec3c403159dafc05538dc0783559772874d9"
> R.s()
"0x92f2700514a8ab3ac026d1d3119ab2677d1d083a"
> var simple=comp['/Users/xxx/sources/Simple.sol:Simple']
> var SContract=eth.contract(simple.info.abiDefinition)
> var S = SContract.at(R.s())
> S.setData("un test de chaine", {from: eth.coinbase, gas:100000})
> S.data() // after mining
"un test de chaine"
> R.getSimpleData() // without mining
"un test de chaine"
> R.data() // the data of R is not set
""

So this is actually odd. Anyone has a view that justify such behaviour?
Now, the funny thing is that it tricks the EVM that is not able to have in RootContract a function like

function getSimpleData() constant returns(string) {
    return s.data();  // fails with usual Error: Return argument type inaccessible dynamic type is not implicitly convertible to expected type (type of first return variable) string memory
}


texts: Get history of transactions to specific account

texts:
I am using web3.js and geth to do my coding. I have an Ether Account (Not a Wallet Contract) that will be receiving funds from clients. The clients will be writing a number in the DATA field (that you see when you click "SHOW MORE OPTIONS").

But now I need to be able to look at the history of transactions to my specific account, and view the Data being sent to it.

QUESTION:

Is there a function in web3 to view the most recent transactions being sent to an Account? If not for an account, does that exist for a Wallet Contract? I know that the following function exists:

var transactionObject = web3.eth.getTransaction(hash);

But I do not have the hash for a transaction that a client does to me.


texts: Is it conceivable to have a DApp that doesn't issue tokens?

texts: I'm trying to nail down my explanations to people when they ask about Ethereum, and I'm trying to think of applications that wouldn't benefit from dispersing a token for some reason or another.


texts:
In my python code I try to send multiples transactions from different address at the same time.
The code build a transaction, sign it and send it, then I print "transaction number n sent" and it continue with the next one. It takes approximately 1 seconde between two print, which means a transaction is sent every 1 seconde, too slow for me.
Is it normal ? Do I need a better computer or internet connexion ? I'm using Infura provider
myContract=w3.eth.contract(address=adresse_contract,abi=abi_contract)

def multi_transactions(gaz_price_gwei):
   nonce = w3.eth.getTransactionCount(adresses[0])
   for i in range (len(adresse)):
       tx = myContract.functions.swap(Token).buildTransaction(
    {
      'from': adresses[i],
      'gas': 200000,
      'gasPrice': w3.toWei(gaz_price_gwei,"gwei"),
      'nonce' : nonce
    } )
       signed_tx = w3.eth.account.sign_transaction(tx, keys[i])
       w3.eth.sendRawTransaction(signed_tx.rawTransaction)
       print("Transaction",i,"sent")

Adresses and keys are arrays. The swap function in my contract just swap on Uniswap. All transaction have the same nonce


texts:
The following code is taken from truffle unbox

      initContract: function() {
        $.getJSON("adding.json", function(addingdappfrontend) {

          App.contracts.Add = TruffleContract(addingdappfrontend);

          // we have to set provideer

            App.contracts.Add.setProvider(App.web3Provider);

adding.json is my json file which is build directory
addingdappfrontend is the name of the folder where my code is written

1)Why are we sending adding.json inside $.get json

2)We have never used the adding.json in your ui

3)what $.getjson() is your code


texts: javascript input field doesn't trigger boolean in smart contract correctly

texts:
In one of my smart contracts I have the following function:

function dosomething(bool _okl) {
    if (_okl == false){
        boola = true;
        boolb = false;
        nextstep();
    } else {
        boolb = true;
        nextstep();
    }
}

I have a frontpage where bool _ok can be filled in by an input field:

input type="text" name="_okl" id="_okl" placeholder="true or false"

and button:

button id="button3">OK? button

this button is triggering my dApp.js in the following way:

$("#button3").click(function() {
    contractED.dosomething({value: $("#_okl").val()}, function(err, result) {
        console.log(err, result);
    })
});

For some reason, if I enter false in _okl, my contract doesn't recognize it as such in the logical check. What am I doing wrong here? It is triggering the function just fine, but always goes directly to the else part of my function.

Anyone any idea?


texts: ethers.js Why aren't logs filtering? (query returned more than 10000 results)

texts:
I'm building an API to scrape events from a contract suite deployed to Rinkeby. Here's an example function with some context:
const network = getNetwork(parseInt(`${process.env.CHAIN_ID}`));
const provider = network.name === 'unknown' ?
      new ethers.providers.JsonRpcProvider('http://localhost:8545/') :
      getDefaultProvider(network);

const tokenInstanceContract = new Contract(`${process.env.TOKEN_ADDRESS}`,
      TokenABI.abi,
      provider);

export async function getAllTxs(address: string = "", total: number = 50, userRole: any = null) {
    const event = tokenInstanceContract.interface.events.Transfer
    const logs = await provider.getLogs({
      fromBlock: process.env.DEPLOYMENT_BLOCK,
      toBlock: 'latest',
      topic: event
    }).catch((err: string) => console.error("BACKEND CATASTROPHE: ", err))
    console.log("YO ITS THE ALL TX LOGS: ", logs);

    return logs
}

The contracts were deployed recently. Still when I trigger this function, I get the following back:
code: -32005,
  data: undefined,
  url: 'https://rinkeby.infura.io/v3/{redacted}',
  body: '{"method":"eth_getLogs","params":[{"fromBlock":"0x6a20f3","toBlock":"latest"}],"id":408,"jsonrpc":"2.0"}',
  responseText: '{"jsonrpc":"2.0","id":408,"error":{"code":-32005,"message":"query returned more than 10000 results"}}'
}

I can tell that the function is hitting the Infura API, and seems to be scraping from the parameter passed into fromBlock. If that's the case, though, why are there so many results? I mean, even ignoring that the contract doesn't have even close to 10K interactions.
I assume that I'm filtering wrong, but can't figure out how to make this better. Any ideas?


texts: Gas price is reverted to be zero after updating using REST API on a Kaleido node

texts:
For those who have used Kaleido nod
I'm running a PoA node on Kaleido and I want to set the minimal gas price for the node.

I followed the instruction below to update a node configuration using REST API.

https://docs.kaleido.io/using-kaleido/blockchain-advanced-configuration/#gas-price

After updating, I attached to the node and checked eth.gasPrice on the geth console and I could confirm eth.gasPrice is updated from zero (which is default) but a few minutes later, it reverts to zero AUTOMATICALLY.

I could not find the answer to why this happens so it'd be very appreciated if you can help me.


texts: Is this a satifactory crowdsale contract?

texts:
Can one of you awesome people look over this contract for any issues? Its meant to be a simple crowdsale contract that has a deadline, a goal, and a minimum.

Participants should have the option of withdrawing their funds after the deadline, if the goal was not met.

pragma solidity ^0.4.2;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
  function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint256 a, uint256 b) internal constant returns (uint256) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return c;
  }

  function sub(uint256 a, uint256 b) internal constant returns (uint256) {
    assert(b <= a);
    return a - b;
  }

  function add(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a + b;
    assert(c >= a);
    return c;
  }
}

contract NextLevelCrowdsale {
    using SafeMath for uint256;

address public beneficiary;
uint public fundingGoal = 1200 ether;
uint public amountRaised;
uint public deadline = 1504180740;
uint public price;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;

//Mapping
mapping(address => uint256) public balanceOf;

//Events
event GoalReached(address beneficiary, uint amountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);

function NextLevelCrowdsale(
    uint fundingGoalInEthers,
    uint crowdsaleDeadline,
    uint minimumAmount) {
        fundingGoalInEthers = fundingGoal;
        minimumAmount = 1 ether;
        crowdsaleDeadline = deadline;
    }

function () payable {
    if (crowdsaleClosed) revert();
    uint amount = msg.value;
    if (amount < 1 ether) revert();
    balanceOf[msg.sender].add(amount);
    amountRaised.add(amount);
    FundTransfer(msg.sender, amount, true);
}

modifier afterDeadline() { if (now >= deadline) _; }

//Checks if the goal or time has been reached and ends the campaign
function checkGoalReached() afterDeadline {
    if (amountRaised >= fundingGoal) {
        fundingGoalReached = true;
        GoalReached(beneficiary, amountRaised);
    }
    crowdsaleClosed = true;
}

 function safeWithdrawal() afterDeadline {
    if (!fundingGoalReached) {
        uint amount = balanceOf[msg.sender];
        balanceOf[msg.sender] = 0;
        if (amount > 0) {
            if (msg.sender.send(amount)) {
                FundTransfer(msg.sender, amount, false);
            } else {
                balanceOf[msg.sender] = amount;
            }
        }
    }

    if (fundingGoalReached && beneficiary == msg.sender) {
        if (beneficiary.send(amountRaised)) {
            FundTransfer(beneficiary, amountRaised, false);
        } else {
            //If we fail to send the funds to beneficiary, unlock funders balance
            fundingGoalReached = false;
        }
    }
}

}


texts: Is that easy to turn a centralized app into a dApp hosted on Ethereum blockchain?

texts:
Currently I have an app that I use on my own servers. It is coded with JavaScript and PHP. The code is ready, I mean already exists.

Would it be difficult to turn it into a dApp using smart-contracts, hosted on Ethereum blockchain ?


texts: Current Blockchain Size - geth and Parity?

texts: As of 09.09.2017, can anyone tell me the current disk space requirements of the blockchain, when using Geth and when using Parity?  Please assume invoking with no options.


texts: How to prevent someone to replace our smart contract

texts:
I'm still learning to develop dApp and currently, I conduct some testing on my dApp.

I found out that someone who is part of the blockchain network (miner and node) can replace our deployed smart contract using Truffle

truffle migrate --reset --network networkName

I want to make sure that only the contract owner can replace the current smart contract. How can I do that?


texts:
I am wondering how I could have a function in one contract call another contract and check to see if the calling contract was in fact the one that initiated the call, rather than checking for msg.sender. How could I do this?

I guess an example is that I have a contract that holds tokens and I would like that contract to approve a transferFrom function that allows another contract to transfer token on behalf of the contract. How do I do this while avoiding the role of msg.sender?


texts: Will ERC223 Tokens work after Serenity Update?

texts:
Trying to understand what we should expect after External Owned Accounts will be treated as Contracts after second Serenity update will be live.

How does it influence ERC223 Tokens, will they break or continue to work ?

Thanks !!!


texts: Random number generation in certain range

texts: I need to add a random number function in my smart contract. Is it best to use Oraclize and e.g. random.org? It's not a lottery which means the random number generation does not require heavy security.


texts:
While I am trying to call a function using metamask i've got this error :

  error: Error: TypeError: senderAddress.toLowerCase is not a function
  at
  chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:65204:74
  at HookedWalletSubprovider.getAccounts
  (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:3806:11)
  at HookedWalletSubprovider.validateSender
  (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:65202:8)
  at HookedWall....


texts: Geth console does not seem to be reading the correct balance

texts:
I'm running a geth console on Windows with the following command:

geth --fast --cache=512 console

I've been playing around with Ethereum for a little bit, and want to do a little more. I want to just read the balance of my account for now. My account is:

0x28887D97CcA03df4Ce969726faFD3111e6F7f476

I get the following values:

This contradicts the amount I know to be in the account, and what reads out on etherchain:

https://etherchain.org/account/0x28887d97cca03df4ce969726fafd3111e6f7f476

Any reason why this could be? Is it because I am using fast syncing?


texts: Making contract compatible with newer solidity compiler

texts:
I have a simple timelock contract however it doesn't work with modern solidity compilers,

Could anyone make my contract compatible with solidity newer than 0.5.16? Thanks.

Here is the code, it only works with solidity version 0.3.5

contract timeLock
{
    struct accountData
    {
        uint balance;
        uint releaseTime;
    }

    mapping (address => accountData) accounts;

    function payIn(uint lockTimeS)
    {
        uint amount = msg.value;
        payOut();
        if (accounts[msg.sender].balance > 0)
            msg.sender.send(msg.value);
        else
        {
            accounts[msg.sender].balance = amount;
            accounts[msg.sender].releaseTime = now + lockTimeS;
        }
    }

    function payOut()
    {
        if (accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime < now)
        {
            msg.sender.send(accounts[msg.sender].balance);
            accounts[msg.sender].balance = 0;
            accounts[msg.sender].releaseTime = 0;
        }
    }

    function getMyLockedFunds() constant returns (uint x)
    {
        return accounts[msg.sender].balance;
    }

    function getMyLockedFundsReleaseTime() constant returns (uint x)
    {
        return accounts[msg.sender].releaseTime;
    }

    function getNow() constant returns (uint x)
    {
        return now;
    }
}

Thanks in advance!


texts: What is WETH and why can't we just use ETH?

texts: can someone explain why we need WETH? what's the purpose of WETH, can't we just use plain ETH? it's not like it removes the tx fees or something. Hopefully someone can shed light on the concept.


texts: Could't connect to node? ethereum wallet installing error

texts:
Im getting an error message when trying to install a new ethereum wallet
any ideas on how to solve it


texts:
Testing the GethJS console commands. I put in practice the personal.listWallets and personal.listAccounts. The first return me this value:

And the second command return me this:

It seems that are same things and I getting confuse


texts: Is it possible to use web3.js API methods to interact with a contract deployed on Rinkeby?

texts:
I have deployed a simple HelloWorld Solidity contract on one of the Ethereum Testnet called Rinkeby with MyEtherWallet and of-course I can interact with it.  Now I want to interact with that contract through web3.js API methods, if possible, in javascript code.  I have Google this but could not get any idea where to start.

Here I want to call getWord() function in javascript through web3.js API.

pragma solidity ^0.4.0

contract HelloWorld{
    string word = "Hello world";

    function getWord() constant returns(string){
       return word;
    }

}


texts: why i get a lot of errors when i use truffle?

texts:
Seems that i have a lot of lost dependencies for example installing sha3 errors:

> node-gyp rebuild

C:\Windows\system32\node_modules\sha3>if not defined npm_config_node_gyp (node "
C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin
\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program
 Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )

gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Program Files\nodejs\node_mo
dules\npm\node_modules\node-gyp\lib\configure.js:483:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_mod
ules\npm\node_modules\node-gyp\lib\configure.js:508:16)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\grac
eful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:152:21)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodej
s\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Windows\system32\node_modules\sha3
gyp ERR! node -v v8.11.3
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open 'C:\Windows\system32\pac
kage.json'
npm WARN system32 No description
npm WARN system32 No repository field.
npm WARN system32 No README data
npm WARN system32 No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"
})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sha3@1.2.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sha3@1.2.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\mirror\AppData\Roaming\npm-cache\_logs\2018-08-06T15_05_03
_287Z-debug.log

Always install nodegyp again show errors, again if i install web3 the same errors, maybe is because i must to use linux instead of windows? Compiling errors again with web3


texts: What are DeFi tokens ? How to create them in Ethereum?

texts:
I found about Defi that;

“DeFi is an ecosystem comprised of applications built on top of public
distributed ledgers, for the facilitation of permissionless financial
services.” Broadly speaking, DeFi is an ambitious attempt to
decentralize core traditional financial use cases like trading,
lending, investment, wealth management, payment and insurance on the
blockchain. DeFi is based on Decentralized Applications (dApps) or
protocols. By running these dApps on a blockchain, it provides a
peer-to-peer financial network. Like lego building blocks, every dApp
can be combined with each other. Smart contracts work as connectors —
comparable with perfectly specified APIs in traditional systems.

But I'm still not clear about DeFi tokens. Can anyone please explain me ?
And provide some good resources to start with ?
Thank you!


texts: If I choose not to verify a smart contract, the source code will be not visible, but would other people be able to see the content anyway? I am asking this because I want to call an API and that would expose the key and secret. Is there a way to hide it?


texts: Issue with selfdestruct() getting an error

texts:
main contract function which calls my secondary contract

 function gameOver(uint _matchId)public payable onlyOwner returns(bool) {
    Match my_match = Match(matchTracker[_matchId]);
    bool success = my_match.destroy(msg.sender);
    if(success == true)
        delete matchTracker[_matchId];
    return success;

  }

here matchTracker stores the Address of each of the Match contracts

Match contract destroy function

function destroy (address payable _owner)external returns(bool)
        {   require(_owner == owner);
            selfdestruct(owner);
            return true;
        }

Can anyone identify what is wrong?
solidity version in use is 0.5.13


texts:
I am making a dapp in which ethereum user accounts that call certain functions are rewarded with an ERC20 token. All the dapp is based on functions using only one ethereum account as parameter. But if several people want to collaborate and call a function together then the smart contract needs to be able to treat that case. Instead of changing all functions I thought about the possibility offered by multisig.
For instance if 3 users create a multisig address on ethereum and call the action with a multisig wallet as the multisig account. Is it possible and do you see anything wrong with this approach? Is metamask able to do it if not is it technically possible to develop a wallet able to handle the multisig transactions signatures process ?

Best regards


texts: Issue with New version of Metamask: Remix cannot detect the Metamask address

texts:
I have just installed Metamask version: 6.3.1

Now in Remix, the address of my account in metamask is not detected. The account box in remix remains always blank now (see picture below).

Note that I did not have this issue with an older version of metamask.

Question: How to resolve the above issue? so remix can detect metamask.


texts: How to find the gas and gas price for truffle.js with large files?

texts: this might be a basic question, but I was trying to deploy a large smart contract with multiple solidity files within it using Truffle and I cannot seem to be able to find a correct gas or gasPrice for the truffle.js file. Everything compiles, but when I try to migrate I continue to get the error "The contract code couldn't be stored, please check your gas amount". I know that there are gas estimates in the build folder, but the contract I am trying to deploy is rather large and it would take forever to go through all the .json files in the build folder and add up all their gas estimations. Can someone give me a basic idea of what I should do here? Thanks!


texts: Why were empty accounts allowed to be on the blockchain?

texts:
It's hard to see what the benefits of allowing empty accounts to be on the blockchain are.  This was a known subtlety (see "note: there is a difference between zero-balance and nonexistent") and exploited by a "state-bloat" attack.

What were the technical challenges why the protocol didn't prevent them in the first place?
What are the "flaws" in the protocol as mentioned in the State Clearing EIP158 rationale and this question?


texts: Is there a 'log2' builtin function or constant value in Solidity?

texts:
Remix gives me a warning that I haven't received before:

Is there a new log2 builtin function or constant value in Solidity?


texts: Why do some transactions use more gas than others, even when they send the same ERC20 token?

texts:
Why do some transactions use more gas than others, even when they are transferring the same ERC20 token, for example USDC. Even when the receiver is the same and the transferred amount is the same.
This one used 42,381 gas:
https://etherscan.io/tx/0x05c86098176a2d7d7d85375c7745503c36b7abc7dbdcbcdd01802859b6fec3a9
This one used 27,381 gas:
https://etherscan.io/tx/0x4499361f0ab60aed804f6d4ead7aa2ec0f801dcc3cfa1d945bd82c1081ca8611


texts: Why does function GetEVM set the balance of from address to MaxBig256?

texts:
As you can see in this line,

func (b *LesApiBackend) GetEVM(ctx context.Context, msg core.Message, state *state.StateDB, header *types.Header) (*vm.EVM, func() error, error) {
    state.SetBalance(msg.From(), math.MaxBig256)
    context := core.NewEVMContext(msg, header, b.eth.blockchain, nil)
    return vm.NewEVM(context, state, b.eth.chainConfig, vm.Config{}), state.Error, nil
}

The GetEVM function has a side-effect that sets the balance of from address to MaxBig256. What's the logic behind it?


texts:
Actually in my App.js I have called my contract function like this:

[
this.state.swapcontract.methods.sendFunds(address).send({ from: this.state.account , value:amount})
]

The function is called perfectly and does the work correctly but it also emits an event.

How do I access that event in my app.js?

Also if some function returned something then how to access it also?

Also this is not a async call and the call back function which many sites suggest is doing nothing.


texts:
After purchasing from a site like coinbase I would like to transfer from their wallet, what are some recommended storage options for ethereum?

My final solution is a hardware option like the ledger nano S, but in the meantime?


texts: How many miners are working on Ropsten (or other testnets)?

texts: I'm curious how many miners or nodes are there on an Ethereum testnet. Is there any website which records such statistic or any method to estimate?


texts: Multisig wallet generating a big number of ETH addresses

texts:
I'm looking for a possibility to generate many (say, 1000) addresses from a multisig wallet. The idea is that we accept payments to these addresses, and then move all funds to a single address using 2-of-3 signatures. Is it possible?

I know how to generate multiple addresses with geth API, but whoever knows the geth's passphrase, owns all funds, since this is not a multisig wallet.

I know I can use e.g. Mist for multisig, but this implies we have a single multisig wallet that has all funds, and we have 1000's.


texts: Infura tutorial no longer accurate, how to get the initial curl HTTPS POST to work?

texts:
Following the guide at https://blog.infura.io/getting-started-with-infura-28e41844cc89, step 2 after registering is to send a HTTPS POST using curl. The command is

curl -X POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":1}' https://mainnet.infura.io/MYAPIKEY

But when I try this (with my actual API key in place in the url) I get an error

Invoke-WebRequest : A parameter cannot be found that matches parameter name 'X'.
At line:1 char:6
+ curl -X POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion"," ...
+      ~~
+ CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

I am using windows 10 powershell and have downloaded curl-7.60.0-win64-mingw, which I ran by running the curl.exe in the bin folder.

According to another answer on stackoverflow that recommended using the command

Remove-item alias:curl

on windows 10 to avoid that specific Invoke-WebRequest error, and then running the curl command. When I do this I get no error, but nothing happens. There is no JSON returned with the Client and version, like the tutorial says their should be.

How do I get this to work? I can't follow the tutorial with these problems.

Thanks to anyone that can help.


texts: how can i restrict my smart contract getting invoked by any account in the network.can i tell the EVM itself to check(validate the account) is allowed to invoke the smart contract even before entering the smart contract for execution


texts: How to restrict access to a function to the owner of the contract only?

texts:
I am trying to modify the contract function type to endorse the fact that ONLY the owner of the contract can verify if a Company has done the payment of 2 Ethers required.

I tried with the following function which I called "isPaymentOK" but anyone has a better idea?

contract KYCPurchase {
  uint public price = 2 ether;

  struct Company {
      string registeredNumber;
      string companyName;
  }

  mapping (address => Company) companies;

  function buy(string registeredNumber, string companyName) public payable {
    require(msg.value == price);

    // Keep a list of buyers who have transferred enough ether
    companies[msg.sender] = Company(registeredNumber, companyName);

  }

  function isKYCPaymentOK (string registeredNumber, string companyName) pure private returns (string, string) {
        return (registeredNumber, companyName);

  }
}

Thanks.


texts: What is the use case of Parity's passive sync mode?

texts:
The Parity Ethereum client has four sync modes, two of which are active and passive. Active makes perfect sense to me, Parity continuously syncs the chain. However passive says "parity syncs initially, then sleeps and wakes regularly to resync".

Why would anyone choose passive instead of active? In other words, what is the use case for passive sync?


texts: Are there more important "impossible triangles" aside from CAP theorem, FLP impossibility and Zamfir's triangle?

texts:
I have come across CAP theorem, FLP impossibility, and Zamfir's triangle ever since I began to study blockchain. As I interpret CAP theorem as the tradeoff between consistency, Availability,  and Partition Tolerance; FLP impossibility as Determinism, Asynchrony, and Failure which can be further categories into safety and liveness; Zamfir's triangle as Latency, Message Overhead, and number of nodes.
1. Is my understanding of these theorems correct?
2. Are there more impossible triangles that are important to understand blockchain?


texts:
Assuming I have enough Ether, can smart contracts be executed no matter how complex they are as long as I specify a large enough gasLimit?
Hope you can give me some hope, thanks!


texts: Web3 behaves different on the client and server with different providers

texts:
I'm trying to read a mapping storage variable from blockchain. Below, are my attempts, from client and server. Testing on Rinkeby network.

From client:
Metamask is installed and I'm trying from the browser console. Web3 version is 0.2.x.

const index = "0000000000000000000000000000000000000000000000000000000000000005";
const key = web3.toHex('my_key');

web3.eth.getStorageAt(
  'contract_address_here',
   web3.sha3(key + index, { encoding: 'hex' }),
   (err, result) => {
        console.log(result); // Returns 0x00.....1; // Key exists
   }
);

It works. The key does exist on the Rinkeby network.

Attempt from server:
Please note, that web3 version is 1.0.0-beta.26 and I'm using Infura as the provider.

// Init web3
const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider(
  "my rinkeby infura link here"
);
const web3 = new Web3(provider);

const index = "0000000000000000000000000000000000000000000000000000000000000005";
const key = web3.utils.toHex('my_key');

web3.eth.getStorageAt(
  'contract_address_here',
  web3.utils.sha3(key + index, { encoding: 'hex' }),
  (err, result) => {
    console.log(result); On the server, the result is always 0x...0
  }
);

Does anyone know what is going on here? I'm making double sure, the Contract address is the one that is on Rinkeby and also my Infura link is one from Rinkeby.

Edit:
1. Looks like the web3 version is the problem. If I try to use web3 0.2.x on the server and hook it up with Infura provider, it works well.


texts: Not able to read data from smart contracts

texts:
I am doing PoC on Ethereum using Azure Ethereum network and Web3. I was working from last 1 month and I have created one smart contract for student management and that was working like fab. But for some reason I have deleted my Azure Ethereum network and created a new one. I have followed all the steps which I did previously, but its showing error in formal verification section like

  Error: Type int256 not supported for state variable

The same smart contract code was working fine previously. Transactions are happening from Metamask but I cant read the data from functions so I am able to figure our where the exact issue is?

~pragma solidity ^0.4.9;
contract SimpleTest {
    int public count;

    function IncCounter()
    {
        count++;
    }

    function GetCounter() constant returns(int)
    {
        return count;
    }
}

I have searched for this issue but didn't find anything valuable, can someone please help me understand the exact issue and how to resolve it quickly.


texts: Is Contract Deployment analogous to Object Instantiation?

texts:
Is deploying a contract analogous to instantiating a plaint old class in OOP and the address returned similar to the memory pointer of the OOP object? Should I be thinking of the ledge as memory to a running program?

If yes, then if I’m looking to do have something like an array of objects then I would have another contract that creates a new contract and store it’s address in array field?


texts:
I have create a truffle project with this command:
truffle unbox react

I have looked at test/simplestorage.js and add a test:
contract("SimpleStorage", accounts => {
     it("my test", async () => {
         console.log(await web3.eth.getBalance(accounts[1]));
     });
 });

I can see test accounts are credited with 100 Ether. Is there a way to choose how much ether i can put in each account test ?
Thanks


texts:
When I try to verify my contract , it returned:
Note: Contract was created during TxHash# 0x8a13fd16a810e886266d49addf46e459847d583528f966561e45abdd34a13e14
 Result: Does not match the input creation bytecode found at this address

Sorry! The Compiled Contract ByteCode for 'TokenERC20' does NOT match the Contract Creation Code for Address 0xda4e52e448f2f0fc9232d029b6bbae94963c1ca5.
 Found the following ContractName(s) in source code: TokenERC20, tokenRecipient.

Unable to Verify Contract Source Code.

I think this maybe cause by using the wrong ABI , but I don't know how to find the right one.


texts:
I can see the error message on Etherscan.
But I can't find it in getTransactionRecept().
Is there any special settings that I need set in my Genesis.json before I can see it?


texts: Why does the EVM program counter not increase by one but by two in PUSH1 opcode?

texts:
In the tutorial here, the program counter increases by 2 for a PUSH1 opcode. Then it increases by 1 for other opcodes. Why is this? Does it have to do with the opcodes size in memory? Aren't they all 256 bit?

PC: 11 STACK: [32] MEM: [], STORAGE: {}

PC: 13 STACK: [2020202020] MEM: [], STORAGE: {}

PC: 14 STACK: [2020202020, 0] MEM: [], STORAGE: {}

PC: 16 STACK: [2020202020, 54] MEM: [], STORAGE: {}

PC: 17 STACK: [] MEM: [], STORAGE: {54: 2020202020}


texts: The gas price on the Ropsten test net today rose from 0.211 ether per million gas to 1.8 ether per million gas, why?

texts: Seems like Ethereum adjusts its gas price to meet demand. How does it do this?


texts: How to remove the contract storage associated with instance variables?

texts:
Reading the Solidity docs:

delete a assigns the initial value for the type to a.

So, it just clears or resets the value of a variable (e.g., an integer to 0)?

I thought there was a way of removing things from storage, when it isn't needed?

Is it possible to have an instance variable that sometimes occupy bytes in storage, while at other times it takes no storage? If not, what mechanims can be used for this?


texts:
Possibility of Quantum Computing significantly speeding up transactions per second (TPS) / transaction rate for blockchain consensus algorithm?

For example, Shor Algorithm, the most complex quantum algorithm known to date, has ‘exponential’ speed-up over classical algorithms.

Can distributed consensus algorithms of today be speed up to scale blockchain transaction rate to an unprecendented speed?

Nathan Aw


texts: Multiple constructor functions - Will they be executed once?

texts:
let's say I have the following contract/solidity file:

pragma solidity ^0.4.20;

contract partOne {
    address public owner;
    function partOne() public {
        owner = msg.sender;
    }
}

contract partTwo is partOne{
    uint public ownerBalance;
    function partTwo() public {
        ownerBalance = 500;
    }
}

Now, constructor functions are runned once and only in the contract deployment. Will now both constructor functions run once and after that not being callable again? Or is it better to put everything in the second constructor function?


texts: Transaction receipt can be missing for mined transaction?

texts:
ETH Node: Geth
I am subscribing to new blocks, check each block & add transactions related to my node to database.
Before adding i check if transaction have receipt and the have gasPrice or not.
my question is , is it possible for a mined transaction to not have transaction receipt or empty gasPrice  when its mined or to be specific immediately after node receives the transaction.
Any guidance is much appreciated.


texts:
Gettting Error: Returned error: VM Exception while processing transaction
function getLatestPrice() public payable returns (int) {
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
          arr.push(price);// every method call current price will be pushed into an array
      emit PriceFeed(msg.sender,price);
        return price;
    }

Calling the method from the truffle console
Assign.deployed().then(instance => assign = instance)   web3.eth.getAccounts().then(function(acc){ accounts = acc })
tried:
-->assign.getLatestPrice(accounts[1], { from: accounts[1], value: 10000000000000000000 })

-->instance.getLatestPrice({from: web3.eth.accounts[0], gas: 3000000, value: 100}, function(err,res){});
-->instance.getLatestPrice({from: web3.eth.accounts[0]});


texts: Uniswap Approve Succeeded But No ETH Returned in "Swap"

texts:
I attempted to swap some eMax (using the Uniswap Swap feature) for ETH and the Approve went through, in the end I received another token (old version of token before hard fork).
It seems to be the correct token address, I seemed to have had enough ETH for gas, what happened here?
https://etherscan.io/tx/0x4808b55c6f49a377697016b1e94787c4688e196c076cc495e1383fc46d7c3008
After further research after first posting this, I realized the token I received was an old version of the eMax token before a hard fork. I never purchased/traded this token. I just received the old token of eMax in this swap transaction. How is this even possible with Uniswap swap contract? "New eMax" for ETH and receive another token? Aren't the only possibilities here that I receive ETH or nothing if the transaction fails?
https://etherscan.io/token/0xa3e059c0b01f07f211c85bf7b4f1d907afb011df?a=0x9448ec46932ef1647c332a80c1e782a239f97523

Did I do something wrong? Am I misunderstanding something? How can I prevent something like this in the future?
**edited to emphasize that I used the swap feature of Uniswap and received verification of swap with transaction address and clarification that I received old version of the token I was swapping instead of ETH


texts: what's the difference between call and just using function?

texts:
Let's say I have a contract called contractA.
It has the function:
function bla(address test) {
    // way 1. test.call(abi.encodeWithSignature("first4bytes", arg1, arg2))
    // way 2. testAddrInterface(test).functName()
}

As you can see, in the way 2 example, I just use the interface so that I can call functName on it directly instead of using way 1.
I've seen lots of places that people use way 1. Why ? what's wrong with Way 2? if you tell me way 2 contains more code and is more gas costly, I will ask: are the interfaces still included in the final code and is this the only reason why Way 1 is better ?


texts: How can I create a similar application to YouTube on Blockchain? What is the cost of it?

texts:
How can I create a similar application to YouTube on Blockchain or as a smart contract? What is the cost of it?. I am keen on picking it up as a project.
Thank you!


texts: Can I make an ethereum token that runs a certain function every 15 seconds?

texts:
I have a rinkeby token, and I wanted to add "merged mining" when someone mines a block, they get awarded 0.25 of that token.

function issueBlockReward() {
balanceOf[block.coinbase] += 0.25;

The code above (I am missing the bottom closing tag)
Awards the miner of an ethereum block 0.25 token.
How can I make this run every 15 seconds?
My pragma version is v0.4.21+commit.dfe3193c
Thanks!


texts:
Whilst downloading the blockchain which has taken me approximately a week to get to block 1.09 mil, I received a message from geth.exe after a reboot around 1050999 -1060888

  You're one of the lucky few that will try out the JIT VM (random). If
  you get a consensus failure please be so kind to report this incident
  with the block hash that failed. You can switch to the regular VM by
  setting --jitvm=false

Any idea as to what this means ?  It's a Just In Time Virtual Machine? after reading and reading I'm surmising this has to be some sort of fork? Correct me if I'm wrong , thanks for the feedback ! Due to my lizard brain I rebooted the sync.


texts: Is it required to use multiple Etherem accounts to send transactions on behalf of customers to avoid pending transactions?

texts:
We are developing an Ethereum based exchange. In our project, customers put their orders to send ETH or ERC20 tokens to others, and we currently do these transactions via our Ethereum account on their behalf. On issue that we faced with was pending transactions. In our first tests, we created some transactions after just some seconds, and found out while the previous transactions are processing (pending), other transactions will be kept pending too due to the previous transaction status and the nonce the previous one had.
The message I receive in Etherscan:
There is a Pending txn with a lower account nonce. This txn can only be executed after confirmation of the earlier Txn Hash

Please help me to know is this result true in your mind and practices too? And if so, what is the solution to avoid this problem? Do we need to use multiple accounts or is there any other solution?


texts: I am looking to get funding from the ECF Network  for an Ethereum project. They ask for a PGP key under the apply form ("Please make sure you paste your pgp public key here: ", but nowhere on their website or online can I find what they mean (I know it is an encryption key...but to what?). I don't want to ask before I ask for funding because I don't want to risk losing any chance of receiving funding due to perceived incompetence. Can anyone help explain what is required here?


texts:
According to Whitehat Withdrawal contract - Update and Next Steps and Whitehat Withdrawal contract - Last update before deployment, the Goodies will be deploying the withdrawal contracts whetcwithdraw.sol, authorized_addresses.sol and whauthorizeaddress.sol to facilitate the withdrawal of Classic Ethers (ETCs) based on your The DAO tokens DAO balance at block 1,919,999 just prior to the hard fork.

How do I use these contracts to withdraw my Classic Ethers (ETC) from the withdrawal contract?

The DAO Refunds

How do I convert my The DAO tokens into ethers using the withdrawal contract after the hard fork?
How do I get a refund for the amount I paid in excess of 1 ether to 100 The DAO tokens
How do I get a refund for my The DAO tokens that was split into a child DAO?
[THIS] How do I convert my The DAO tokens into ethers on the Ethereum Classic chain?
How to conditionally send ethers to another account post-hard-fork to protect yourself from replay attacks

See also:

How To Use sign() for the Whitehat Withdrawal
Reddit - Whitehat Withdrawal contract - Update and Next Steps
Reddit - Whitehat Withdrawal contract - Last update before deployment
Reddit - Whitehat Withdraw contract is deployed at 0x9f5304da62a5408416ea58a17a92611019bd5ce3
ETC withdraw contract to be reviewed
WH Funds Movement
How can I verify that my The DAO token balance is correct when the Goodies provide an ETC refund on the Ethereum Classic chain?
How do I sync the Ethereum Wallet and/or geth to the Ethereum Classic chain without affecting my hard-forked Ethereum chain?
https://gastracker.io/ - ETC Chain Block Explorer


texts: Pulling ETH-BTC quotes from coinbase programmatically

texts:
I am using the coinbase 2.1.0 python api to pull prices.  I have been able to pull BTC-USD prices but not ETH-BTC.  My code is:

from coinbase.wallet.client import Client

api_key = ""
api_secret = ""
api_version = "2018-07-07"
client = Client(api_key, api_secret)
askBTC = client.get_buy_price(currency='USD',  currency_pair = 'BTC-USD')
eth = client.get_sell_price(currency='BTC', currency_pair = 'ETH')

The last line gives the error
coinbase.wallet.error.NotFoundError: APIError(id=not_found): Not found

Thoughts?