texts:
I'm confused about how to manage/calculate with WEI in a web3 application.
So far I found:

BigInt: This is JS native and it works with large quantities (e.g. 10000000000000000000000). But it doesn't have out of the box utilities like e.g. converting to hex.

BigNumber: This is provided by ethers:

Many operations in Ethereum operation on numbers which are outside the range of safe values to use in JavaScript.
A BigNumber is an object which safely allows mathematic operations on numbers of any magnitude.

Given this description, and that it's dedicated to Ethereum, I thought this must be it, but it actually doesn't work with large numbers:
// Numbers outside the safe range fail:
BigNumber.from(Number.MAX_SAFE_INTEGER);
// Error: overflow (fault="overflow", operation="BigNumber.from", value=9007199254740991, code=NUMERIC_FAULT, version=bignumber/5.0.8)

Aside of that, for WEI I probably need integers, not floating point.
So what's the recommended way to deal with WEI?
In the ideal case I'd like something that not only represent big numbers but actual WEIs and has built in functionality to convert safely to and calculate with GWEI or ETH out of the box, but this is not a must.
Using Typescript, but it probably isn't relevant.
Edit: I found another library: BigNumber.js. This seems to do what I expect. It can be converted to string to interact with web3.js.


texts: Using a "worker" or "worker name" is often an option when you do pool mining. It is often exemplified by "rig1". But how do you create one, and what is its use?


texts: ERC20 Smart contract that can pick winning address based on balance

texts:
I want to create a smart contract that has zero decimal places, i.e. whole integer balances only. The idea is that 1 token represents a ticket. It would be possible for people to buy multiple tickets. So basically an ERC20 with no decimal places, but with one extra function.

I want to be able to randomly select a winning address; getWinner(r), but the winner should be in proportion to the tickets an address owns. So for example; if A owns 1 ticket, B owns 3 tickets; then B is 3 times more likely to win. The problem I'm having is how to do this for a large number of addresses, I don't want to iterate. I guess I could store the address for every ticket in an array; [ A, B, B, B ] but that seems kind of inefficient, also I would have to move things around to plug holes on balance changes and deletes.

Is there a better way?


texts: Issue in Integrating metamask to chrome browser in mobile

texts:
I am trying to create an DeFi app by integrating the MetaMask wallet.
Desktop
The DeFi app works fine with the MetaMask integration
Mobile
I have my MetaMask setup in my Android mobile. When I tried the same DeFi App in my Android mobile, it is not connecting with the MetaMask at my mobile.
I have not tried in iOS
I am not sure whether I am missing anything in the mobile side. Please assist me in integrating MetaMask with mobile chrome browser.


texts: Analysis of same deployed contracts in the network

texts: Is there a way to analyze how many the exactly the same Solidity contracts were deployed into the network?


texts: What is the maximum size of string which we can store on solidity?

texts: Is there a limit to the size of a string that we can store on the Ethereum blockchain?


texts: Cannot reproduce Etherscan verified compilation for 0.6.6 contract

texts:
I'm trying to reproduce the following contract compilation on Etherscan: https://etherscan.io/address/0x7a250d5630b4cf539739df2c5dacb4c659f2488d#code.

Runtime bytecode on-chain
I can get the runtime bytecode on chain by calling eth_getCode for the contract address from a JSON RPC client connected to mainnet.
Here is the bytecode I get:
60806040526004361061018f5760003560e01c80638803dbee116100d6578063c45a01551161007f578063e8e3370011610059578063e8e3370014610c71578063f305d71914610cfe578063fb3bdb4114...

Runtime bytecode (Etherscan)
Here, looking at the etherscan contract information in the link above, I notice 3 key things: compiler version (0.6.6), optimisation runs (999999) and evm version (istanbul).
So I set up Solidity compilation as follows:
{
    "language": "Solidity",
    "sources":
    {
        "uniswap.sol":
        {
            "urls":
            [
                "./uniswap.sol"
            ]
        }
    },
    "settings": {
        "optimizer": {
            "runs": 999999
        },
        "evmVersion": "istanbul",
        "outputSelection": {
            "*": {
                "*": [ "evm.deployedBytecode" ]
            }
        }
    }
}

and ran with:
solc --standard-json --allow-paths .

But I'm getting slightly different bytecode:
60806040526004361061018f5760003560e01c80638803dbee116100d6578063c45a01551161007f578063e8e3370011610059578063e8e337001461131e578063f305d71914611406578063fb3bdb4114...

What could be wrong in the reproduction and how may I amend it? Can constructor arguments change runtime bytecode if immutable values are used?


texts: I understand that Blockchain is coming, it has lot of potential and its complex. What is its adoption rate in enterprises ? Is it only related to Authentication or Verification ?


texts:
I sent tokens (veri) from my ether wallet to meta mask address ether scan shows the transaction but i cannot see them or send them.
If you have a solution please explain as if i were 4 yr old.
cheers
james


texts:
I'm newbie having a few Eth issues, to begin with:
Trying to run Ethereum Wallet 0.8.0 on my x64 linux my internet connection becomes intermittent. If a ping is left running (say 8.8.8.8), when the EW starts I start getting "Destination Port Unreachable" with maybe 1 in 4 or 5 pings still replying. Nothing else breaks my wifi connection like this.

In the terminal I started EW from messages say "mini-api.cryptocompare.com’s server DNS address could not be found". When I CTRL-C to stop EW the pings go back to normal.

Could please do with some steps to troubleshoot or clue where to look. Testing with a wired connection is difficult.


texts: Can I write and deploy smart contracts using Jaxx wallet

texts: I am quite new to Ethereum development . I would like to know if i can create new smart contracts using solidity programming language and deploy them to the network using Jaxx wallet . Right now I have downloaded Ethereum wallet from github for this purpose , but it takes a long time as it downloads all the blocks


texts: How can I retrieve the internal transaction of transfer ether by contract invoke?

texts:
I want to retrieve the internal transactions of specified tx, the result should be same as "https://api-ropsten.etherscan.io/api?module=account&action=txlistinternal" api request reuslt.

So I want to know how to do it. There are anyone can give me some example golang code? Thanks very much.


texts:
I tried to connect to an ethereum node by using remix. It means that I am using http and not https. However, I receive same error message:

Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

Is there any other solution for this problem ? I searched in internet and found only one answer : use of http, that in my  case I receive same error message.


texts: Are these two implementations of safe ERC-20 equivalent?

texts:
These implementations from Uniswap and Compound seem both to have been written to account for the missing return value bug - an issue with some ERC20 token contracts that don't return a boolean when transfer or transferFrom is called.
From Uniswap's TransferHelper.sol
function safeTransfer(address token, address to, uint value) internal {
  // bytes4(keccak256(bytes('transfer(address,uint256)')));
  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
  require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}

From Compound's Erc20.sol:
function doTransferOut(address payable to, uint amount) internal {
    EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
    token.transfer(to, amount);

    bool success;
    assembly {
        switch returndatasize()
            case 0 {                      // This is a non-standard ERC-20
                success := not(0)          // set success to true
            }
            case 32 {                     // This is a complaint ERC-20
                returndatacopy(0, 0, 32)
                success := mload(0)        // Set `success = returndata` of external call
            }
            default {                     // This is an excessively non-compliant ERC-20, revert.
                revert(0, 0)
            }
    }
    require(success, "TOKEN_TRANSFER_OUT_FAILED");
}

The question: are they equivalent?


texts: Upgrading to solidity version 0.5.0 getting deployment failed error with same smartcontract perfectly deployed on 0.4.24

texts:
The same smart contract is running smoothly in solidity version 0.4.24 but now when I update the solidity version and solving a lot of bugs inside my smart contract I intended to deploy that in ganache-cli and now getting this below error.
Note that I have 4 contracts with this below deloy_all file.

2_deploy_all.js

    const Manager = artifacts.require("Manager");
    const Delegate = artifacts.require("Delegate");
    const Interface = artifacts.require("Interface");
    const ExternalStorage = artifacts.require("ExternalStorage");

    module.exports = function(deployer, network, accounts) {
      deployer
        .deploy(
          Delegate
        )
        .then(function() {
          return deployer
            .deploy(
              Manager,
              Delegate.address
            )
            .then(function() {
              return deployer
                .deploy(
                  ExternalStorage
                )
                .then(function() {
                  return deployer
                    .deploy(
                      Interface,
                      Manager.address,
                      ExternalStorage.address
                    )
                });
            });
        });
    };

Error

2_deploy_all.js
===============
Error:  *** Deployment Failed ***

"Delegate" is an abstract contract or an interface and cannot be deployed.
 * Import abstractions into the '.sol' file that uses them instead of deploying them separately.
 * Contracts that inherit an abstraction must implement all its method signatures exactly.
 * A contract that only implements part of an inherited abstraction is also considered abstract.

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

Truffle v5.0.1 (core: 5.0.1)
Node v9.6.

  Note : I have tried making IDelegate contract from Delegate contract and  deploy it but the result is same.

I need help at this point to deploy my all smartcontract in version 0.5.0


texts:
I have read at many places

  peoples require someone with an excellent experience to develop and
  deploy a smart contract for ICO

Here my question is, what exactly smart contract is here?

Does it mean to create a new ETH token? Or develop a new coin itself from zero?

How exactly someone can create his / her ERC20 token based on ETH blockchain?


texts: Workaround for testRPC bug where amounts spent multiple time with library calls?

texts:
Using testRPC the amount transferred is multiple times of the msg.value if a library call is involved.

There is bug report and it was raised
here and
here as well.

It's a well documented, long standing bug in testRPC and as of testRPC v4.0.1 it's still there.

Anyone was able to come up with a workaround?


texts: How to manipulate value stored in array (Solidity smart contract)?

texts:
I'm currently fighting with a seemingly very simple issue.
I just try to increment the value stored in an array in a Solidity contract.

uint256[] public barLengthToBarAmtForSale;

I initialise the array in the constructor...

uint16 counter = uint16(0);
    while(counter <= 10) {
        barLengthToBarAmtForSale.push(uint256(0));
        counter++;
    }

Later I try to increment values in this array:

uint16 _length = 5;
barLengthToBarAmtForSale[_length]++;

But the smart contract doesn't compile bc of this line :(

What might be the reason?

Thank you.

Edit: sorry for the misleading name of _length parameter. It's not the length of the array. It's just an example value.
I just checked my implementation using remix and there it compiles. However, when using truffle migrate, it doesn't work.


texts:
How I do I push the first value to this:

  struct Balance {
    address owner;
    uint amount;
    DeepBalance[] deepBalance;

  }

  struct DeepBalance{
    address swap ;
    uint amount ;
  }
Balance[] balances;

this doesn't work, but is what I feel in the bottom of my heart is close:

DeepBalance[] memory deepBalance;
balances.push(Balance({
  owner: 0,
  amount: 0,
  deepBalance: DeepBalance({
      swap: 0,
      amount: 0
  })
}));


texts:
I'm looking to build a smart contract with a function which is able to generate a unique and limited amount of ERC721 tokens based on an input string. I also want to be able to look up all the tokens based on the input string.

How should I go about approaching this complying with best practices?

Example:
I input the string "Cow", to a function in the smart contract.
Next, I should be able to create a parent token which represent the string, and each child token should have a numerical ID within the range 1-50.


texts: Problem with Truffle Console: Cannot read property 'call' of undefined

texts:
I´m having problem with the basic HelloWorld example coded in Solidity and managed with truffle with testrpc.

  pragma solidity ^0.4.2;

  contract HelloWorld {
     uint public balance;

  function HelloWorld() {
         balance = 1000;
     }
  }

>  truffle(development)>
> HelloWorld.deployed().balance.call().then(console.log) TypeError:
> Cannot read property 'call' of undefined
>     at evalmachine.<anonymous>:1:30
>     at ContextifyScript.Script.runInContext (vm.js:35:29)
>     at Object.exports.runInContext (vm.js:67:17)
>     at TruffleInterpreter.interpret (c:\Users\whha\AppData\Roaming\npm\node_modules\truffle\lib\repl.js:128:17)
>     at bound (domain.js:280:14)
>     at REPLServer.runBound [as eval] (domain.js:293:12)
>     at REPLServer.<anonymous> (repl.js:545:10)
>     at emitOne (events.js:96:13)
>     at REPLServer.emit (events.js:188:7)
>     at REPLServer.Interface._onLine (readline.js:239:10) truffle(development)>

The problem looked similar to
this thread, but it does not solve my problem:

The contract is properly deployed and has a valid JSON document, I really don´t understand why I cannot access its members. The only one that return value is a constructor.

truffle(development)> HelloWorld.deployed().constructor
[Function: Object]

Any ideas??


texts: Using Solidity, how can I execute the transferFrom function of an ERC20 Token?

texts:
I am trying to accept ERC20 Tokens as payment in a contract. As I understand it the sender will have to use the approve function to give my contract an allowance first. So far so good. What I do not understand is how does my contract call the transferFrom function to credit itself.

Specifically I want to test if the 'allowance' approved for my contract is equal to a value and if the remaining balance of the sender is equal or greater than my contract's allowance. Conditionally to that I want to execute the 'transferFrom' function of the ERC20 Token.

I am trying to do the following:

if (
         && _Token.call(bytes4(sha3("allowance(owner, this)"))) = 100
         && _Token.call(bytes4(sha3("balanceOf(owner)"))) >= 100
         )
         {
         _Token.call(bytes4(sha3("transferFrom(owner, this, 100)")));

But the Myst compiler says Expected primary expression.

 && _Token.call(bytes4(sha3("allowance(owner, this)"))) = 100

Many thanks.


texts: What are remappings and how do they work in solidity?


texts: Signing message with private key and verifying signer in smart contract

texts:
I have a smart contract that provides a message to sign and then validates the signer of the message. Something like:

   mapping(address => uint) public userNonce;

function getSigner(bytes32 message, bytes32 r, bytes32 s, uint8 v)
    public
    pure
    returns (address)
{
    bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", message));
    address signer = ecrecover(prefixedHash,v,r,s);
    return signer;
}

function getMessageToSign(address user, address _operator)
    public
    view
    returns (bytes32)
{
    return keccak256(abi.encodePacked(
        bytes4(0xe18546ee),
        address(this),
        userNonce[user], // sequential nonce
        _operator
    ));
}

function prove_me (bytes32 message, bytes32 r, bytes32 s, uint8 v, address _operator)
    public
{
    address signer = getSigner(message, r, s, v);
    bytes32 proof = getMessageToSign(signer, _operator);
    require(proof == message);
    userNonce[signer] = userNonce[signer] + 1;
    // do something on behalf of user
    hasUserAllowed[signer] = true;
}

Testing above with dummy private-key and address.

I get a message to sign from smart contract :

  dataHash =
  "0x3c6819779a3c0a163d93e2e1e1168fb5ab424217555132ea356d491002c84e7f"

  user1Addr = "0x72f27f62998bc1a2929a72bf753b6a335abd46c0"

  user1PvtKey
   = "0xc73c6b7ad8e821a303871e8a63f8a53c9b6b0cf3977becd94032f3ff7c3055c1"

I sign it using private key belonging to user1:

web3.eth.accounts.sign(dataHash, user1PvtKey);

But when I pass corresponding r,s,v to the getSigner method, I get a different signer (0x2ad05a181F51975C1bc79b6B1eC1Ab9A86a3fE24)

I know this works if I use web3.sign but that requires an unlocking account with personal however I prefer signing using the private key.

The signature is different using web3.sign than web3.eth.sign.

PS: I know that web3 updated the signing method including chain code as well. But since I can not update my smart contract, how can I sign the message using a private key and smart contract verifies the correct owner?


texts:
I would like to run two nodes in the same machine which has to share the same genesis file. I tried the following.

Terminal 1 (Node 1)

$ ./geth --datadir "node1/" init genesis.json

It shows successful

$ ./geth --datadir "node1/" --port 21212 console

  eth.accounts

[]

It shows empty, eventhough there are three accounts are there in genesis file.
Why it shows like that?

If I put like below then it works fine

Terminal 1 (Node 1)

$ ./geth init genesis.json

It shows successful

$ ./geth console

  eth.accounts

[0Xadbee , 0xabde, 0xabcde]


texts: web3.py does not print Events `ValueError: No matching functions found`

texts:
Goal: I want to print logs of the smart contract, like I do on web3.js, using web3.py.

On web3.js side, following code piece works:

var event = myContract.LogJob({}, {fromBlock:0, toBlock:'latest'});
event.watch(function(error, result) {
  console.log(JSON.stringify(result));
});

But on the web3.py side following line returns: [].

=> On my smart contract I did not use the emit keyword before (event Deposit(...)), could it be the reason?

Example Small Contract Piece:

pragma solidity ^0.4.20;

contract Contract {

  function deposit(bytes32 _id) payable {
     LogJob(msg.sender);
  }
  event LogJob(address indexed _from);
}

--

web3.py call:

#!/usr/bin/env python -W ignore::DeprecationWarning

from __future__ import print_function
import os, sys
from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider

os.chdir(sys.path[0]);

web3 = Web3(HTTPProvider('http://localhost:8545'))

fileAddr = open("address.json", "r")
contractAddress = fileAddr.read().replace("\n", "")

with open('abi.json', 'r') as abi_definition:
    abi = json.load(abi_definition)

Contract = web3.eth.contract(contractAddress, abi=abi);

transfer_filter = Contract.on('LogJob', {'filter': {'clusterAddr': clusterAddress}})
print(transfer_filter.get())

Returns:

Traceback (most recent call last):
  File "getClusterInfo.py", line 54, in <module>
    transfer_filter = Contract.on('LogJob', {'filter': {'clusterAddr': clusterAddress}})
  File "/usr/local/lib/python2.7/dist-packages/web3/utils/decorators.py", line 13, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/web3/contract.py", line 345, in on
    argument_filter_names,
  File "/usr/local/lib/python2.7/dist-packages/web3/contract.py", line 647, in _find_matching_event_abi
    raise ValueError("No matching functions found")
ValueError: No matching functions found

=> On web3.py can we also filer events from specific blockNumber?


texts: Merkle-Patricia-Trie-Root is wrong. How to get transaction proof? in Python3

texts:
I am trying to calculate proof that a specific Transaction is mined with a specific difficulty. So far I got the Block via JSON_RPC and all its Transactions.

I am Using the trie Library for Python 3.6

For the sake of testing everything I'm using a Block with no Transactions.

txTrie = HexaryTrie(db={}) #make new trie
print('txRoot: \t', block['transactionsRoot'])
print('txTrieRootS: \t 0x' + txTrie.root_hash.hex())

For this Code both Print-Statements return the same value.

Now I run the same code with a Block that contains one transaciton

txTrie = HexaryTrie(db={}) #make new trie
txTrie[transactionIndex] = transacionHash #add the transaction to the Trie
print('txRoot: \t', block['transactionsRoot'])
print('txTrieRootS: \t 0x' + txTrie.root_hash.hex())

And now the two print statements don't return the same value.

Can anyone help me how to get Proof that a Transaction is in a specific Block at a specific index? I just can't figure this out.

EDIT:
Here is the full code:

import requests
import json
import lib.mpt as mpt
import lib.rlp as rlp
from trie import HexaryTrie

url = 'https://mainnet.infura.io/ffn6QLIJrYtke3b07YLp'

headers = {
    "Content-Type": "application/json"
}
data = {}
data['jsonrpc'] = '2.0'
data['id'] = 1
data['method'] = 'eth_getBlockByNumber'
data['params'] = [hex(100004), True]
data = json.dumps(data)

response = requests.post(url, headers=headers, data=str(data) )
block = json.loads(response.text)
result = block['result']
transactions = result['transactions']
print('txRoot: \t', result['transactionsRoot'])

txTrie = HexaryTrie(db={})
print('txTrieRootS: \t 0x' + txTrie.root_hash.hex())
for x in transactions:
    txTrie[b'0'] = bytes.fromhex(x['hash'][2:])
    print(txTrie[str.encode(x['transactionIndex'][2:])])
print('txTrieRootA: \t 0x' + txTrie.root_hash.hex())


texts: Crowd funding smart contract where it returns funds to users if funding amount isn't met?

texts:
Is there a smart contract where you can create a crowd funding campaign. Say I wanted to raise 1000 ETH within 30 days or X number of blocks. If the 1000 eth goal isn't reached, it will return all the funds back to the users that sent it to my smart contract. Does something like this exists? And what issues might one run into when doing something like this?

I'm curious to how funds are returned. Say if 10000 addresses sent me random amounts of eth. Wouldn't gas cost alot as it would have to loop through all those 10000 addresses to do a refund?


texts: Truffle: Error: Could not find a compiler version matching 0.5.0

texts:
I wonder why I get the error when I have v0.5.0 everywhere and do the following:

In my Action.sol:
pragma solidity ^0.5.0;

In Migrations.sol:
pragma solidity >=0.5.0 <0.6.0;

When running truffle compile I get:

Error: Could not find a compiler version matching 0.5.0. Please ensure you are specifying a valid version, constraint or build in the truffle config. Run `truffle compile --list` to see available versions.

In test-a-smart-contract-with-truffle/truffle-config.js:

  compilers: {
    solc: {
      version: "0.5.0",

In /usr/local/bin/truffle:

compilers: {
      solc: {
        version: "0.5.0",
        settings: {
          optimizer: {
            enabled: false,
            runs: 200
          },
          evmVersion: "byzantium"
        }
      },
      vyper: {}
    },

But when I run truffle compile --list I get:

[
 "0.5.4",
 "0.5.3",
 "0.5.2",
 "0.5.1",
 "0.5.0",
 "0.4.25",
 "0.4.24",
 "0.4.23",
 "0.4.22",
 "0.4.21",
 ".. and 38 more. Use `--all` to see full list."
]


texts: How to rewrite this variable in solidity?

texts:
I have this code snippet that i want to modify a bit
uint256 public constant decimals = 9;

uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 10**9 * 10**DECIMALS;

uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);

uint256 private constant MAX_SUPPLY = ~uint128(0);  // (2^128) - 1

uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;

mapping (address => mapping (address => uint256)) private _allowedFragments;

What i try to achieve is make this code work with a totalsupply of 300 Token, this code produces 1 billion token.
Im asking about the line
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 10**9 * 10**DECIMALS;

this cretes a contract with 1 billion token, how can i change it to produce 300 token?
I tried this
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 300;

and I also tried
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 300 * 1**DECIMALS;

But it somehow doesnt work the way i want to, it creates 300 coins but when i call the burn function and burn 1 Token- i can see that the totalSupply is 299 token but i dont see the decimals that are beeing burned.
So basically if i have 1000 token with 10 tokenholders that hold 100 token each, after i burn 100 token everyone only holds 90 token.
Now if I have only 300 token and 300 token holders- the tokenholders should have after the burn about 0.998 token or so but when i ran it in remix, the balance still shows 1 token


texts: Mist 0.5.1 synchronization problem on Windows

texts:
I'm running Mist on Windows 10. I have been trying to download the blockchain since yesterday and the process is too slow and cumbersome.
I switched off the firewall and I set the clock and I started the client. Although, when I start the client I reach 10-20 peers, this number drops, and most of the time is between 0-4. I set again the clock, but this does not improve. Thus, I restart the client.
At moment 378093 blocks left.
Initially it was faster, now it seems to be very slow (< 25-100 blocks/min).
No special error in Geth, only when the peer number drops to 0, it appears a synchronization error.
Any idea?


texts: Return an array of structs using events?

texts: I wan’t my function to spit out an array of structs. I know this is not straightforwardly possible. What is the best way for me to proceed?  Should I loop through my array in my function and trigger an event each time to return the arguments of each struct separately? Should I create a large json object by looping through my array and spit it out as a string?  Is there a more straightforward way of doing this?


texts: How to set dynamic buy and sell price for my token?

texts: I have built a simple erc-20 token. I used the code given on ethereum.org code as a reference. There they have talked about setting the price of my token. But how do I set it dynamically, as in automatically change the buy and sell price based on market ? Where do I get this price from ? Ethereum.org has said something about data feeds, what is that ? and How do you use it ?


texts:
I am looking for the less gas consuming random number generator. I think i need an oracle but can you direct me to the best ?

Thanks


texts:
I hear these two terms interchangeably Consortium Blockchain and Permissioned Blockchain. Are they the same?
If not, can you please show the difference between them.

P.S. Since there exists no general (StackExchange) Blockchain community, I am asking my question here.


texts: Is there a more elegant way to do an aggressive multi-send?

texts:
I understand there are many approaches to do multisend but for me timing is a priority and I do not want to stop the transaction if a address.send fails.

   function multiSend() internal isAdmin {
     for (uint initial = iter; iter < initial + 100 && iter < sendList.length; iter++) {
         if(!sendList[iter].send(valueMap[sendList[iter]])) {}
     }
   }

addresses in the sendLinst need to be sent ether mapped to them in valueMap.

iter is set to 0 initially, so the first time above function is called the first 100 (or length of array) addresses will be sent their mapped amounts. The nest time above function is called the next 100 addressed are paid and so on.

changes to sendList and valueMap are locked at this point and iter is not manipulated anywhere else. The function still does its job when the address reverts or runs out of gas.

this it what that looks like

I know I have ignored a bunch of security recommendations with this but are there any obvious security concerns with this approach ?


texts: Contract gives erc20 tokens based on an event, to an empty wallet

texts:
I have a new wallet address and no ETH.

I want to be able to request an amount of 10 erc-20 tokens. Because I do not have any eth on this wallet, I want to be able to get the tokens onto my wallet via this contract (maybe mint them - after approval?).

What is the best approact to get tokens to a virgin wallet? Sign the contract?
Making any requests requires ether on my virgin wallet. At the expense of the contract holder, is it possible to initiate a transfer by the contract (in order to the contract to spend the tokens there?). What happens after the tokens are transferred? Can I retransfer them if i do not have any eth?

Is there a better approach?

Thanks


texts: Can two addresses ever have the same sorting value?

texts:
From uniswap documentation it says:
token0
function token0() external view returns (address);
Returns the address of the pair token with the lower sort order.

token1
function token1() external view returns (address);
Returns the address of the pair token with the higher sort order.

As far as I understand, in order to compare them in javascript, I would need to cast them to BigInt, i.e.
let token0;
let token1;

const address0 = BigInt('0xDB17618B140EFCB8a07BC8e9b88920de1daE6C87');
const address1 = BigInt('0x4d4CC29b9C4E413CFe5f898E16280f11db57E186');

if (address0 < address1) {
  token0 = address0;
  token1 = address1;
} else {
  token0 = address1;
  token1 = address0;
}

Two questions:

Is there ever a case where two distinct addresses will have the same sorting value?
If yes, then should I be using <= or < here?


texts: My cutom RPC meta mask created account is not showing in terminal

texts:
I have installed geth and created genesis.json and run my own private eth network. I started my rpc using

geth --rpc --rpcport 5200 --rpcaddr 192.168.1.99 --datadir ./private

Then I connected to this network in meta mask and then created a new account there. Then I came back to my terminal stopped rpc and then I do

geth --datadir ./private --networkid 1114 console 2>> eth.log

then I check using web3.eth.accounts it doesn't display my meta mask created address. So what is the proper way to create meta mask account which also reflects in my custom created network?


texts: there is some error when Depoly SimpleMultiSig

texts:
I want to use the contract https://github.com/christianlundkvist/simple-multisig to deploy a multi-sig contract, but whatever I change the gaslimit or value in Remix, deploy aways failed. One of the deploy is https://rinkeby.etherscan.io/tx/0x80d87edb68a953e71f07491119f23ddd2616d00462fe7168fc9078cade254b5c.

Then I use web3j to deploy the contract but get the error"Transaction has failed with status: 0x0. Gas used: 111376. (not-enough gas?)", one of the deploy isishttps://rinkeby.etherscan.io/tx/0x2fa0c13ff3d491253a2166de24ce5a535607ed8bbf42a6e77360bf01713cb636

can any one help me. blow is the code.

contract SimpleMultiSig {

// EIP712 Precomputed hashes:
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)")
bytes32 constant EIP712DOMAINTYPE_HASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;

// keccak256("Simple MultiSig")
bytes32 constant NAME_HASH = 0xb7a0bfa1b79f2443f4d73ebb9259cddbcd510b18be6fc4da7d1aa7b1786e73e6;

// keccak256("1")
bytes32 constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;

// keccak256("MultiSigTransaction(address destination,uint256 value,bytes data,uint256 nonce,address executor,uint256 gasLimit)")
bytes32 constant TXTYPE_HASH = 0x3ee892349ae4bbe61dce18f95115b5dc02daf49204cc602458cd4c1f540d56d7;

bytes32 constant SALT = 0x251543af6a222378665a76fe38dbceae4871a070b7fdaf5c6c30cf758dc33cc0;

  uint public nonce;                 // (only) mutable state
  uint public threshold;             // immutable state
  mapping (address => bool) isOwner; // immutable state
  address[] public ownersArr;        // immutable state

  bytes32 DOMAIN_SEPARATOR;          // hash for EIP712, computed from contract address

  // Note that owners_ must be strictly increasing, in order to prevent duplicates
  constructor(uint threshold_, address[] owners_, uint chainId) public {
    require(owners_.length <= 10 && threshold_ <= owners_.length && threshold_ > 0);

    address lastAdd = address(0);
    for (uint i = 0; i < owners_.length; i++) {
      require(owners_[i] > lastAdd);
      isOwner[owners_[i]] = true;
      lastAdd = owners_[i];
    }
    ownersArr = owners_;
    threshold = threshold_;

    DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAINTYPE_HASH,
                                            NAME_HASH,
                                            VERSION_HASH,
                                            chainId,
                                            this,
                                            SALT));
  }

  // Note that address recovered from signatures must be strictly increasing, in order to prevent duplicates
  function execute(uint8[] sigV, bytes32[] sigR, bytes32[] sigS, address destination, uint value, bytes data, address executor, uint gasLimit) public {
    require(sigR.length == threshold);
    require(sigR.length == sigS.length && sigR.length == sigV.length);
    require(executor == msg.sender || executor == address(0));

    // EIP712 scheme: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md
    bytes32 txInputHash = keccak256(abi.encode(TXTYPE_HASH, destination, value, keccak256(data), nonce, executor, gasLimit));
    bytes32 totalHash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, txInputHash));

    address lastAdd = address(0); // cannot have address(0) as an owner
    for (uint i = 0; i < threshold; i++) {
      address recovered = ecrecover(totalHash, sigV[i], sigR[i], sigS[i]);
      require(recovered > lastAdd && isOwner[recovered]);
      lastAdd = recovered;
    }

    // If we make it here all signatures are accounted for.
    // The address.call() syntax is no longer recommended, see:
    // https://github.com/ethereum/solidity/issues/2884
    nonce = nonce + 1;
    bool success = false;
    assembly { success := call(gasLimit, destination, value, add(data, 0x20), mload(data), 0, 0) }
    require(success);
  }

  function () payable external {}
}


texts: address payable[] public causing SWC 110 and execption state

texts:
This is the output of mythril
==== Exception State ====
SWC ID: 110
Severity: Medium
Contract: XXXXXXX
Function name: recipients(uint256)
PC address: 2067
Estimated Gas Usage: 1089 - 1184
An assertion violation was triggered.
It is possible to trigger an assertion violation. Note that Solidity assert() statements should only be used to check invariants. Review the transaction trace generated for this issue and either make sure your program logic is correct, or use require() instead of assert() if your goal is to constrain user inputs or enforce preconditions. Remember to validate inputs from both callers (for instance, via passed arguments) and callees (for instance, via return values).
--------------------
In file: something.sol:42

address payable[] public recipients
--------------------
Initial State:

Account: [CREATOR], balance: 0x0, nonce:0, storage:{}
Account: [ATTACKER], balance: 0x0, nonce:0, storage:{}
Account: [SOMEGUY], balance: 0x0, nonce:0, storage:{}

Transaction Sequence:

Caller: [CREATOR], calldata: , value: 0x0
Caller: [ATTACKER], function: recipients(uint256), txdata: 0xd1bc76a10000000000000000000000000000000000000000000000000000000000000000, value: 0x0

Here is the relevant code:
address payable[] public recipients;

...

modifier onlyOwner {
    require(
        msg.sender == owner,
        "Only the contract owner can call this function"
    );
    _;
}

function addRecipient(address payable payee) public onlyOwner {
    recipients.push(payee);
}

Can anybody explain why calling recipients causing the exception? I am not able to understand. The only thing I can understand is decoding tx data with type address gives 0x0000000000000000000000000000000000000000, is that relevant?


texts: Solidity function not returning - keeps returning tx receipt

texts:
I try to call my Solidity function:

function getVehicleDetails(string _vin) returns (string _vln, uint _year, string _make, string _model, string _colour) {
    Vehicle vehicle = vehicles[_vin];
    if (vehicle.year == 0)
        throw;

     _vln = vehicle.vln;
    _year = vehicle.year;
    _make = vehicle.make;
    _model = vehicle.model;
    _colour = vehicle.colour;
}

Here's the geth command:

instance.getVehicleDetails("vin_101",{from:web3.eth.accounts[1]})

  returns "0x6cf98ab5b77bfa0397ee6eaa046f85a133c5a3ef636c59a56b4308dc73fb20fd"

i.e. it keeps returning a tx receipt!

Here's how I create a vehicle:

function setVehicleDetails(string _vin, string _vln, uint _year, string _make, string _model, string _colour) owneronly {
    Vehicle vehicle = vehicles[_vin];
    if (vehicle.year == 0)
        throw;
    vehicle.vln = _vln;
    vehicle.year = _year;
    vehicle.make = _make;
    vehicle.model = _model;
    vehicle.colour = _colour;
}

I call this in geth with:

instance.registerVehicle("vin_101","vln_101",2004,"ferrari","convertible","black",{from:web3.eth.accounts[0],gas:4000000})

What am I doing wrong?

All I want to do is read the return values from getVehicleDetails and it just refuses to!

I'm on testrpc.


texts: I have a question regarding VerifySeal function in Geth source code. If I understood correctly, it verifies if block has valid seal regarding the PoW algorithm. The arguments that function takes are chainReader and block header. Is there a way to get the body of the block that is being verified? I know that chainReader has method GetBlock(), but it needs the hash of the block and I don't know how to obtain it. On the other hand, I'm not sure if the block that is being verified is on the blockhain yet, so perhaps this method won't even work?


texts: Do transactions/call to functions of smart contracts ever happen in parallel/concurrent manner?

texts:
I am trying to set up a smart contract by which two parties need to agree upon a state. For that, for security, I require one party to say the state and the second to also say it, and see if they both agree.

I was wondering, is it possible that both parties are recognised as the first party to say the state? (this would completely break my smart contract).

Thanks


texts: Help to understand library linking and the multisig hack

texts:
Just read about the today issue with parity multisig wallets,

https://paritytech.io/blog/security-alert.html

where as far I can understand the problem is that a library linked to many wallets was hacked, transformed to a contract and finally suicided causing all the wallets to freeze forever. However, this comes with some surprise for me as I assumed that like in traditional languages, linking a library to a contract was a compile time process where once the compilation is done you'd expect a bytecode containing contracts and libraries to be deployed to some address. Instead, in the docs I read that libraries have their own ethereum address. The library hacked today seems in fact to live at some address in the blockchain and then linked to many contracts. This puzzles me a bit, then when I use SafeMath.sol in my code what is my contract linking to? A bytecode I've just compiled or some instance already deployed?

Can anyone explain how the linking mechanism works?


texts: contract event not firing in web3 node console

texts:
It appears my events are not being fired in my node application when I transact the contract in the ethereum wallet gui.

I deployed a custom contract via ethereum-wallet
I have fired up geth attach
in geth I have started the rpc admin.startRPC("127.0.0.1", 8545, "*", "web3,db,net,eth")
within the node repl shell I have done the following:

> var Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
> var contractAddress = "0x807bF45B0245d8FA96F68E319116E18a15b07A10"
> var contractCode = "<paste in the code above for the contract>"
> var compiledContract = web3.eth.compile.solidity(contractCode)
> var contractDefinition = compiledContract.ShareClass.info.abiDefinition
> var reference = web3.eth.contract(contractDefinition).at(contractAddress)
> reference.Transfer().watch(
     function(error, result){
         console.log(result.args.from + " => "+result.args.to + " ["+result.args.value+"]");
     });

When I then call the Transfer method on my contract in ethereum wallet, the contract balance changes, but the console logging does not take place in my node app.


texts: Is it possible to deploy Dapp on Ethereum classic network and be listed in mist?

texts: So as a small bisness entety can not pay 100k USD for app deployment, one wonders on is it possible to deploy Dapp not in the test net but in a more real ETC one?


texts: How to input multiple arguments in remix?

texts:
My contract has a function transfer(address _to, uint256 _value) returns (bool), I want to run this function in remix injected web3 env.
I wanted to transfer 100 tokens of this contract https://kovan.etherscan.io/address/0xf63acf73c90b1136a39e5e64f839b68b808f7be7#code

How do i enter the parameters in remix? I tried "0xaddress",100000000000000000000 (that is 100  * 1e18) and it gave me this error

transact to RTTToken.transfer errored: Error encoding arguments: Error: Assertion failed

However if i try "0xaddress",100 it manages to transfer but then i am only getting 1e-15 token transferred which is incorrect.


texts: How to convert gasPrice from ETH Gas Station API to US dollars?

texts:
This is a simple call to https://ethgasstation.info/json/ethgasAPI.json

{
  "fast": 111,
  "fastest": 180,
  "safeLow": 55,
  "average": 80,
  "block_time": 14.761904761904763,
  "blockNum": 9819011,
  "speed": 0.9302273514361274,
  "safeLowWait": 18,
  "avgWait": 2.8,
  "fastWait": 0.5,
  "fastestWait": 0.5,
  "gasPriceRange": {
    "4": 246,
    "6": 246,
    "8": 246,
    "10": 246,
    "20": 246,
    "30": 246,
    "40": 246,
    "50": 21.4,
    "55": 18,
    "60": 10,
    "70": 7.7,
    "80": 2.8,
    "90": 1.8,
    "100": 0.8,
    "110": 0.6,
    "111": 0.5,
    "120": 0.5,
    "130": 0.5,
    "140": 0.5,
    "150": 0.5,
    "160": 0.5,
    "170": 0.5,
    "180": 0.5
  }
}

From the guide I read

  fast: Recommended fast(expected to be mined in < 2 minutes) gas price in x10 Gwei(divite by 10 to convert it to gwei)

This is the param I need, fast.

So in this call, fast is 111, so 11.1gwei.

This is a gas price, right?

My call consume 68988 unit of gas. It's a fixed length hash, so it's every time identical, I hope.

So totale gas paid is 11.1 * 68988 = 765766.8 giga wei.

Is this calculation right?

How can I determine the money cost of this transaction?


texts: Estimating costs to implement a permissioned blockchain

texts: I'm trying to ascertain what inputs and costs would be associated with implementing a permissioned blockchain like Hyperledger or Quorum. So far I have come up with the hardware costs (i.e servers) and employees with the skillsets necessary (i.e developers). What other inputs or costs would need to be considered?


texts: Error: Unhandled Rejection (Error): This contract object doesn't have address set yet, please set an address first?

texts:
I was learning Solidity through Remix and I decided to make a simple front-end application with pure HTML and CSS, it worked using Rinkeby.
Then I discovered Truffle and since then I try to make the same application on it (with React, Metamask and Rinkeby) but all the tutorials I follow, as an example: https://medium.com/@PasschainBlog/jumping-into-truffle-and-rinkeby-3acf6a2d9bef it seems that after truffle unbox react

truffle compile and truffle migrate just give an npm start and the default screen of Truffle with React works, but with this error in the terminal:

Then I thought: I will put cd client and I will run npm start there, then open localhost: 3000, the screen that should appear for 2 seconds appears and then gives this error, I don't know how to solve it. If you can help me ... :/
(translated by Google Translate)


texts: How to Set Gas Price in Private Blockchain?

texts:
I admit that I don't understand Gas at all.  But I think it is basically the currency which dapps use to interact with each other and the blockchain.  Yes?

If you're creating a custom/private network, is there a way to set the required gas per transaction to be 2x the cost of the ethereum blockchain?  I have looked at the chainspec and genesis files and the setting doesn't jump out at me as something obvious.

If you did that, would that mean more reward for miners?  And would the tradeoff be that is is more expensive to deploy a dapp?

Thank you.


texts:
I installed geth, created an account, and made a test payment (0.001). Now i am trying to sync the blockchain. After several hours I reached this point.

> eth.syncing
{
  currentBlock: 3886418,
  highestBlock: 3886509,
  knownStates: 44318,
  pulledStates: 18028,
  startingBlock: 3886216
}
> eth.getBlock('latest').number
0
> eth.getBalance(eth.coinbase)
0
>

I started syncing the blockchain from scratch using geth --cache=2048 fast and then when almost all the blocks were loaded i ran geth --cache=2048. So, what I can see here when I start geth is this:

INFO [06-17|11:11:54] Loaded most recent local header          number=3886284 hash=98a872…a28371 td=3622…722126
INFO [06-17|11:11:54] Loaded most recent local full block      number=0       hash=d4e567…cb8fa3 td=1717…84
INFO [06-17|11:11:54] Loaded most recent local fast block      number=3886216 hash=f4992e…1782cb td=3621…077687

I think I messed up something so I would like to know what I shall do to have the whole system synced and able to send/receive transactions.


texts: Mapping with iterating uint as identifier - multiple transactions in the same block

texts:
I want to use an iterating uint as an identifying number, but I have a simple question to make sure I can do this safely on the mainnet.  Here's a simple example to demonstrate the issue:

pragma solidity ^0.5.8;

contract Names {

    uint lastId;
    mapping(uint => string) public numberedNames;

    constructor() public {
        lastId = 0;
    }

    function setName(string memory name) public {
        numberedNames[lastId] = name;
        lastId++;
    }
}

My question is that if setName gets called multiple times within the same block, is it possible that lastId does not get updated after the first call, thus overriding the previous numberedNames element?


texts: Post the DAO-fork, is there a double-spending problem?

texts:
If an account had ETH before the DAO-fork does the ETH now not exist on both the ETH and the ETC chains?

A Poloniex notice says "All users who had an Ethereum balance at the moment of the fork now have a matching balance of ETC".  It seems that if the ETC chain lives, then account holders can spend and trade on two chains.  Effectively, is it possible to transfer your ETH balance to someone else on the ETC chain, and have it remain in your ETH account on the main ETH chain?

We also have a couple of posts referencing this:

https://steemit.com/ethereum/@pauls/ethereum-fork-step-by-step-guide-to-safely-splitting-your-eth-etc

https://steemit.com/crypto-news/@phistr/ayvsf-ethereum-step-by-step-guide-to-protect-your-eth-and-etc-funds-and-avoid-replay-attacks

A quote:

  Step 2: Send funds to Poloniex.
  Generate an ETH deposit address or use an existing one.
  Then send a test transaction (for example 1ETH) to this address.
  You should be credited ETH and the same amount of ETC.
  If so go ahead and send the rest of the ETH.

Can someone please help explain whether a double spending issue exists?


texts: How to use fiat exchange rate oracle in DAPP?

texts: my team is trying to develop a DAPP about fiat exchange rate. How to get the latest fiat exchange rate (USD/EURO etc.) accurately from external Oracles(Or are there better ways doing this)?


texts:
What is "Universal Hash Time" which is presented by Jeff Coleman at DEVCON1?

What is the purpose?
What is the problem it will solve?
What is the solution?
How does it work?


texts: Why is it bad to use myetherwallet.com for key generation on mobile?

texts: From my android, I read the myetherwallet.com mobile site that it is unsafe to generate keys in that manner. Why is it unsafe to generate keys on a mobile device?


texts: my computer is mac and it has run geth import for about a week, and it's 4000000 block now. I have ran geth --fast before and it's slow too. I am in china, is it something i can do to make it faster?


texts: I want to fork Ethereum with my own implementation. Like changing name or block size or something like this

texts: I'm such a noob or may be this is a noob type question i just want to fork Ethereum in go(maybe in another language) with my own implementation. Anyone can guide me about that?? Is there any relevant resources. I want to fork it as whole with some changings. Thanks in advance.


texts: If I want to make a project for image patent, what should I learn?

texts:
I'm new to Ethereum. Such as title, I want to make a project for image patent. I think it's a PoA project. Now I am studying Parity. And I have tried some tutorial, too. I can run a private chain in Docker with Parity and make some simple transaction now. But I don't know what should I do next. Maybe I need to study about how to write an GenesisBlock，
or how to use Web3?
I'm very confused now. Could you give me some advice or some tutorials?
And I want to know which client is most suitable for my project? There are so many client, I don't know choose which one to start... :(
Thanks a lot!！


texts: Transaction receipts, blocks and confirmations

texts:
In Bitcoin, there is a best practice to wait between three to six block confirmations before accepting an transaction. This is to avoid double spending. Are there similar rules of thumb in Ethereum?

Let's assume I am building a service that tracks Ethereum payment transactions. If I have an incoming tx hash, how can I check confirmations over Geth RPC API? I assume the transaction receipt should be used, but what numbers I should track to watch out for double spends and similar things. Is a transaction somehow invalidated if a double spend or other malign condition (fork?) is detected?


texts: From what source does etherscan.io aggregate and broadcast data that appears on the blockchain ledger?

texts:
as blocks are hashed together as transactions pile up and are broadcasted on the Ethereum blockchain, how exactly does the website etherscan.io in turn publish and broadcast all that information in real-time? Is etherscan.io an API in and of itself? If so, what source is it tapping into: Where and how is it getting its blockchain data?
In my opinion, etherscan.io is not the blockchain itself, but is somehow aggregating and collecting transactions as they happen on the blockchain, and then publishes them on the world wide web. My question is, how does this website do this? What is the source it is tapping in to to extract real-time information from the Ethereum blockchain?


texts:
pragma solidity ^0.4.24;
contract XXXX{
    address  owner;
    constructor()public
    {
        owner=msg.sender;//To store address of contract deployer

    }
        struct Project//struct to store project details
        {

            string  proName;
            string  proDetails;
            uint  proPrice;
            address  proOwner;

        }
        Project [] public  pros;//Dynamic array of strut to store project details
        mapping (address => Project) public enrolled;

    function ProjectDetails(uint _price, string _name,string _projectDetails) public
    //fucntion to accept project details
    {
        require(msg.sender!=owner);
        //require(enrolled[msg.sender]);

        Project memory newPro = Project// stores data in the struct
        ({
            proPrice:_price,
            proOwner:msg.sender,
            proDetails:_projectDetails,
            proName:_name

            });
            pros.push(newPro);

            enrolled[msg.sender]=newPro;

    }
}

I am getting the error that the called function should be payable even though I am using the above function just to enter data


texts: How can I receive message by golang - whisper

texts:
In geth --shh --rpc console, for example I type

f = shh.newMessageFilter({privateKeyId: id}, function(error, messages){console.log(JSON.stringify(messages))})

to receive a posted message by callback, and this works fine.

I am trying by golang to receive a posted message but this not work

example:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common/hexutil"
    shh "github.com/ethereum/go-ethereum/whisper/shhclient"
    whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
)

func main() {
    ctx := context.TODO()

    c, err := shh.Dial("http://127.0.0.1:8545")
    if err != nil {
        log.Fatalln(err)
    }

    id, _ := c.NewKeyPair(ctx)
    fmt.Println("id:", id)

    fID, err := c.NewMessageFilter(ctx, whisper.Criteria{PrivateKeyID: id})
    if err != nil {
        log.Panicln(err)
    }
    fmt.Println("FilterId:", fID)

    puKey, err := c.PublicKey(ctx, id)
    if err != nil {
        log.Println(err)
    }
    fmt.Println("PublicKey:", hexutil.Encode(puKey))

    blk, err := c.Post(ctx, whisper.NewMessage{
        TTL:       60,
        PowTime:   2,
        PowTarget: 2.5,
        Payload:   []byte("Hello"),
        PublicKey: puKey})
    if err != nil {
        log.Println(err)
    }
    fmt.Println("Blk:", blk)

    m, err := c.FilterMessages(ctx, fID)
    if err != nil {
        log.Panicln(err)
    }
    fmt.Println(m)

}

How I can to fix this issue?


texts: Checks-Effects-Interactions Pattern - External Call not reached

texts:
What happens if one uses Checks-Effects-Interactions Pattern and the gas runs out before the last line of the code in the contract can be reached, i.e., the last line is to interact with another contract and/or making an external call.

The resultant state is an incorrect state as the contract execution is incomplete. Would the use of revert() work?

What if the revert line is never reached as well?


texts:
In a function, does block.timestamp record the time the transaction was processed, or the time the block.timestamp computational step was processed?

Is block.timestamp the time the transaction is processed, or would time and time2 differ ?

function doSomething() {

uint time = block.timestamp

// ... a few 400000 gas of other things ... //

uint time2 = block.timestamp

}


texts: geth console flag/option to output all opcodes executed in call to contract or function invocation

texts:
What I'd like to do is analyze all the opcodes that are executed when I call a contract, or call a function from a contract.

According to my understanding, this computation would happen on my own machine, in the EVM, and only the result would be sent to the blockchain.

My idea is that, for this result to be calculated, the computations have to run on my local machine at some point in the following process:

var contractAbi = eth.contract([{"constant":true,"inputs":[],"name":"getPeople","outputs":[{"name":"","type":"bytes32[]"},{"name":"","type":"bytes32[]"},{"name":"","type":"uint256[]"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_firstName","type":"bytes32"},{"name":"_lastName","type":"bytes32"},{"name":"_age","type":"uint256"}],"name":"addPerson","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"people","outputs":[{"name":"firstName","type":"bytes32"},{"name":"lastName","type":"bytes32"},{"name":"age","type":"uint256"}],"payable":false,"type":"function"}]);

undefined

var myContract = contractAbi.at("0xC127E3ca071892B1b471b4FC568312Fcbb737879");

undefined

var getData = myContract.addPerson.getData("S. Matthew", "English", 28);

undefined

personal.unlockAccount(eth.coinbase, 'hunter2');

web3.eth.sendTransaction({to:"0xC127E3ca071892B1b471b4FC568312Fcbb737879", from:"0xd7a9a61a480d458a1181e0563b07f944df4489a6", data: getData, gas: (270000)});

"0x0cec118d22fbd572bf25c7e4143919e608989bec7da08512f2a6f3171df3b3b8"

myContract.address

"0xC127E3ca071892B1b471b4FC568312Fcbb737879"

myContract.getPeople()

[["0x532e204d61747468657700000000000000000000000000000000000000000000"], ["0x456e676c69736800000000000000000000000000000000000000000000000000"], [28]]

myContract.getPeople().toLocaleString()

"0x532e204d61747468657700000000000000000000000000000000000000000000,0x456e676c69736800000000000000000000000000000000000000000000000000,28"

How can I observe the opcodes that are being executed as a consequence of the above sequence?

Using the ByteCode To Opcode Disassembler on Etherscan I've seen which opcodes are invoked on contract creation, but I imagine that this is different than just calling a contract or one of it's functions, since- for instance, you won't need to invoke the constructor again, etc.


texts: What other constants depend on the current call like msg.sender?

texts:
I recently noticed that msg.sender isn't always the original caller's address (see here). It's the address of the current call. So if foo() calls bar(), then msg.sender in bar() will be the address of the contract containing foo().

My questions are:

Are there any other constants that depend on the current call? Full list: https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#special-variables-and-functions
What's the best way to get the original sender's address?


texts: Is the content of a function and the data in a smart contract publicly readable?

texts:
When I create a smart contract with some functions in it, I know anyone can execute those functions. My question is; can anyone also read the source/logic of those functions?

And I've got the same question for storing things on the Ethereum network. Let's say I create some sort of DAO in which people can register their names. If I don't create a method/function to read out those names, can anyone read the data stored by the smart contract (the names) anyway?


texts: Error : BlockGasLimitReached: : 'gaslimit' actual:4712388 target:3141592

texts:
I am using testrpc & truffle to build a test local blockchain. I am getting below exception while I run 'truffle test'.

I even tried to manually set the gas_limit variable in tester.py to 4712388 but still getting the same error.

Could you please help me to resolve this.

Thanks,

BlockGasLimitReached: : 'gaslimit' actual:4712388 target:3141592
ERROR:jsonrpc.manager:API Exception: {'message': ": 'gaslimit' actual:4712388 target:3141592", 'args': (": 'gaslimit' actual:4712388 target:3141592",), 'type': 'BlockGasLimitReached'}
Traceback (most recent call last):
  File "/home/sarath/.local/lib/python2.7/site-packages/jsonrpc/manager.py", line 108, in _get_responses
    result = method(*request.args, **request.kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/testrpc/server.py", line 33, in inner
    return rpc_fn(*args, **kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/testrpc/testrpc.py", line 89, in eth_sendTransaction
    return tester_client.send_transaction(**formatted_transaction)
  File "/home/sarath/.local/lib/python2.7/site-packages/eth_tester_client/client.py", line 251, in send_transaction
    self._send_transaction(*args, **kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/eth_tester_client/client.py", line 55, in inner
    return client_method(self, *args, **kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/eth_tester_client/utils.py", line 119, in inner
    return fn(*bytes_args, **bytes_kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/eth_tester_client/client.py", line 213, in _send_transaction
    output = self.evm.send(sender=sender, to=to, value=value, evmdata=data)
  File "/home/sarath/.local/lib/python2.7/site-packages/ethereum/tester.py", line 341, in send
    return self._send(*args, **kwargs)["output"]
  File "/home/sarath/.local/lib/python2.7/site-packages/ethereum/tester.py", line 296, in _send
    (success, output) = processblock.apply_transaction(self.block, transaction)
  File "/home/sarath/.local/lib/python2.7/site-packages/ethereum/processblock.py", line 142, in apply_transaction
    validate_transaction(block, tx)
  File "/home/sarath/.local/lib/python2.7/site-packages/ethereum/processblock.py", line 112, in validate_transaction
    raise BlockGasLimitReached(rp('gaslimit', block.gas_used + tx.startgas, block.gas_limit))
BlockGasLimitReached: : 'gaslimit' actual:4712388 target:3141592


texts: Commit-Reveal contract still vulnerable to front running. How can it be improved?

texts:
I'm writing a contract and I want to shield it from front-running as best as it can possible be done (obviously, fully preventing front running would be ideal). My implementation is very similar to the Raffle implementation from  @Ismael here so I will be using that:
contract Raffle {

    mapping(address => bytes32) commitments;
    mapping(uint256 => address) reserved;

    event Reserved(uint256 value, address owner);
    event Committed(bytes32 hash);

    function commit(bytes32 hash) public {
        require(commitments[msg.sender] == bytes32(0), "Already committed");
        commitments[msg.sender] = hash;
        emit Committed(hash); // Added this event for similarity
    }

    function reveal(uint256 nonce, uint256 value) public {
        bytes32 d = digest(nonce, value, msg.sender);
        require(commitments[msg.sender] == d, "Invalid data");
        require(reserved[value] == address(0), "Already reserved");
        reserved[value] = msg.sender;
        emit Reserved(value, msg.sender);
    }

    function digest(uint256 nonce, uint256 value, address sender) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(nonce, value, sender));
    }
}

This contract is vulnerable to the following front running scenario:

Honest user makes a commit. Commit is a hash so there is nothing the
attacker can do at this point.
Eventually honest user will make transaction to use the reveal method. At this point both the value and nonce are made public.
Before the honest user's transaction is picked from the mempool, the
attacker get's the now revealed parameters value and nonce, sends a
high gas transaction to make his commit.
In sequence frontruns the reveal transaction from honest user. (3 and 4 may even be done in the same block)

What measures can I take to prevent/mitigate this behavior?

Just like in the contract above I need both commit and reveal methods to be permanently open for interactions (Meaning I can't separate the methods in commit phase and reveal phase, as it would be done in a sealed bid auction)

My current idea for mitigation is to register the block.number with the commit, and in the reveal method only reserve the value if an arbitrary number of blocks has been mined since the commit was made. E.g: You made the commit on block 100, you need to wait to block 110 to call reval (otherwise the transaction is reverted). This gives a 10 blocks "advantage" to the honest user, as attacker will need to wait 10 blocks to try to frontrun.
The cons:

It doesn't solve the problem, the reveal transaction may stay X blocks (X being the arbitrary number of blocks to wait) on the mempool, due to clogged blockchain, low gas, or  other reasons. Long enough for the attacker to frontrun.
If the honest user mistakenly calls the reveal function before the number of blocks is mined he will have a failed transaction and the parameters will be revealed, cutting his advantage short.
Hard to determine a reasonable number of blocks.


texts: I have seen these two words - private and permissioned, a lot. Sometimes, they're used interchangeably. I don't believe these words have the same meaning. Can anyone give a detailed description differentiating these two types of blockchains?


texts: Receiving 'undefined' when using getBalance from web3

texts:
I am trying to fetch the balance of an address by web3 and node from Ropsten network with the commands below:
var Test = require('web3')
var url = 'https://ropsten.infura.io/v3/...'
var web3 = new Test(url)
var address = 'A Public Address'
web3.eth.getBalance(address, (err, bal) => {balance = bal})
balance`

The result is :
undefined

It was working and all of sudden this happened.


texts: When I create a signed transaction on my offline computer and then broadcast it on my online computer. What hinders a node to broadcast it again after my transaction is included in a block?


texts: what is the use case of this function ApproveAndCallFallBack?

texts:
ApproveAndCallFallBack

What will be the usecase for this code? excuse my markdown trials.

  contract ApproveAndCallFallBack {
      function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
  }
   function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
          allowed[msg.sender][spender] = tokens;
          Approval(msg.sender, spender, tokens);
          ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
          return true;
      }


texts: How can I download the entire Ethereum blockchain?

texts:
Is there a way to "get" the whole ethereum blockchain in order to process it locally? For example a link for direct download or via a developer API?
Thanks in advance!


texts: Is there any way to configure hyperledger besu to mine blocks only when there are transactions?

texts:
I have been following this tutorial:
https://besu.hyperledger.org/en/stable/Tutorials/Private-Network/Create-IBFT-Network/
Everything works fine, however I can see that every 2 seconds new block is added even thou there is no transactions at that moment. Is there any way to configure network that uses IBFT 2.0 to mine blocks only when there are transactions...


texts: Help with error please (SHA256 returns 0x)

texts:
I'm just playing around with testrpc vs creating my own private blockchain and for some reason when I use testrpc and i use SHA256 in my smart contract to return a hash it gives me a proper one. But when I start using my own private blockchain it returns 0x. Anyone know a solution to this?

PS : I used keccak256 and it works good in both testrpc and my private blockchain. it only happens with SHA256


texts: Contract call with ether and gas fails with revert

texts:
Testing with Truffle and solidity on localhost ganache network:

Works:

function dosomething(string a) {
    //do nothing
}

testing with:

TokenFactory tf = TokenFactory(TokenFactoryAddress);
function testDeployed() public {
  TokenFactory tf = TokenFactory(TokenFactoryAddress);
  tf.dosomething("lala"); //works!
  tf.dosomething.value(1000); //works!
  //assertions here
}

fails:

function dosomething(string a) payable {
   //do nothing
}

testing with:

TokenFactory tf = TokenFactory(TokenFactoryAddress);
function testDeployed() public {
  TokenFactory tf = TokenFactory(TokenFactoryAddress);
  tf.dosomething.value(100000)("lala"); //fails!
  tf.dosomething.value(100000).gas(1000000)("lala"); //fails!
  //assertions here
}

error:

  Error: VM Exception while processing transaction: revert


texts: Interaction with a deployed smart contract from the geth command line

texts:
I have a contract which I'd like to be able to sum numbers submitted by any other address:

contract UnitCounter {
    mapping (address => uint256) public UnitsFrom;
    uint256 public TotalUnits;

    function submitUnits(uint256 Units) {
        UnitsFrom[msg.sender] = Units;
        TotalUnits += Units;
    }
}

Using this as rough guidance, I followed the following steps on a private-net:

Deploy the contract using mist
Get the JSON Interface code using the "Show Interface" icon in mist
Copy the address of the deployed contract 0x17d541b8aACFFe473e3dD32eBA83C82B51DB8EF9 on my private blockchain.
On a Geth console:

var abi=[ { "constant": false, "inputs": [ { "name": "Units", "type": "uint256" } ], "name": "submitUnits", "outputs": [], "type": "function" }, { "constant": true, "inputs": [], "name": "TotalUnits", "outputs": [ { "name": "", "type": "uint256" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "address" } ], "name": "UnitsFrom", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "type": "function" } ]

var MyContract = web3.eth.contract(abi);

var MyContractInstance = MyContract.at('0x17d541b8aACFFe473e3dD32eBA83C82B51DB8EF9');

MyContractInstance.submitUnits('10');

I then get the following errors:

  Error: invalid address
          at web3.js:3887:15
          at web3.js:3713:20
          at web3.js:4939:28
          at map ()
          at web3.js:4938:12
          at web3.js:4964:18
          at web3.js:4989:23
          at web3.js:4055:16
          at apply ()
          at web3.js:4141:16

What do these errors mean?

How should I debug from this point?


texts: Ethereum Wallet sending zero value transactions

texts:
I'm not sure what's happening. I created a private network and started mining it.

When the mining is started, the coin base is getting the block reward ( with no transaction).

Things change when I connect Ethereum wallet with this IPC. When connected, the coinbase also gets some transaction fee ! I have no Idea what kind of transaction is done by Ethereum wallet, but it executes state transition function with some transaction involved :

EDIT :

However I don't see any transaction fee added to accounts while mining only blocks

EDIT2 :

I figured mist is sending 0 value transactions. I have no idea why. That is why they are not reflected in the block.


texts: A tiny problem about mapping in solidity (parse error when initializing the mapping)

texts:
I encountered this problem when I designed a test contract and initialized the mapping therein as provided below.

pragma solidity ^0.4.10;

contract test{

    mapping (uint256 => string) uintTostring;

    uintTostring[uint256(1)]="1";
}

The compiler says there is parse error about this command " uintTostring[1]='1' "
Where do I make wrong and how I can solve this problem?


texts: Truffle - deploy and interact with a contract locally from a script

texts:
I have created a contract, wrote a migration and a test. When I run truffle test the contract is deployed locally and then the tests are run against it. All is working fine.
I also added a function to the contract that looks like this (which I also call in the test):
function entryExists(uint256 id, string memory type)
        public
        view
        returns (bool)
    {

Now, I would like to locally deploy that contract (perhaps truffle develop could be of help?) and call that function from let's say a nodeJS script. How would I do that? I can't seem to find anything about that anywhere but it feels like such a basic thing.
Thanks in advance to anyone helping.


texts: Parity POA Smart Contract Method Always Fails

texts:
I have set up a private POA Network according to the tutorial from the parity homepage. I have two nodes running on localhost:8540 and localhost:8541. I have connected MetaMask to my first node and am able to send transactions between test accounts and even deploy a smart contract from remix. Unfortunately I am not able to call the functions from the deployed contract as the gas estimation always fails and the transaction gets mined but execution fails.

Here are my configurations:

Spec.json

{
"name": "OraclePOA",
"engine": {
    "authorityRound": {
        "params": {
            "stepDuration": "5",
            "validators" : {
                "list": [
                    "0x0038ba71301213d9508ce44fd25272d83b1c5dae",
                    "0x002e9ac8fef5ab0d0591488860562438ab154bd4"
                ]
            }
        }
    }
},
"params": {
    "gasLimitBoundDivisor": "0x400",
    "maximumExtraDataSize": "0x20",
    "minGasLimit": "0x1388",
    "networkID" : "0x2323",
    "maxCodeSize": "0x6000",
    "eip155Transition": 0,
    "validateChainIdTransition": 0,
    "eip140Transition": 0,
    "eip211Transition": 0,
    "eip214Transition": 0,
    "eip658Transition": 0
},
"genesis": {
    "seal": {
        "authorityRound": {
            "step": "0x0",
            "signature": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
        }
    },
    "difficulty": "0x100000",
    "gasLimit": "0x1000000"
},
"accounts": {
    "0x0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
    "0x0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
    "0x0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
    "0x0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
    "0x00d695cd9b0ff4edc8ce55b493aec495b597e235": { "balance": "10000000000000000000000" },
    "0x001ca0bb54fcc1d736ccd820f14316dedaafd772": { "balance": "10000000000000000000000" }
}
}

The configuration of the node connected to MetaMask:

[parity]
chain = "oracle-spec.json"
base_path = "/myOracle/parity0"
[network]
port = 30300
[rpc]
port = 8540
apis = ["web3", "eth", "net", "personal", "parity", "parity_set", "traces", "rpc", "parity_accounts"]
[websockets]
port = 8450
[account]
password = ["authNode0.pwds"]
[mining]
engine_signer = "0x0038ba71301213d9508ce44fd25272d83b1c5dae"
reseal_on_txs = "none"
usd_per_tx = "0"

here is my sample contract:

pragma solidity 0.5.7;
contract Sample{
    //address of owner
    address payable owner;

    //whoever deploys contract is the owner
   constructor() public{
        owner = msg.sender;
   }

    function doSomething() external payable {
        int i = 10 + 10;
        i++;
   }
}

Help would be much appreciated!


texts:
Using Web3 version 1.0 and getting the following error:

  web3.toWei is not a function


texts: How to caculate/estimate Gas Limit and Gas Price based on current state of the ether network?

texts: Ethgasstation and similar websites estimate proper Gas Price based on current state of Ethereum network. Is there any way of using working with Geth/web3 to estimate proper Gas Price? and similar to this, how about estimate Gas Limit?


texts:
I am making a transaction using the function,

simple.multiply.sendTransaction(5,6{from:"0xcf03e41ee1116bed4f1acf8a2209b4d37d755988"})

This is a simple function which multiplies the two numbers 5 & 6. The value returned should be 30. But I am not able to see the result of this function anywhere.

All I have is the hash of the transaction with me which is:

"0x2c5f34dadb8929e891f96e6082cc0403043b60493d4a44114973655ec67bd87e"

Does geth have any method by which I can access the output. Are these output logs stored anywhere?


texts: Call a payable function and pay ether with MetaMask

texts:
I am using web3 and MetaMask for my dApp
I have a deposit function in a contract. Now I know, that I could simply tell the user that he should send ether to a contract and the fallback function would do the rest.

But how can I do a manual deposit function where the user enters an amount on the website in an input field, clicks on a "Make deposit"-button and then needs to accept the MetaMask request where he sends the ethereum he entered together with the request to call deposit()?

Thanks! :)


texts:
I have a very strange problem. Many solidity contract examples use address struct types as state variables. But my smart contract:

pragma solidity ^0.4.0;

contract ProductItem {
address[] _owners;
address _currentOwner;
address _nextOwner;
string _productDigest;

function ProductItem(string productDigest) {
    _currentOwner = msg.sender;
    _productDigest = productDigest;
}

function setNextOwner(address nextOwner) returns(bool set) {
    if (_currentOwner != msg.sender) {
        return false;
    }
    _nextOwner = nextOwner;
    return true;
}

function confirmOwnership() returns(bool confirmed) {
    if (_nextOwner != msg.sender) {
        return false;
    }
    _owners.push(_nextOwner);
    _currentOwner = _nextOwner;
    _nextOwner = address(0);
    return true;
}

function getOwner() constant returns(address owner) {
    return _currentOwner;
}

function getOwners() constant returns(address[] owners) {
    return _owners;
}

function getProduct() returns (string product) {
    return _productDigest;
}
}

gives me error in web ide:

  Untitled:4:5: Error: Type "address[]" not supported for state variable.
      address[] _owners;
      ^---------------^"

If i ignore this error and try to deploy and call function, e.g. getProduct() it results with null.


texts: I use metamask custom RPC and set it to be http://myip:8545, and it looks like keep trying connecting, but always not finish, actually I am using private ethereum network, whether I must mine on my private network to make the metamask ok?


texts: Issue with Contract function return value data type

texts:
I am using a simple contract

Contract code

contract Bank {
    address public owner;
    mapping(address => uint) private customerBalance;
    event fallbackCalled(address, uint256);
    event deposit(address, uint256);

    constructor() public {
        owner = msg.sender;
    }

    /** Customer Deposit payable function */
    function depositFunds(uint _value) external payable returns(bool) {
        require(_value > 0, "values not greater then zero");
        customerBalance[msg.sender] += _value;
        emit deposit(msg.sender, _value);
        return true;
    }

    /** Fetch Customer Balance */
    function getCustomerBalance() public view returns(uint) {
        return customerBalance[msg.sender];
    }

    function () external payable {
        emit fallbackCalled(msg.sender, msg.value);
    }
}

Test case --->

describe('Customer should able to deposit funds', () => {
  it('customer balance should be positive ', async () => {
    // Deposite money into Bank from account[1]  #2
    let _value = 10;
    const result = await deployedInstance.methods.depositFunds(_value).send({
      from: accounts[1]
    });

    // Fetch the balance of account[1] and it should be equal to 1
    let accountBalance = await deployedInstance.methods.getCustomerBalance().call({
      from: accounts[1]
    });

    expect(accountBalance).toBe(_value);
  })
})

Test case Result

expect(received).toBe(expected) // Object.is equality

Expected: 10
Received: "10"

**Difference:** Comparing two different types of values. Expected number but received string.

When I'm performing my unit testing that time, test case is failing caz customer balance value is coming as String from Contract call but I am supplying a number value from Testcase..

I have also check the offical documentation which also shows an exmple where they are fetching uint but getting string.

https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html?#id18

Is there any specific reasons for returning strings.

Regards
Dev


texts: What is the difference between "geth" and "geth --fast"?

texts:
EDIT : I hadn't see the other question but this one ain't a duplicate because I'm asking here, precisely, if the state differs and if it does, what are the implications. The answer to that question isn't present in the other question and isn't present in the comment of that other question: all that is written, in a comment, is that the state ends up being different. I'd like to know what are the implication of the state being different.

When I start a geth Ethereum node from scratch, I can use "geth --fast", which is faster than just using geth to synch the blockchain.

My question is: do I end up with a node in the same state as if I hadn't used the --fast option and, if not, what are the implications of the two states being different.

Here are, for example, many related subquestions one could have...

Questions

If the two are identical, why isn't geth --fast always used when starting geth with an empty chain?
If the two are not identical, are there any security concerns when using the --fast option? Is it able to then verify every new block correctly? (if so I take it the end state is totally exactly identical?)
Does a node started with "geth --fast", once synched, then act as a "normal node"?
If a new "geth --fast" node was connected to one and only one node and that node was a "geth --fast" started one, would the new "geth --fast" node be able to download the blockchain from scratch?
If a new "geth" node was connected to one and only one node and that node was a "geth --fast" started one, would the new "geth" node be able to download the blockchain from scratch?
What if in the entire world there were only "geth --fast" nodes operational, would that prevent the Ethereum network from operating normally? What would be lost?


texts: infura.io secret configuration in HDWalletProvider (truffle-config.js)

texts:
I have set a secret for my project in infura.
Here is my truffle-config.js file:
module.exports = {
  networks: {
    ...
    ropsten: {
      provider: new HDWalletProvider(mnemonic, "https://ropsten.infura.io/xxxxx"),
      network_id: 3
    }
  }
};

My question is: Where can i put secret in this configuration file. I have read a lot of documentation/turorials and there is nothing about this secret.
Thanks a lot


texts: Merkle proof for Smart Contract mapping field data

texts:
I'm trying to get merkle proof for Ethereum Smart Contract mapping field data.
I created test smart contract and deployed to test network.
Smart Contract Code like following code:

contract TestSmartContract {

mapping(string => string) mappingField;
address sender;

function TestSmartContract() public {
    sender = msg.sender;
}

function addData(string key,  string value) public {
    mappingField[key] = value;
}}

I invoked smart contract addData method with test data.

"a","1"
"b","2"
"c","3"

After invoking smart contract, I tried to get value with web3 library, it works and i can get value for "a" key as "1".

var slot = "0".repeat(64);
            var key = web3.fromAscii('a');
            contractAddress = "0xac3f3d7286d8092be72d0011865a393ea722f609";
            var keccak256 = web3.sha3(key + slot, { encoding: 'hex' });
            web3.eth.getStorageAt(
                contractAddress,
                keccak256,
                function (err, result) {
                    console.log(web3.toUtf8(result))
                    console.log(result);
                }
            );

As a final stage, I tried to create Merkle Proof for Key "a". I tried to use https://github.com/zmitton/eth-proof library for retrieving Merkle Proofs. But it gives "storageNode not found" error. You can find my test code below:

const Web3 = require('web3');
const EP = require('eth-proof')

var chainDataPath = '/Users/ramazan.girgin/chain-tmp/privchain/geth/chaindata/';
try {
    var latestBlockHash = 'f02052990b2ea9daa445c0a4655cb3a395a84c8300cba8258b8faf4357b109c7'
    Web3.providers.HttpProvider.prototype.sendAsync = Web3.providers.HttpProvider.prototype.send;
    var eP = new EP(
        new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
        latestBlockHash,
        chainDataPath
    )
    contractAddress = 'ac3f3d7286d8092be72d0011865a393ea722f609';
    eP.getStorageProof(contractAddress, '0','0x61').then((result) => {
        console.log(result)
    }).catch((e) => {
        console.log(e)
    })
} catch (e) {
    console.log(e)
}

Actually, ZMitton uses https://github.com/ethereumjs/merkle-patricia-tree in this library. But i think there was a problem while sending path for storageTrie.findPath function in library getStorageProof method or i can incorrect values for getStorageProof() method. In the other hand, if i call getStorageProof for sender field , it gives complete proof.

eP.getStorageProof(contractAddress, '1').then((result) => {
            console.log(result)
        }).catch((e) => {
            console.log(e)
        })

How can i retrieve merkle proof for mapping field in Smart Contract? Or how can i calculate correct path for storageTrie.findPath function parameter ?

Thanks in advance

Ramazan


texts: Truffle console doesn't work :Unexpected error: Cannot provision contracts while instantiating the console

texts:
when I run truffle compile, truffle migrate successfully and then truffle console gives me the following error.
strong text

**Enexpected error: Cannot provision contracts while instantiating the console.
Error: Cannot parse .DS_Store: Unexpected token  in JSON at position 0
    at /usr/local/lib/node_modules/truffle/lib/repl.js:69:27
    at tryToString (fs.js:447:3)
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:434:12)
truffle(development)> TypeError: Cannot read property 'forEach' of undefined
    at TruffleInterpreter.resetContractsInConsoleContext (/usr/local/lib/node_modules/truffle/lib/repl.js:95:17)
    at /usr/local/lib/node_modules/truffle/lib/repl.js:44:12**

UPDATE: I solved this problem by pulling a fresh copy of my code from github. And then in my new project directory, I re did npm install. Hope this is helpful


texts: Watch an Ethereum address for incoming payments

texts:
I want to watch a set of Ethereum contracts and be notified (preferably by email) when a contact receives a payment to it.

I prefer me not to write my own software for this and not to install it on my own server, but programming suggestions are welcome.


texts: is it possible to run pending transactions on local node to see the outcome?

texts:
I am looking for a way to execute current pending transactions on local node, to see their outcome and log events, without really mine it.

it is some kind of pre-simulation, to see what is going to happen on the next block in the network.

is it possible? how can it be done?


texts:
unable to connect MetaMask with local blockchain(Ganache)
Chrome Console Error

truffle-contract.js:425 Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)

contract runs fine in truffle console
web3.eth.getAccounts() // worked fine

1_initial_migration.js
var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {
  deployer.deploy(Election);
};

2_deploy_migration.js
var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {
  deployer.deploy(Election);
};

truffle-config.js
module.exports = {
  networks: {
    development: {
       host: "127.0.0.1",
       port: 7545,
       network_id: "*" // Match any network id
    },
    develop: {
       port: 8545
    }
  }
};

App.js
//Some code up here

initWeb3: function() {                             //Connect Client Side to locak blockchain
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
  // If a web3 instance is already provided by Meta Mask.
  App.web3Provider = web3.currentProvider;
  web3 = new Web3(web3.currentProvider);
} else {
  // Specify default instance if no web3 instance provided
  App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
  web3 = new Web3(App.web3Provider);
}
return App.initContract();
},

 //Some  more code here which contain contract deploying index.html file code

On Ganache

Network Id 5777
RPC Server http://127.0.0.1:7545

MetaMask

Custom RPC
Network Id - development / Ganache
New RPC Url - http://127.0.0.1:7545
Chain Id - 1337

Chrome
npm run dev
Url - http://localhost:3000
Measure Taken

successfully imported local blockhain account as MetaMask account using Priavte Key of imported account

installed ganache-cli
npm install -g ganache-cli
ganache-cli --chainId  //As per github docs

Accounts     ----*/*/*/*/*/----
Private Keys ----*/*/*/*/*/----
Listening on 127.0.0.1:8545

used port no 8545

used chainId  1

still got no results as expected.. if required I will send the whole project file..


texts: Does Ethereum have the "private key exposed on spend" problem?

texts:
Is it the case that Ethereum requires the spender to provide the private key for an address so that it can prove ownership when spending ETH?
If so, is there some mechanism where each spend actually creates a new address with a new private key, and invalidates the old address, to avoid someone else knowing the private key and taking the Ether?

I've googled for a while to look this up, but the search terms I'm using are probably not right, as I don't find any good hits. ("does spending ether expose the private key" and many variants.)
Also, if this is already answered in this very SO, I'd love a link!


texts: Cannot sign data using eth_signTypedData_v3 in coinbase wallet but can in every other dapp wallet?

texts:
Signing data worked in trustwallet, metamask, opera wallet. But not in coinbase using walletlink.
Using eth_signTypedData_v3 - when sent to coinbase wallet via walletlink the error Cannot read property 'EIP712Domain' of undefined is returned.
   const domain = [
      { name: "name", type: "string" },
      { name: "version", type: "string" },
      { name: "chainId", type: "uint256" },
      { name: "verifyingContract", type: "address" },
      { name: "salt", type: "bytes32" },
    ];

  const data = JSON.stringify({
      types: {
        EIP712Domain: domain,
        Listing: Listing,
      },
      primaryType: "Listing",
      domain: domainData,
      message: message,
    });

    const signedData = await new Promise((resolve, reject) => {
      web3.currentProvider.sendAsync(
        {
          method: "eth_signTypedData_v3",
          params: [account, data],
          from: account,
        },

returns the error:
web3.saga.tsx:720 TypeError: Cannot read property 'EIP712Domain' of undefined
    at Object.findTypeDependencies (index.js:149)
    at Object.encodeType (index.js:127)
    at Object.hashType (index.js:179)
    at Object.encodeData (index.js:42)
    at Object.hashStruct (index.js:168)
    at Object.hash (index.js:208)
    at Object.hashForSignTypedData_v3 (index.js:225)
    at WalletLinkProvider._eth_signTypedData_v3 (WalletLinkProvider.js:449)
    at WalletLinkProvider._handleAsynchronousMethods (WalletLinkProvider.js:235)
    at WalletLinkProvider.js:186
    at new Promise (<anonymous>)
    at WalletLinkProvider._sendRequestAsync (WalletLinkProvider.js:165)
    at WalletLinkProvider.sendAsync (WalletLinkProvider.js:112)

Yet in walletlink's code it has:
  async _eth_signTypedData_v3(params) {
        this._requireAuthorization();
        const address = util_1.ensureAddressString(params[0]);
        const typedData = params[1];
        this._ensureKnownAddress(address);
        const message = eth_eip712_util_1.default.hashForSignTypedData_v3({ data: typedData });
        const typedDataJson = JSON.stringify(typedData, null, 2);
        return this._signEthereumMessage(message, address, false, typedDataJson);
    }


texts: Why does Mist doest show up anything for me running on testnet

texts:
I just see a blank screen when I open Mist Browser on ubuntu running on testnet. What is the issue ?

I couldnt start in the first place. But after using --ignore-gpu-blacklist I could start, Then I get the blank Page as in the image below and it doesn’t show up anything.

Its not a duplicate question, I have edited it as per the solutions in the other questions. I had issues with starting Mist only when I gave --ignore-gpu-blacklist it only started. My blockchain is synced with testnet as wel..


texts: Generate Ethereum account in a JSON/UTC v3

texts:
What are some trustful ways to generate an Ethereum account in a JSON/UTC v3 format? I know some web wallets, but I would prefer a very used/well-known desktop or plugin wallet.
Metamask does not allow me to generate this format. It only allows me to export the private key in plain text.


texts: The security of private key with geth on the server-side

texts:
If you initiate a transaction in real time, you need to store the private key on the geth server to initiate the transaction. Once the geth server is hacked, the private key may be leaked. Is there any good way to use the private key to initiate a transaction, but there is no danger of the private key being leaked?
Hope you can give me some help, thanks!


texts:
I am trying to make APIs in Go by using the ethapi.
I need to call the below method from my golang code but i'm not able to call it. Can anyone help me?

func GetAPIs (apiBackend Backend) []rpc.API


texts: How to generate a raw transaction with data using Pyethereum

texts:
How do you use Pyethereum to generate a raw tx to send to the blockchain? I can do it successfully with a transaction with no data, but when I am attempting to use data, it does not function properly.

To expand on this, I have pinpointed the problem to the data encoding. I can send a 1 ETH transaction with no data perfectly. I can send that same transaction with a string of data, say '0xabcdef' and it will go through the same, except the 'data' section on etherscan.io does not read '0xabcdef'. I believe this is the issue, but I do not know how to fix it.

To show an example, I am using this to create the transaction, and the following code works:

nonce = 100
gas_price = 10000000000
gas_limit = 22000
value = 1000000000000000000
data = ""
privkey = private_key_here

unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, to_address, value, data).sign(privkey))
signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')

The following code, which is the same, but with data, also goes through, but the data is not what I expect:

nonce = 100
gas_price = 10000000000
gas_limit = 22000
value = 1000000000000000000
data = "0xabcdef"
privkey = private_key_here

unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, to_address, value, data).sign(privkey))
signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')

Data output (according to etherscan.io): 0x3078616263646566

Obviously that is not the data I wanted to see. How can I pass in the same data I see on etherscan.io?


texts:
when i'm working on ganache all event that i have emit are store in my nodejs server but when i turn to kovan or ropsten my server don't catch event . i'm working with infura

this my code

  no products are added when I’m on a network other than ganache

server.js show this

  (node:11608) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Ebay on Ethereum server listening on port 3001
Error: The method eth_newFilter does not exist/is not available
    at Object.InvalidResponse (/var/www/krypteth/node_modules/truffle-contract/node_modules/web3/lib/web3/errors.js:35:16)
    at /var/www/krypteth/node_modules/truffle-contract/node_modules/web3/lib/web3/requestmanager.js:86:36
    at XMLHttpRequest.request.onreadystatechange (/var/www/krypteth/node_modules/web3/lib/web3/httpprovider.js:128:7)
    at XMLHttpRequestEventTarget.dispatchEvent (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:469:24)
    at IncomingMessage.emit (events.js:194:15)
    at endReadableNT (_stream_readable.js:1103:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Error: The method eth_newFilter does not exist/is not available
    at Object.InvalidResponse (/var/www/krypteth/node_modules/truffle-contract/node_modules/web3/lib/web3/errors.js:35:16)
    at /var/www/krypteth/node_modules/truffle-contract/node_modules/web3/lib/web3/requestmanager.js:86:36
    at XMLHttpRequest.request.onreadystatechange (/var/www/krypteth/node_modules/web3/lib/web3/httpprovider.js:128:7)
    at XMLHttpRequestEventTarget.dispatchEvent (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/var/www/krypteth/node_modules/xhr2/lib/xhr2.js:469:24)
    at IncomingMessage.emit (events.js:194:15)
    at endReadableNT (_stream_readable.js:1103:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

this my app js web3 provider

window.addEventListener('load', function() {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, $
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
  } else {
    console.warn("No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live,$
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("https://kovan.infura.io/v3/<my-key>"));
  }

  App.start();
});

and my server.js provider code

var provider = new Web3.providers.HttpProvider("https://kovan.infura.io/v3/<my-key>");