texts: Ethereum - What is the correct way to pass a string using delegate Call?

texts:
In my contract, I have separated my code and data. In the "data contract", I am storing the current version of code. Whenever addEmployee() is called, I am trying to delegate it to Current Version address (with string as parameter) where the actual function code resides. But the problem is string being received by the Current Version is always ' ' regardlessof my input. (See the commented part in the contract Data.)The function works as expected if I use bytes32 instead of string. Can someone explain this behaviour??? Am I missing some concept??

pragma solidity ^0.4.11;

contract EmployeeDir{
    uint public id;
    string public name;
    address public currentVersion;
    address public owner;

    struct employee{
        string name;
        uint days_present;
    }

    mapping (uint => employee) public dir;

    /**
     * Constructor: Sample Input "vishy", "<address of contract Code>"
     * @param _name - Name of the EmployeeDir
     * @param _versionAddr - Address of the Current Version to which Delegate Call is intended to
     **/
    function EmployeeDir(string _name, address _versionAddr){
        dir[id].name = _name;
        currentVersion = _versionAddr;
        owner = msg.sender;
    }

    function updateVersionAddress(address _versionAddr){
        if(msg.sender == owner)
            currentVersion = _versionAddr;
    }

    function addEmployee(string _name){
        if(msg.sender == owner){
            //This is where the string is being passed as empty
            //To check if the delegatecall is indeed working, a sample var id has been introduced.
            //The var id is getting updated on delegatecall meaning that delegatecall is working but the string is not getting updated.
            currentVersion.delegatecall(bytes4(sha3("addEmployee(string)")), _name);

            dir[id].name = name;
        }
    }
}

contract Code{
    uint public id;
    string public name;

    function addEmployee(string _name){
        id += 1;
        name = _name;
    }
}


texts:
I am looking for some kind of walk through or tutorial about how to use ethereum with an ruby on rails application?

Is there anything out there?


texts: react truffle box calling solidity with addresses issues

texts:
Repository

I've tested the solidity side and things seem to work appropriately.  However my hooking up the react box is running into a few problems.

I seem to have varying problems related to addressing and calling functions.

App.js

in the instantiateContracts function and in the Check Function.

the uncommented out 'return' lines are the ones that WORK, the uncommented returns DO work.

Also on the attempt to push a credentialOrg (button) i get an Error: invalid address on all attempts.

I expect I'm missing something basic.

this may be a clue: this is the last result  and can't retrieve the values via result.c[0], etc.


texts:
I have created one account using the command geth account new , name acc1 and another under the geth console using the command personal.newAccount() name it acc2. Now i am not able to see the acc1 using the command eth.accounts and acc2 using the command geth account list .
Both accounts have been created on same node. Then why the data of both accounts have been synchronized between both consoles.
What is the difference in both the ways of account creation?


texts: How it works with modified go-ethereum source code

texts:
I modified go-ethereum source code and built it. I am wondering if I want to test and run geth with the modified source code in mainnet or testnet, and how it works in the mainnet or testnet.

How to test the modified source in mainnet or testnet
How it works with modified source in mainnet or testnet


texts: What does Response for View Function request look like? Does Validator give any prooves that the execution was done correctly?


texts: I know that Ethereum and Bitcoin both you the same underlying elliptic curve, so I'm wondering, is it possible to store bitcoin in an Ethereum contract?


texts: Why I'm still getting web3 0.20.0 API in javascript?

texts:
I followed https://web3js.readthedocs.io/en/1.0/getting-started.html and downloaded web3.min.js to my http host. In my html I have:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="./web3.min.js"></script>
    <script type="text/javascript" src="./libs/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            console.log(Web3.givenProvider || web3.currentProvider);
            web3 = new Web3(Web3.givenProvider || web3.currentProvider);

            console.log('Version:', web3.version.api);
        });
    </script>
</head>
<body>
</body>
</html>

I visit the page and see version is 0.20.0. Also from the API doc, if it were 1.0 then web3.version should be 1.0 and there should be no member called .api.

What am I doing wrong here that I'm getting 0.20.0?

Chrome. Metamask 3.13.4. Downloaded web3.min.js from https://raw.githubusercontent.com/ethereum/web3.js/1.0/dist/web3.min.js

EDIT

Also tried download web3.min.js from the master branch. Same result.

EDIT

Actually for the current 1.0 I'm getting Uncaught SyntaxError: Unexpected token << from the file as I look into browser's debug window.


texts:
I want to buy an ASIC Miner (A10 Pro 6GB) but i have some doubts.

Is it good to buy an ASIC Miner in Nov. 2020 for ETH and ETC mining ?
Recently I heard that the mining algorithm for ETC is changing so can i mine the ETC after this change ?
Will the ETH mining algorithm also change? If not then, will the change in ETC mining algorithm affect ETH profitability?


texts: Where can i get total list of all existent Etehereum contract ABIs?

texts: We all know that exists https://www.4byte.directory/ where we can get mapping (function selector) -> (function signatures). Is there a dataset where I can get mapping (contract address) -> (JSON contract abi) without any web requests? If there is no such one, is there any ways to create such. For example by creating similar to 4byte directory service, but for contract addresses will it be popular enough to gather some data?


texts: Example of Signedness Bug in Smart Contracts

texts:
I found an example of underflow bug at:
Catching Vulnerable Smart Contracts Once and for All

contract UnderflowAttack {
 ...
 function withdraw (uint amount) public {
   require(balances[msg.sender] - amount > 0);
   msg.sender.transfer(amount);
   balances[msg.sender] -= amount; //Underflow
 }
 ...
}

I feel the above contract also exhibits signedness bug. Can somebody please provide me a more specific example of a signedness bug in smart contract?


texts: Accepting Map or JSON in a constructor or method

texts:
I have a question:

Can a Contract accept a HashMap kind of a data structure or some kind of a JSON structure of the following format in its Constructor?

[
{key1 -> {val1, val2, val3}},
{key2 -> {val1, val2, val3}},
{key3 -> {val1, val2, val3}}
]

If it can, how to extract these (k, {v}) pairs in the contract and store them in some mapping?

Could someone please show me examples of both?

Thanks.


texts:
So sync the whole chain just takes way too long for me, after a whole day of work it wasn't even halfway.

I ran the geth --light command and it seems to work. It is showing the correct amount of ether.

But i noticed I have two versions of geth 1.6.5 and 1.6.6
I removed 1.6.5 but then the wallet shows 0 ether, so i restored it.
It's also seems to be stuck at 0% sync now, i'm not sure if I should just leave it like this or that I can set it up to use 1.6.6 instead?


texts: Out of gas ethereum transaction. Didn't roll back?

texts:
I sent ether to an ICO from my poloniex wallet. But it says out of gas error. And the ether I sent didn't come back to my wallet. What should I do?
(https://i.stack.imgur.com/MOd7j.png)


texts: Deploy smart contract on Ropsten using truffle-hdwallet-provider

texts:
I have 7 smart contracts to deploy on the Ropsten network.

I am using truffle-hdwallet-provider and below is the content of my truffle.js file:

module.exports = {
  solc: {
    optimizer: {
    enabled: true,
    runs: 200
 }
},
networks: {
 ropsten: {
  provider: function() {
    return new HDWalletProvider(
      process.env.MNENONIC,
      `https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`
      );
    },
    gasPrice: 250000000000,
    network_id: 3
  }
 }
};

Then I run the following command:

truffle migrate --network ropsten

but I get the following response:

Error encountered, bailing. Network state unknown. Review successful transactions manually.insufficient funds for gas * price + value

Fine, it stated I have insufficient fund and my fund was 1.509 Ether at the time. So can I assume the cost to deploy all my contracts is more than 1.509 Ether (that's more than USD163!)?

Appreciate if someone can guide me.


texts:
This is ethereum address.
On which there are a bunch of registered ENS names

How can we view the actual ENS names which were registered/won in auctions from this address?


texts: How to verify the type/name of token received in a smart contract?

texts:
Here is a sample contract which is designed to take xyz token. How can the contract verify that the sent is the xyz token?
pragma "^0.7.0"

contract myContract {
  address public payable owner;
  uint public value;  //<<==xyz token

  constructor(uint _value) payable {
    owner = msg.sender;
    value = _value;  //<<== how does the contract verify it is the _value of xyz token?
  }
}


texts: Accessing Web3 in trufflebox's react-auth-box

texts:
Hi I am using trufflebox boilerplate react-auth-box. Created a new component called Foo where I am trying to access the web3 object that has been mapped from Store to this.props.

However the console.log(this.props.web3) is showing {web3Instance: null}. What should we do?

src/Foo.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Foo extends Component {

    componentWillMount() {
        console.log(this.props.web3)               // {web3Instance: null}
    }

    render() {
        return (
foo
 )
    }
}

function mapStateToProps(state) {
    return {
        web3: state.web3
    }
}

export default connect(mapStateToProps)(Factory);

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { syncHistoryWithStore } from 'react-router-redux'
import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js'
import getWeb3 from './util/web3/getWeb3'

// Layouts
import App from './App'
import Home from './layouts/home/Home'
import Dashboard from './layouts/dashboard/Dashboard'
import SignUp from './user/layouts/signup/SignUp'
import Profile from './user/layouts/profile/Profile'
import Foo from './Foo'

// Redux Store
import store from './store'

// Initialize react-router-redux.
const history = syncHistoryWithStore(browserHistory, store)

// Initialize web3 and set in Redux.
getWeb3
.then(results => {
  console.log('Web3 initialized!')
})
.catch(() => {
  console.log('Error in web3 initialization.')
})

ReactDOM.render((
    <Provider store={store}>
      <Router history={history}>
        <Route path="/" component={App}>
          <IndexRoute component={Home} />
          <Route path="dashboard" component={UserIsAuthenticated(Dashboard)} />
          <Route path="signup" component={UserIsNotAuthenticated(SignUp)} />
          <Route path="profile" component={UserIsAuthenticated(Profile)} />
          <Route path="foo" component={Foo} />
        </Route>
      </Router>
    </Provider>
  ),
  document.getElementById('root')
)


texts: JSONRPC method should be specified for params: “undefined” while attempting to batch transactions with web3

texts:
I am attempting to batch the following transactions:
const txBatch = new web3.BatchRequest()

txBatch.add(tokenInstance.methods.approve(contract_address, allowance).send({ from: account }))

txBatch.add(contractInstance.methods.sendToken(value, memoUINT64).send({ from: account }))

txBatch.execute()

However I get an: Error: JSONRPC method should be specified for params: "undefined"!
Any help on how to resolve this would be greatly appreciated!


texts: Can I automate the truffle (smart contracts) test scripts?

texts:
As we all aware about smart contract testing using truffle framework.
Currently, we are writing the test scripts either in solidity or in java-script manually.
Is there any way so that I can auto generate the test scripts for my smart contracts without doing hard coding??
What are the APIs for smart contracts? How to use those APIs?

Eventually, I want to develop a generic code which is capable of writing test scripts for smart contracts automatically, for which I just have to set the test cases in modular ways.


texts: How to read a data sent to my Smart Contract

texts:
How can I read/ get a data that has ben sent to my smart contract ?

I tested sendTransaction({data: xyz }) and when I tried to get this data from the Smart Contract using msg.data I got NULL this means the data wasn't sent to the SC , any help ? a need the line code of the transaction with a data


texts:
I wanted to do a get() to return some contract information, including an array, but when I put it gives this error:

browser/leilaoSimples.sol:34:9: TypeError: Data location must be "memory" for return parameter in function, but none was given.
uint[] _historicoDeOfertas
^------------------------^

function get() public view returns(
        address _dono,
        uint _contadorDeOfertas,
        address _comprador,
        uint _ultimaOferta,
        uint[] _historicoDeOfertas
    ){
        return(
            dono,
            contadorDeOfertas,
            comprador,
            valorAtual,
            ofertas
        );
    }

Full code (Note: it's in Portuguese)

pragma solidity >=0.5.1 <0.6.0;

contract leilaoSimples{
    uint valorAtual;
    address payable comprador;
    address dono;
    string nome;
    uint contadorDeOfertas = 0;
    uint[] ofertas;

    constructor(uint valorInicial) public{
        valorAtual=valorInicial;
        dono = msg.sender;
    }

    function set() public payable{
        uint oferta = msg.value;
        require(oferta>valorAtual, "Oferta abaixo do valor atual.");
        require(comprador!=msg.sender, "Você deu o último lance.");

        comprador.transfer(valorAtual);

        valorAtual = oferta;
        contadorDeOfertas++;
        ofertas.push(valorAtual);
        comprador = msg.sender;
    }

    function get() public view returns(
        address _dono,
        uint _contadorDeOfertas,
        address _comprador,
        uint _ultimaOferta,
        uint[] _historicoDeOfertas
    ){
        return(
            dono,
            contadorDeOfertas,
            comprador,
            valorAtual,
            ofertas
        );
    }
}


texts:
I have a HelloWorld contract and Keystore contract, both deployed in my truffle console.

When I read the Helloworld's public attribute balance, I get a value.
When I try to read Keystore's public array of owners (addresses), it fails.

Why?

contract HelloWorld {
  uint public balance;

contract Keystore {
  address[] public owners;

truffle(development)> hw.balance
{ [Function]
  call: [Function],
  sendTransaction: [Function],
  request: [Function: bound ],
  estimateGas: [Function] }
truffle(development)> hw.balance.call()
BigNumber { s: 1, e: 3, c: [ 1000 ] }

truffle(development)> ks.owners
{ [Function]
  call: [Function],
  sendTransaction: [Function],
  request: [Function: bound ],
  estimateGas: [Function] }
truffle(development)> ks.owners.call()
Error: Invalid number of arguments to Solidity function
    at Object.InvalidNumberOfSolidityArgs (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:41471:16)
    at SolidityFunction.validateArgs (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:327892:22)
    at SolidityFunction.toPayload (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:327908:10)
    at SolidityFunction.call (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:327949:24)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:316821:16
    at new Promise (<anonymous>)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:316812:18
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)

EDIT:

Error trying to call with param:

truffle(development)> ks.contract.owners(0)
Error: VM Exception while processing transaction: revert
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:41484:16)
    at RequestManager.send (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:329505:22)
    at Eth.send [as call] (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:37994:58)
    at SolidityFunction.call (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:327953:32)
    at SolidityFunction.execute (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:328078:22)
    at evalmachine.<anonymous>:1:13
    at ContextifyScript.Script.runInContext (vm.js:59:29)
    at Object.runInContext (vm.js:120:6)
    at Console.interpret (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:202629:17)
    at ReplManager.interpret (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:203345:18)
truffle(development)> ks.owners
{ [Function]
  call: [Function],
  sendTransaction: [Function],
  request: [Function: bound ],
  estimateGas: [Function] }
truffle(development)> ks.owners.call(0)
Error: VM Exception while processing transaction: revert
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:41484:16)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:329530:36
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:325200:9
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:328229:7)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:176415:18)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:176705:12)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:176860:12)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:176820:24)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
truffle(development)>


texts: Problem with more than one light node peer connection

texts:
I have the following nodes running :

FULL NODE and LIGHT SERVER

geth --datadir node1 --port 30303 --rpc --rpcport 3003 --rpcaddr 127.0.0.1 --ipcpath node1/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.1 --wsport 3103 --wsorigins "*" --lightserv 80

LIGHT NODE

geth --datadir node2 --port 30304 --rpc --rpcport 3004 --rpcaddr 127.0.0.2 --ipcpath node2/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.2 --wsport 3104 --wsorigins "*" --syncmode light

LIGHT NODE

geth --datadir node3 --port 30305 --rpc --rpcport 3005 --rpcaddr 127.0.0.2 --ipcpath node3/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.2 --wsport 3105 --wsorigins "*" --syncmode light

Node2 is a peer of Node1 and everything works correcty, but Node3 cannot connect to the fullnode and I get the following error:

Synchronisation failed, retrying         err="peer is unknown or unhealthy"

Using --verbosity 6 :

DEBUG[02-10|22:23:18.459] Adding p2p peer                          name=Geth/v1.8.19-stable-... addr=127.0.0.1:30301 peers=1
TRACE[02-10|22:23:18.459] connection set up                        id=6e6521711faf66d0 addr=127.0.0.1:30301 conn=staticdial                              inbound=false
TRACE[02-10|22:23:18.459] Starting protocol les/2                  id=6e6521711faf66d0 conn=staticdial
TRACE[02-10|22:23:18.459] Dial task done                           task="staticdial 6e6521711faf66d0 127.0.0.1:30301"
TRACE[02-10|22:23:18.459] New dial task                            task="wait for dial hist expire (29.977287427s)"
DEBUG[02-10|22:23:18.459] Connect new entry                        enode=6e6521711faf66d0
DEBUG[02-10|22:23:18.459] Light Ethereum peer connected            id=6e6521711faf66d0 conn=staticdial                              name=Geth/v1.8.19-stable
TRACE[02-10|22:23:18.466] Registering sync peer                    peer=6e6521711faf66d0
DEBUG[02-10|22:23:18.466] Received new announcement                id=6e6521711faf66d0 conn=staticdial                              number=10494 hash= reorg=0
DEBUG[02-10|22:23:18.466] Registered new entry                     enode=6e6521711faf66d0
DEBUG[02-10|22:23:18.466] Light Ethereum message handling failed   id=6e6521711faf66d0 conn=staticdial                              err=EOF
TRACE[02-10|22:23:18.466] Unregistering sync peer                  peer=6e6521711faf66d0
DEBUG[02-10|22:23:18.466] Disconnected old entry                   enode=6e6521711faf66d0
DEBUG[02-10|22:23:18.466] Removing p2p peer                        id=6e6521711faf66d0 conn=staticdial                              duration=7.280ms peers=0 req=true err="too many peers"

It seems like it is possible to connect just one light node. Any idea how to solve it?


texts: withdrawEth - undeclard indentifer error

texts:
can some help: I am getting withdrawEth - Undeclared indentifier error compiling the below contract:
contract MyToken is ERC20, Pausable, Ownable {
    event MTKBuyEvent (
        address from,
        address to,
        uint256 amount
    );

    event MTKSellEvent (
        address from,
        address to,
        uint256 amount
    );

    mapping (address => uint256) pendingWithdrawals;

    constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) public {
        _mint(msg.sender, 1000);
    }

    // A wallet sends Eth and receives MTK in return
    function buyToken(uint256 _amount) external payable {
        // Ensures that correct amount of Eth sent for MTK
        // 1 ETH is set equal to 1 MTK
        require(_amount == ((msg.value / 1 ether)), "Incorrect amount of Eth.");
        transferFrom(owner, msg.sender, _amount);
        emit MTKBuyEvent(owner, msg.sender, _amount);
    }

    // A wallet sends MTK and receives Eth in return
    function sellToken(uint256 _amount) public {
        pendingWithdrawals[msg.sender] = _amount;
        transfer(owner, _amount);
        **withdrawETH();**
        emit MTKSellEvent(msg.sender, owner, _amount);
    }
}


texts: How can a run a 'Dev' instance and have Mist running on Geth at the same time?

texts:
I have Mist open and running on the Geth Node but want to run a local dev environment using geth --datadir ./.ethereum/devnet --dev console.

Is this possible?


texts:
I thinking of developing some kind of application in which I need to have some kind of public key cryptography done by the smart contract. The sender sends some data to the smart contract encrypyted by smart contract's public key, will the smart contract be able to decrypt it, using the smart contracts private key ? While the smart contract decrypts the data, will everyone be able to see the plain text since its replicated on all the nodes ?

Since the smart contract is replicated on all the nodes across the network, will every one be able to see all the contents of the smart contract ?


texts:
I am trying to create my own token and confused a bit. As I understood from the documentation all information about adresses and tokens amount is stored inside contract (ERC20 - mapping(address => uint256) balanceOf). But somebody says to me that token could be sold using services like myetherwallet by uploading wallet. That is weird.

So my questions are following:

Am I right that once contract implemented ad uploaded ALL information about token transfers, sells and buys stored in the contract itself?
How understand statement like "myetherwaller supports ...coin"? Does it means that I can sell tokens outside contract?
How to make my token world-wide-available? Or just need to provide a way to exchange ETH -> Token?
Am I right that token name could be any, even duplicate existing one, but shortname (ERC20 symbol) must be unique?


texts: Convert address to string after solidity 0.5.x

texts:
After solidity 0.5.x release none of conversions from address to string appear to be working. I've tested all of them on remix and got errors like converting bytes to uint or something like this.

This one reverts remix:

function toString(address x)
    external pure
    returns (string memory)
{
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++)
        b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
    return string(b);
}

This one shows me that something is not allowed from bytes1 to uint256

function addressToString(address _addr) public pure returns(string memory)
{
    bytes32 value = bytes32(uint256(_addr));
    bytes memory alphabet = "0123456789abcdef";

    bytes memory str = new bytes(51);
    str[0] = '0';
    str[1] = 'x';
    for (uint i = 0; i < 20; i++) {
        str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
        str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
    }
    return string(str);
}

Is there any proper way to convert address to string? Even if through bytes or bytes32.

The reason why I need this is I have a privileges contract with string => PrivilegeData mapping and Im' calling global privileges from that string like "voting_time_limit". For specific addresses I would like to use calling by address parsed to string  like "0x252f...".


texts: 'Runs (Optimizer) ' and 'Optimization' while verifying source code on Etherscan

texts:
This is about the parameters that we need to provide at the time of source code verification on Etherscan. I have a bit idea about it but i am looking for some deep and clear explanation.

So my question is what are these parameters i.e  runs and optimization all about. Answer can consist the detail about:

How they exactly affect the source code verification?
Why enabling
optimization sometimes prevents smart contract verification?
Why we
usually pass 200 to runs?


texts: Getting unexpected output in Solidity + web3

texts:
I have a solidity function:

function something(bytes32 hash) public returns (bool) {
    bool success;
    success = check(hash);
    emit LogSomething(msg.sender, hash, success);
    return success;
}

and I try to show its result on Web3:

contractInstance.something(hash, params, function(error, result){
    if (error) {
        alert("Error!");
    } else {
        $("span#result").text(result);
    }
})

However, in my result span, I get the transaction hash:

0xd0039716e5834ac880f3b66e024c29e4b25cdf69e26b4f19e278f116d6a2fec2

instead of a True or False as expected from a boolean output. Why is this so? There are no error messages whatsoever and I'm confident in the code logic.


texts: How to sign a message using Ethereum private key, locally without running a full node?

texts:
I need to sign locally, on a client (preferably in a browser) a message using my Ethereum private key. How can it be done without running full node locally? Message does not need to be sent to blockchain.

I have found this answer, but I am looking for more details and best practices. For example, what function of web3.js is the best to use?
I have also asked more specific question about web3.js functions here.


texts: Why fallback function cannot be declared public in solidity?

texts:
When declaring fallback function we needs to make sure that it is declared external but why fallback function cannot be declared as public. Since external is a subset of public why can't we declare the fallback function public.
Viewing from the perspective of definition of external(Only accessible externally not internally). Why do use external in fallback?


texts: Ropsten infura test network + web3 js event listener

texts:
I have deployed contracts on ropsten test network.
truffle.js

ropsten: {
  provider: function() {
    return new HDWalletProvider(mnemonic, "https://ropsten.infura.io/<api-token>")
  },
  network_id: '*',
  gas:"4000000"
}

store.sol

pragma solidity ^0.4.17;

contract SimpleStorage {
  uint myVariable;
  event emitval();

  function setValue(uint x) public {
    emitval();
    myVariable = x;
  }

  function getValue() public returns (uint) {
    emitval();
    return myVariable;
  }
}

In my node js code I am using web3 js to call/listen methods/events from contracts.

my node js file is

web3.setProvider(new Web3.providers.WebsocketProvider('https://ropsten.infura.io/<api-token>'));

and for listening events I wrote

var contracts = new web3.eth.Contract(importedjson.abi, deployedaddressat)

contracts.events.emitval(function(error, result){
    if(error) { console.log(error);}
    else { console.log('Event setVal:', result);}
})

When I am calling methods of solidity (setValue() or getValue() which emits emitval() event), I am not able to listen it on node js code.

Could you please help me out.
I am uisng latest web3js version "1.0.0-beta.33".


texts: How to extract the URL of a crypto art as it appears within the NFT? and technical details like ERC-token type?

texts:
The following piece of crypto art has a title, description, and additional details regarding file and image size, provided by the NFT platform (Makersplace) where the artist (Lumi) minted the NFT for the image.

https://makersplace.com/lumi/trajectory-3-of-10-48596/

How can I view the URL link to the associated image file as it appears within the metadata/code of the NFT itself? and get technical details such as whether the NFT is an ERC-721 or ERC-1155 token?


texts: Do economic bets by miners fail to ensure security if the Notional Value of a contract exceeds that of the largest such bets?

texts:
A Smart Contract could be written to track a notional value greater than that of the value of ethereum contained in the contract, or even that of the stake of the miners in Proof of Stake, or the value of a bet implied by Proof Of Work.

For example there could be a contract that allows bets on off-blockchain gold futures, or some other off-blockchain measure of value, where the notional value of the bet is a significant fraction of outstanding ether on Ethereum, but doesn't actually use Ether to represent the value of the bet, but where the contract is merely used to irrefutably annotate the status of the bet.

If that notional value is a lot larger than the value of economic bet made by miners (in units of Ether), then it seems economically feasible to bribe miners to make the bet go in favor of the briber, e.g. by altering the contract's contents on a successfully bribed fork.

Is this actually a problem?  If so, is the answer to this question "don't do that"?  If that answer is "don't do that", then what's a good way to calculate the upper limit for notional value tracking on Ethereum?


texts:
I'm trying to build the frontend of a dApp, but the web3js makes my head hurt. I need to include it in my project, but the latest web3.min.js i can find is this. I want to use 1.2.1, and i understand that i need to bundle it together using browserify or something like that and then adding it as a js script.
Do any of you guys know of a guide to explain how i bundle together web3?

many thanks.


texts:
When a block is being mined nonce will be generated so that the nonce is appended with the previous block hash,data. Then the resulting hash of that appended value should be less than the target.

The question is Until the correct nonce is generated , will the nonce be appended to the previous block hash,data OR  for each try the nonce gets appended to the total hash produced by the previously produced nonce ?


texts:
Two months ago, I wrote solidity contracts on remix.ethereum.org. They compiled and ran fine.

This code, which you can see here https://gist.github.com/anonymous/1b5c669c09683f285d44c36ab40555dd , has multiple contracts.  Two of which are:

TestToken
TestSale

In TestSale, there is a line that is:

TestToken public token = new TestToken();

When I created TestSale two months ago, remix will show TestSale's address and TestToken's address.  Now, remix's interface has changed and I do not see TestToken's address.  How do I get it?


texts: How to send transaction to Infura node using Web3?

texts:
I want to send ETH from one account to another using Web3 interface and Infura node. I have tried like below, and I got error 405(). Error: Invalid JSON RPC response: ""

I test it in Rinkeby test network.
This is how I initialize Web3 and do the transaction.

<script>
        $(document).ready(function () {
            const Web3 = require('web3');
            const web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/<Access_Token>'));

            $(".btn-send").click(function () {
                web3.eth.sendTransaction(
                    {
                        to: '0xae8cE2D0B2015Aeb62189822C7eEae2f60B011e5',
                        from: '0x5ada788989dCa813cBE82eD8bB8d54e1b43327A7',
                        value: web3.toWei("1", "ether")
                    },
                    function (error, transactionHash) {
                        if (!error) {
                            console.log("send successfully");
                        } else {
                            console.log("Error: " + error);
                        }
                    }
                );
            });
        });
</script>


texts: If a contract didn't allocate initial supply,what will happen?

texts:
Please Have a look at this contract

0x253b898233d2f29ed9c8d499789d651cf9d1818c created this contract,but if you check its source code,you will notice that the contract name is uppercased:

Yet the "construction function" is lowercased:

So this is a fake construction function.Below sentence will never run:

balanceOf[msg.sender] = totalSupply;

So,the contraction creator will not get the whole tokens.And this is the truth,because if we check the whole transaction history of this contract,you will see that the first transaction is sent by 0x42050d23c77b4997b3dc6dca97a45b7b1fd8adaa,which is not the creator of this contract.
So,why does 0x42050d23c77b4997b3dc6dca97a45b7b1fd8adaa has the whole supply tokens since it's not the contract creator?


texts:
I am trying to run a test script for my smart contract but ganache provider is not being accepted by web3 here is my code.

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

beforeEach(()=>{
  web3.eth.getAccounts()
    .then(fetchedAccounts=>{
      console.log(fetchedAccounts);
    });
});

describe('Inbox',()=>{
  it('deploys a contract',()=>{

  });
});

This is error message

/home/ace/Desktop/ETH/inbox/node_modules/web3-providers/dist/web3-providers.cjs.js:720
      throw new Error('Please provide an valid Web3 provider');
            ^
Error: Please provide an valid Web3 provider
    at ProviderResolver.resolve (/home/ace/Desktop/ETH/inbox/node_modules/web3-providers/dist/web3-providers.cjs.js:720:13)
    at Web3.AbstractWeb3Module (/home/ace/Desktop/ETH/inbox/node_modules/web3-core/dist/web3-core.cjs.js:27:51)
    at new Web3 (/home/ace/Desktop/ETH/inbox/node_modules/web3/dist/web3.cjs.js:30:68)
    at Object.<anonymous> (/home/ace/Desktop/ETH/inbox/test/Inbox.test.js:5:14)
    at Module._compile (internal/modules/cjs/loader.js:736:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
    at Function.Module._load (internal/modules/cjs/loader.js:560:3)
    at Module.require (internal/modules/cjs/loader.js:665:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at /home/ace/Desktop/ETH/inbox/node_modules/mocha/lib/mocha.js:250:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/home/ace/Desktop/ETH/inbox/node_modules/mocha/lib/mocha.js:247:14)
    at Mocha.run (/home/ace/Desktop/ETH/inbox/node_modules/mocha/lib/mocha.js:576:10)
    at Object.<anonymous> (/home/ace/Desktop/ETH/inbox/node_modules/mocha/bin/_mocha:637:18)
    at Module._compile (internal/modules/cjs/loader.js:736:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
    at Function.Module._load (internal/modules/cjs/loader.js:560:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
    at executeUserCode (internal/bootstrap/node.js:526:15)
    at startMainThreadExecution (internal/bootstrap/node.js:439:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! inbox@1.0.0 test: `mocha`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the inbox@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ace/.npm/_logs/2019-02-07T14_24_38_841Z-debug.log


texts: How does solc generate the bytecode for a contract?

texts:
I got sick of using remix and copying-pasting my web3 deploy text so I'm trying to write a python script that will generate this deploy test for me. However, one of the fields in the instantiation code is data, and it holds a bytecode representation of the contract. How can I generate this bytecode as well? I'm unable to use py-solc for some reason (when I type from solc import * I get a ModuleNotFound error) so if I could recreate this bytecode manually that'd be awesome.

Here's an example of what I'm trying to do:

for smart contract "Storage.sol" below:

pragma solidity ^0.4.0;

contract Storage {
    uint storedData;
    address lastSetter;
    function set(uint x) public {
        storedData = x;
        lastSetter = msg.sender;
    }

    function get() public constant returns (uint) {
        return storedData;
    }

    function getLastSetter() public constant returns (address) {
      return lastSetter;
    }
}

Remix generates this web3 deploy:

var storageContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"getLastSetter","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]);
var storage = storageContract.new(
   {
     from: web3.eth.accounts[0],
     data: * long hex number *,
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

My script can make this:

var storageContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[],"payable":false,"stateMutability":"type":"function"},{"constant":true,"inputs":[],"name":"getLastSetter","outputs":[],"payable":false,"stateMutability":"type":"function"},])
var storage = storageContract.new(
    {
        from: web3.eth.accounts[0],
        data: '',
        gas: '470000'
    }, function(e, contract){
        console.log(e, contract);
        if (typeof contract.address != 'undefined') {
          console.log('Contract successfully mined. address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
})

(still figuring out the statemutability (what even is that?) and output parsing as well, but thats a question for another day)

To sum up, I am trying to write a Python script that goes from solidity to the 'web3 deploy' text remix generates. How can I generate the required bytecode field?

Edit: I bit the bullet and tackled my installation of py-solc again. Got it right this time; I was accidentally installing using pip2.x rather than pip3.x. I'd still like to know how py-solc generates the bytecode, but the project works know. Thanks all for your help


texts: How would I calculate how much it would cost to store the string "hello world" on an Ethereum block? Would this be more or less than a transaction fee?


texts: Where is contract persistent storage stored?

texts:
I am trying to work out where the data is actually stored. If a contract is deployed with a dynamic array defined, then at the time of deployment no allocation is made for the storage.

I understand there is a sha addressing based system to a disk location for the state variables. But where is that storage? Is this part of the blockchain node?

If the persistent storage is defined based on the contract instance and the storage is dynamic, there must be some kind of pointer to storage.

My reason for asking about this, is to address the scaling question. If contracts start defining large dynamic arrays in state, then the blockchain will need to manage that across the nodes.

I know also a hash tree is kept with a root hash on each node but that does not explain how the state variables are stored in persistent storage for a contract instance.


texts:
when i compile the following code :

pragma solidity ^0.4.22;

contract SimpleAuctions {
    uint  public beneficiary; // 拍卖的受益人
    uint public auctionEnd; // 拍卖的结束时间
    address public highestBidder; // 当前的最高出价者
    uint public highestBid; // 当前的最高出价
    mapping(address => uint) pendingReturns; // 用于取回之前的出价
    bool ended; // 拍卖是否结束
    uint valueforbeneficiary;
    event HighestBidIncreased(address bidder, uint amount); // 出现新的最高价
    event AuctionEnded(address winner, uint amount); // 拍卖结束
    function SimpleAuction(uint[] valueforgoods) public pure {
        uint allvalue;
        uint i;
        for (i = 0;i < valueforgoods.length;i++){
            allvalue = allvalue + valueforgoods[i];

             if (valueforgoods[i] > highestBid) {
                highestBid = valueforgoods[i];
            }
        }
    }
    function bid() public payable {
        require(
            now <= auctionEnd,
            "Auction already ended."
        );
        require(
            msg.value > highestBid,
            "There already is a higher bid."
        );
        if (highestBid != 0) {
            pendingReturns[highestBidder] += highestBid;
        }
        highestBidder = msg.sender;
        highestBid = msg.value;
        // beneficiary = allvalue;
        emit HighestBidIncreased(msg.sender, msg.value);
    }

    function auctionEnd() public {
        require(now >= auctionEnd, "Auction not yet ended.");
        require(!ended, "auctionEnd has already been called.");
        ended = true;
        emit AuctionEnded(highestBidder, highestBid);
        beneficiary.transfer(highestBid);
    }
}

i come with :Member "transfer" not found or not visible after argument-dependent lookup in uint256 beneficiary.transfer(highestBid)".How to modify it?


texts: Is there any other way of passing value in constructor function without web3js?

texts:
Q1: Is there any other way of passing value in a constructor function without using web3js object.

Q2: And in the below code whenever this contract is called will that be recompiled or wil just the value be updated?

  pragma solidity ^ 0.4.8 ;

  contract lastPrice {
     uint price ;
     uint lprice ;

     function lastPrice (uint _price) {
        lprice = (_price * 1 ether);
       }

     function showPrice () constant returns (uint) {
        return lprice ;
     }
   }


texts:
while designing my contracts, I'm wondering if its better to use a struct, and then one mapping that holds that struct type as the value. Or use a bunch of different individual mappings and no struct? In terms of 'better' I guess just general Solidity standards and gas wise.

I read this question's answer: What is better, mapping a struct with 2 variables or having 2 mappings?

And the user chose to use the solution that cost more gas because it was cleaner. Is this the correct choice? In my situation I'd be storing about 8 variables in the struct, or have 8 different mappings.

Thanks!


texts:
It seems that allocating storage elements is 4x as expensive in terms of gas cost than changing them.

Does that mean it would make sense to pool structs and arrays, and maybe also strings, rather than recreating them? Did anyone see such a pattern in solidity?


texts: How do I figure out how much USD it will cost to deploy or execute methods on a contract?

texts: Is there a simple tool for this or do I have to calculate it myself?


texts: constructor input arguments or hardcoded values? best practice

texts: What is the rationale for choosing to use constructor input arguments over hardcoded values? and what is best practice?


texts: I would like to become a blockchain developer

texts: I would like some advice before deciding to become a blockchain developer. Any comment would be really appreciated, thank you in advance.


texts: how to price into a coin real assets backup

texts: For a coin that is backed up by real assets, how do we take that into consideration when setting a price? Should the price be driven by the community on the exchanges by offer and demand? any ideas to include in the price the back up valuation?


texts: can I return an address from a contract interface instead of another contract?

texts:
for example i have a contract function that returns a contract, can I define an interface that calls that function, but only returns an address?

contract foo {
   ....
   ....
}

contract bar {
   function getFoo() returns (foo);
}

Can I make an interface for bar that just returns an address instead of foo? like so:

contract barInterface {
   function getFoo() returns (address);
}

I can't change bar itself because it's a pre-existing contract


texts: How to reenter the "main" morden network without removedb?

texts:
I synced geth using the --fast option, and after the sync, I had a little freak-out because I had lost all my ether.
Actually the problem is that although I have peers, I have not the good testnet blockchain.

I tested the following hashes :

> eth.getBlock(0).hash
"0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303"
> eth.getBlock(1000000).hash
"0x933de4c85a76c1b0652b01d4c22b5f66b76bd44005f607574900ab8bfd4ae052"
> eth.getBlock(1500000).hash
"0x92b43a22a1b33f69397d9fa4d54271df8217635c447f331690c8c21df53b3eab"
> eth.getBlock(1800000).hash
"0xb39e009518615dd1e792537aea755d9b83446a4c504a7df6facd48a8a9345213"

As you can see, my genesis block is correct, as well as the blocks 1000000 and 1500000, and the block 1800000 is wrong.

I tried the following command :
for(i=0;i<admin.peers.length;i+=1) admin.removePeer(admin.peers[i].id)

but geth doesn't resync its blockchain.

Where can I find peers for Morden?
Is there a different solution from doing removedb and sync again? I have no guarantee that it won't make a fork again!


texts: Help me Obi Wan Kenobi.... I need some assistance with understanding etherscan and where my erc20 tokens went

texts:
First post, thanks in advance for any help.  Back in early 2018 I setup some friends with  MEW wallet when they had purchased some Trx while it was still and erc20 token.  I know mainnet happened etc and they basically never looked or did anything with it and just asked yesterday about getting it moved over or traded to mainnet via Binance.  When I opened their wallet today we didn't see the trx tokens, about 102k.  I followed the custom token instructions add instructions from the medium post and still nothing.  I can see some type of action happened and that the tokens were there and interacted with the trx contract but I'm just at a loss I can't tell if they went to some type of contract holding or maybe to binance.  It is possible we had consolidated their tokens to another wallet and they accidentally made a copy of the wrong paper wallet but I can't tell.  Could drop some knowledge on me here as to what happened?
Here's the wallet address:  0xdC1D5aAc95a29a5Ee9938aa09397a679180Bc894
only 2 transactions with it so not a lot to sort through.  Any help is greatly appreciated.


texts:
I have an issue to setup ip address for node I run on my machine.

The command is

docker run -it -p 8545:8545 -p 30303:30303 -v /home/user/Workspace/myether/datadir1:/root/datadir user/my-ether-node /bin/bash

I expect to see ip address, but id doesn't have it.

veth2c0a981 Link encap:Ethernet  HWaddr 6e:41:c9:a5:83:ac
          inet6 addr: fe80::6c41:c9ff:fea5:83ac/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:7 errors:0 dropped:0 overruns:0 frame:0
          TX packets:46 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:586 (586.0 B)  TX bytes:6320 (6.3 KB)

I will need on the second stage when I have to publish enode

I have connection to the network.

Any advice?


texts:
I am a newbie in mining, I have a couple of shitty laptops around 8-16gb ram and an Intel graphics card.
I don't pay for the electricity and don't really care if the laptop dies. I tried to search around if I can mine ETH in this laptop. but all the software wants me to set up the miner with parameters related to the AMD or Nvidea graphics card. Could anyone suggest me any miner which is easy to setup and will work for my case?


texts: My tokens and basic setup scripts are built in solidity 0.8.0 and I just downloaded GSN with OpenZeppelin because I need a platform which will fund users' few things. Now I can't compile because it shows me there are different SOLC versions. This situation forced me to split project into tokens (and few contracts among them) and platform, which is downgraded to 0.6.10 and exported separately. To make it working I need to copy and paste interfaces between projects, paste raw addresses in migrations, it makes mess in the entire project. How can I build everything at one project?


texts:
Can I see a not processed pool of transactions?
I want to see my transaction in line, how many transactions before and other interesting unknown for me information. :)
As I understand transaction to include in a block when the queue will coming. Of course, we have to remember about gas prise what we use in a transaction.
Can I see that list anywhere?


texts: How do I program BTC Relay into my dapp?

texts:
The description of BTC Relay seems pretty cool.  So how do I use it practically?

Dumb question - I'm a non technical person.  Let's say I was building an estore which runs off of contracts.  How would I code in HTML or Java BTC Relay.

Please excuse my lack of knowledge in the subject.


texts: Truffle Error : VM Exception while processing transaction: revert

texts:
I am trying to call following function of smart contract from App.js:

function addCandidate(bytes32 _name, bytes32 _party) public{
    //require(msg.sender == votingAdmin);
    //if(msg.sender != votingAdmin) throw;
    candidates.length++;
    candidates[candidates.length-1].id = candidates.length-1;
    candidates[candidates.length-1].name = _name;
    candidates[candidates.length-1].party = _party;
    LogNewCandidate(msg.sender,candidates.length-1,_name,_party);
}

Code in App.js is :-

Voting2.deployed().then(function(contractInstance) {
    var candidate_name = document.getElementById('candidate_name').value;
    var candidate_party = document.getElementById('candidate_party').value;
    contractInstance.addCandidate(candidate_name,candidate_party,{from: web3.eth.accounts[0], gas:3000000}).then(function(v) {
        console.log(v.toString());
    });
});

Error -

Error: VM Exception while processing transaction: revert
    at XMLHttpRequest._onHttpResponseEnd (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at XMLHttpRequest._setReadyState (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest.request.onreadystatechange (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at /home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
    at /home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at Object.InvalidResponse (/home/vatsal/hello_world_voting/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)

However there is another function written in smart contract and I am successfully able to call it

function getCandidatesCount() public constant returns(uint) {
    return candidates.length;
}

Code in App.js

Voting2.deployed().then(function(contractInstance) {
  contractInstance.getCandidatesCount.call().then(function(v) {
    console.log(v.toString());
  });
});

So, I am not able to execute transaction but I am able to read value returned from a function.


texts: I am developing a dapp in which I need to store large number of employee/customer name or id. Can I use array or map in my smart contract code? Will it increases the smart contract memory as number increase? Which one is the best suited way?


texts:
In the datamarket project

http://datamarket.at/

we would like to guard access to digital assets (data, services) which will  not be stored on the Ethereum ledger. We will guard access to these assets using smart cotnract.

Is there a mechanism within the Ethereum ecosystem which would support the creation of unique links to a digital asset only available to the party for which the contract succeeded?

I am thinking of something based on maybe Swarm where I can upload data to and once a contract succeeds, a unique link can be created through which access to the guarded resource is provided. Forwarding this link to another one should not result in access to this shared resource and ideally be tracked as a violation.


texts: can not open parity after remove some old sst files

texts:
I am using the parity on my mac, due to the limited hardware space, i deleted two olddest sst files under the path

'/Users/abc/Library/Application Support/io.parity.ethereum/chains/ethereum/db/906a34e69aec8c0d/overlayrecent/db'

now I can't open the parity, what should I do to reopen it again, if I can't open how would i get back my account?


texts: how can i show the value(uint256) in contract

texts:
I made a webapp by modifying it from https://github.com/RedSquirrelTech/hoscdev/tree/master/chapter-10%2B11 for newFundraiser.js
I have it sent in monetary value, it will be msg.value and saved as uint256, but in FundraiserCard.js. I could not show that value, it went up to 0, But the balance of the address being sent is deducted equal to the number entered.
I run on the ganache network and my wallet is Metamask
in Fundraiser.sol
constructor(uint256 _number ,address _custodian  ) public {
         number = _number ;
        transferOwnership(_custodian);}

in FundraiserFactory
function createFundraiser ( ) public  payable{
   Fundraiser fundraiser = new Fundraiser(msg.value,msg.sender);
   _fundraisers.push(fundraiser);
   emit FundraiserCreated(fundraiser, msg.sender);
  }

in NewFundraiser.js
const handleSubmit = async () => {
  const number = web3.utils.toWei(numbers.toString())
  const transaction = await contract.methods.createFundraiser().send({
      from: accounts[0],
      value: number ,
      gas: 2000000
    })
}

in FundraiserCard.js
 const [ number, setNumber] = useState(null)
      const numbers = await instance.methods.number().call()
      const number = web3.utils.fromWei(numbers)
      setNumber(number)
return
number: {number}


texts: Is "geth debug trace_2" on "Etherscan.io" a native geth output?

texts:
I am aware of the debug_traceTransaction function.
On Etherscan.io there is an option to view transaction, called Geth Debug Trace_2, which produces output in a format that I need. The option is here:

And the output looks like this

    {
    "type": "CALL",
    "from": "0x5c0c754e08d545e219e0dc8c440f934dc12bac7f",
    "to": "0x4fa2cc6ad3f94e0f99111943985c24d7d3f188cf",
    "value": "0x2386f26fc10000",
    "gas": "0x12e48",
    "gasUsed": "0x1e48",
    "input": "0x312e5a61000000000000000000000000fe89009eda90321fd48f9c6b97bcf4e86a79f71c",
    "output": "0x",
    "time": "3.0075ms",
    "calls": [
        {
        "type": "CALL",
        "from": "0x4fa2cc6ad3f94e0f99111943985c24d7d3f188cf",
        "to": "0xfe89009eda90321fd48f9c6b97bcf4e86a79f71c",
        "value": "0x2386f26fc10000",
        "input": "0x"
        }
    ]
    }

My question is: can I obtain data from geth in a same format or does Etherscan calculate that data based on debug_traceTransaction ?


texts: web3 estimateGas() from fallback function

texts:
When I sign and send raw transactions with web3 in javascipt , to call a method from Smart Contract, I always pass the transaction gas variable after getting it with estimateGas function, from Smart Contract method, as following:
mySmartContract= new web3.eth.Contract(SmartContractABI, SmartContractAddress);
mySmartContract.methods.set(inputnum).estimateGas({from: miAddress})
      .then(function(gas){
          tx.gas = web3.utils.toHex(gas);
        })
      .catch(function(error){
        console.log("Set() - catch error");
        console.log(error);
      });

How could I do the same to invoke the fallback function from the Smart Contract?
estimateGas() is a function from "methods" object, but "fallback" is not a method.
Thanks in advance


texts:
I have a contract deployed on Rinkbey which stores some information. Now, I want to create a new block every time a write a data to contract. I am calling send() method of web3 to instantiate a block on every call and I am getting transaction ID for every block. And Later by using that transaction ID I am able to view the data stored on blocked.
Is it the right way?


texts: web3.py - AttributeError: 'Eth' object has no attribute 'get_block'

texts:
So... I'm probably being super dumb - but I started using web3.py in a jupyter notebook and it connects to the node just fine... but I can't seem to use any .eth methods as it throws a: AttributeError: 'Eth' object has no attribute 'get_block'
Versions:

w3.api
'5.0.0'
Python: 3.9.1
OS: osx

from web3 import Web3
w3 = Web3(Web3.HTTPProvider('http://fullnode.dappnode:8545'))

w3.isConnected() returns True, and I can use w3.api and w3.clientVersion just fine... but when I try to do something eth related I get:
>>> w3.eth.get_block('latest')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-70b856a4c410> in <module>
----> 1 w3.eth.get_block('latest')

AttributeError: 'Eth' object has no attribute 'get_block'

or
w3.eth.chain_id
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-9e974a6bb0e9> in <module>
----> 1 w3.eth.chain_id

AttributeError: 'Eth' object has no attribute 'chain_id'


texts: How to view the arguments in events under truffle console?

texts:
Hello awesome ethereum community, Need help in viewing the arguments under event. I am using event AnyException for error handling. I pass a string argument to my event in my solidity file. When I run the function, I would like to view the string argument passed to my event. Currently, I just see args: [Object] . How do I vew the argument in truffle console?

EventTest.sol

pragma solidity ^0.4.15;
  contract EventTest {
    event AnyException(string message);

    function testEvent(string s) public returns (bool) {
      if (keccak256(s) == keccak256("titu")) {
        AnyException("Invalid input: titu");
        return false;
      }
      return true;
    }
  }

Truffle console

truffle(development)> var et; EventTest.deployed().then(function(deployed){et=deployed;});
undefined
truffle(development)> et.testEvent("titu");
{ tx: '0xcc99eeacdf9cf83aa82e4a1284a35eac71abfad85d91564fbbb4f611b7f52d69',
  receipt:
   { transactionHash: '0xcc99eeacdf9cf83aa82e4a1284a35eac71abfad85d91564fbbb4f611b7f52d69',
     transactionIndex: 0,
     blockHash: '0x81f8c761825b96985e222e713fa7e17f1cabee1a130ca7651e0f8e0f1ba72a12',
     blockNumber: 13,
     gasUsed: 24374,
     cumulativeGasUsed: 24374,
     contractAddress: null,
     logs: [ [Object] ] },
  logs:
   [ { logIndex: 0,
       transactionIndex: 0,
       transactionHash: '0xcc99eeacdf9cf83aa82e4a1284a35eac71abfad85d91564fbbb4f611b7f52d69',
       blockHash: '0x81f8c761825b96985e222e713fa7e17f1cabee1a130ca7651e0f8e0f1ba72a12',
       blockNumber: 13,
       address: '0x1940ce494ecf457feefa4d6874542353db01bf9f',
       type: 'mined',
       event: 'AnyException',
       args: [Object] } ] }


texts: Concealing sensitive data in a public contract

texts:
I have some sensitive data I'd like to keep in my contract in privacy.
I'd like to make a simple version of Zero-Knowledge Proofs and have an idea in mind. Let's say I have a customer who filled out 6 fields in my dapp:

First Name as attr1
Last Name as attr2
Birthdate as attr3
Phone number as attr4
Passport number as attr5

I am makinghash1=SHA2(attr1+attr2+attr3+attr4)
hash2=SHA2(attr1+attr2+attr3+attr5)

and store it in a map where hashes=[hash1,hash2]
A third party could  hash its dapp input using my scheme,query my contract and check if my dapp had this client. If true it can get metadata about found client, e.g. a credit score.

My questions are:

what do you think about this simple ZKP scheme? do you have any other ideas how to realize it?
how easy will it be for an attacker to make a lookup table with all hash1 or hash2 variants (most important question)
should I keep hash1/hash2 scheme in secret?


texts: ABIEncoderV2PackedStorage bug, is something to worry about? any info?

texts:
I have a simple factory of ERC-20 Tokens, deployed to Rinkeby using remix.

When I create contracts with this factory and verify the code in Etherscan (using etherscan API) I am having this warning in Etherscan:

  Warning: The compiled contract might be susceptible to
  ABIEncoderV2PackedStorage (low-severity) Solidity Compiler Bugs.

Sample here:

https://rinkeby.etherscan.io/address/0x55D65C01E8D445D166eE50Cf6076015d2F7Bd46e#code

Etherscan shows a broken link to the ABIEncoderV2PackedStorage bug

And I haven't seen any bug report about this ABIEncoderV2PackedStorage thing.

I this something I should worry about?

Any link or report about this bug in solidity?

Thanks


texts:
Currently I'm using ether.camp to create a contract. At this stage it simply gets and stores some values. However when I try and get the values they are in bytes/hex even though the return type is string?

How do I convert this back to string in the solidity contract? I've tried How to convert a bytes32 to string but no luck

E.g storing "Hello World!" returns  0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000

   contract HelloWorld {
    struct Items {
       address id;
       string data;
    }

    mapping(address => Items) items;

    function getItem(address key) returns (string) {
      return items[key].data;
    }

    function addItem (address key, string data) returns (bool) {
        Items item = items[key];
        item.data = data;
    }

   }

 }

I can see in the ethercamp transactions side bar of the IDE the "Hello World!" is saved as a string but my getItem() just can't retrieve it?


texts: Is it possible to decrease difficulty of ongoing private Ethereum blockchain?

texts:
Please note that my question is in addition to following question: How do I decrease the difficulty on a private testnet?. I am sorry that, I am lost in its answers.

[Q] Is it possible to decrease difficulty of ongoing private Ethereum blockchain (for example: blockchain already mined 491,312 number of blocks)? or should I create a new private Ethereum blockchain from 0th block to alter the difficulty?

I have applied @eth's solution https://ethereum.stackexchange.com/a/7159/4575 on my enode and released that difficulty is started to decrease, but I was not able to mine any of my upcoming transactions due to following error and so on:

Bad block #491231 (0x39e86646d54ad4a83ba41abc1192fb8e64bfcbf733aa2e5e94351fd168091068)
Difficulty check failed for header 914854

In addition to that, I was not sure to apply this solution on all nodes that are connected to me private ethereum network? or only on the enode that the peers connected into?

Thank you for your valuable help and time.


texts: Could not assign contract state variable value to javascript variable

texts:
I want to retrieve and assign the value of my contract state variable to my javascript variable.I am doing as per guidlines provided on this community, but failed to assigned. my javascript code is here
I am using Node js.

const contractAddress1 = '0xc1847e91e386e11e4df447b3e333f1b18abd1aca'
const contractABI = [{"constant":true,"inputs":[],"................];
var contract1  = new web3.eth.Contract(contractABI, contractAddress1)
var ot="raw";
contract1.methods.getTotalSupply().call().then(function(result){

  console.log(result)
  ot = result;
});
console.log("ot : ", ot);

and its output is :

ot :  raw
BigNumber { _hex: '0x2704' }

Why 'ot' has still value 'raw' , why not BigNumber { _hex: '0x2704' } ???


texts: Transfer ETH to 3rd part wallet with keystore - MEW does not recommend

texts:
Hi I have searched the similar questions and can’t find an answer.
I have mined eth about 2 years ago and have a balance in my wallet set up on geth.
I now want to transfer this to my brd wallet however I no longer have geth or want to install and download the blockchain just to transfer using mist. I am a very beginner user and forgot all that I learnt when I was mining.
My BRD wallet does not seem to support the transfer using the keystore file.
MEW strongly discourages using the keystore.
How am I to transfer if I don’t want to use geth/mist coz of the time for the download, etc., and all the 3rd party wallets strongly discourage using the keystore.
I am stumped, please help.


texts: What is the order of operations to verify a transaction?

texts:
I am not asking if all nodes run each transaction.  I'm asking for a rough time sequence of events.  For example, in the case of a double spend attempt, and the double spender is colluding with the miner who is adding the next block.  At what point does a random node in the network, who is participating in mining, verify this was incorrect and flag the issue?
- Is it only the next miner who gets to add a block who detects this issue?
- Does each node only verify/run the transaction the next time they participate in mining or only when they solve the PoW and get to add a new block?
- Next time they are online?
- Is there a trigger such that a full node who may be idle, needs to run the contract code and verify?

What if the next N miners are also colluding?  Does it require just one miner to flag the transaction as incorrect or N+1?

Obviously, all nodes cannot run that transaction before another block is built, so i'm hoping there is a ballpark timeline of events.


texts: Why Could not find artifacts for contract from any sources

texts:
I am using windows 10 with truffle and ganache-cli. I have 2 contracts file to be deployed contain interfaces of other contracts defined within the contract:

Contracts:

ERC721Mintable.sol

Ownable
Pausable is Ownable
ERC165
ERC721 is Pausable, ERC165
ERC721Enumerable is ERC165, ERC721
ERC721MetaData is ERC721Enumerable, usingOraclize
CraveuERC721Token is ERC721MetaData

Verifier.sol

SolnSquareVerifier.sol

pragma solidity >=0.4.21 <0.6.0;

import "./ERC721Mintable.sol";
import "./Verifier.sol";

contract SolnSqaureVerifier is CraveuERC721Token {

    SquareVerifier squareVerifier;

    constructor(address verifierAddress) public {
        squareVerifier = SquareVerifier(verifierAddress);
    }

Here's my deploy_contracts.js:

const SquareVerifier = artifacts.require("Verifier");
const SolnSquareVerifier = artifacts.require("SolnSquareVerifier");

module.exports = function(deployer) {
  deployer.deploy(SquareVerifier).then( () => {
    return deployer.deploy(SolnSquareVerifier, SquareVerifier.address);
  });
};

I am using truffle version 5.0.18

  Error Produced: Error: Error: Could not find artifacts for
  SolnSquareVerifier from any sources


texts: How to buy Ethereum in USA as a non-US citizen?

texts:
I am a non-US citizen studying in USA. I have tried to create a coinbase and a gemini account but it has been stuck in account verification for the last 2 weeks with no hope in sight.

I have a US bank account and would like to buy some ether from it. Is there a way to do it?


texts: How to choose between Ethereum, EOS, and TRON if I want to build a dapp?

texts:
In 2018, Ethereum dapps has $2.6 Billion worth transaction volume in 2018; EOS has $3.45B; TRON has $600M.

However, number of transactions on Ethereum is way less than EOS and TRON. Ethereum has a huge user base but TRON has a lot of incentives to offer and they have strong marketing support.

Data from Dapp Market Report 2018 by Dapp.com


texts: Can't deploy contract with web3.js and ganache-cli

texts:
I'm using the solc module to compile a Solidity contract.  The compilation step looks to be working correctly, however, when I attempt to deploy the contract to the Ganache network (in a Mocha test), the promise never resolves.  Here's what I've already checked:

1) Increasing the timeout to 3 minutes - still nothing

2) Another promise using await, which resolved correctly, so I don't think it's a Mocha config issue with promises

3) Estimated gas - I should have more than enough based on the estimateGas function

4) Updating all versions (web3, solc, ganache-cli) to their most recent versions

Here's the compile.js code:

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const contractPath = path.resolve(__dirname, 'MyContract.sol');
const source = fs.readFileSync(contractPath, 'utf8');

let jsonContractSource = JSON.stringify({
    language: 'Solidity',
    sources: {
      'Task': {
          content: source,
       },
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['abi',"evm.bytecode"],
             // here point out the output of the compiled result
            },
        },
    },
});

module.exports = JSON.parse(solc.compile(jsonContractSource)).contracts.Task.MyContract;

And the test file:

const ganache = require('ganache-cli');
const Web3 = require('web3');
const provider = ganache.provider()
const web3 = new Web3(provider);
const { abi, evm } = require('../../contracts/compile');

let accounts;
let myContract;

before(async function() {

    accounts = await web3.eth.getAccounts()

    myContract = await new web3.eth.Contract(abi)
        .deploy({data: "0x" + evm.bytecode.object, arguments: []})
        .send({from: accounts[0], gas: 5000000});

    console.log("finished")

});

EDIT: One other thing - I was able to deploy a contract to the Ganache network with Remix, so I think the problem is isolated to the ganache-cli.


texts: How can I simply sign an Ethereum transaction?

texts:
I want to use blockcypher to work with the Ethereum network.

In the documentation they give an example of a signer tool written on Go, but I'm use Python.

What is the simplest way to sign a transaction?

I tried using web3.py, but I ran into some difficulties.

Here they give the following example:

transaction = {
       'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
       'value': 1000000000,
       'gas': 2000000,
       'gasPrice': 234567897654321,
       'nonce': 0,
       'chainId': 1
}
key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'
signed = w3.eth.account.signTransaction(transaction, key)
signed.rawTransaction
HexBytes('0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428')
signed.hash
HexBytes('0xd8f64a42b57be0d565f385378db2f6bf324ce14a594afc05de90436e9ce01f60')
signed.r
4487286261793418179817841024889747115779324305375823110249149479905075174044
signed.s
30785525769477805655994251009256770582792548537338581640010273753578382951464
signed.v
37

But I do not understand some of the values that need to be passed to the transaction.

What is nonce, chainId?

Using such data:

transaction = {
    'to': '0xe980e77404ae62ab0f2d6b8510bd951e25185414',
    'value': value,
    'gas': 2000000,
    'gasPrice': 1000000000,,
    'nonce': 0,
    'chainId': 1
}

I get this error:

TypeError: Transaction had invalid fields: {'to': '0xe980e77404ae62ab0f2d6b8510bd951e25185414'}

Next, I tried to use ecdsa

But I was not able to find a simple example. I do not understand anything at all in cryptography, and I need the easiest way to send a transaction to the network without hammering through the details.

UPDATE

I tried to avoid using w3, since I only need to sign a transaction.

I was able to do this to create a signature:

import hashlib
import binascii

import ecdsa

def sign(privkey, message):
    sk = ecdsa.SigningKey.from_string(
        binascii.unhexlify(privkey),
        curve=ecdsa.SECP256k1,
        hashfunc=hashlib.sha256
    )
    signature = binascii.hexlify(
        sk.sign(
            binascii.unhexlify(message),
            hashfunc=hashlib.sha256
        )
    )
    return signature

And the function works fine, I return a byte string like this:

b'4ace74a83082b5fc6d356083932b493e9fafbe0fabca19be3e77ccda188d08c6352f1fccb144e18b95a3f7e18f71fe95d79a9dd8ad9ecaa7490315f06a00177f'

But the length of this line is 128 characters, and in the example of the blockcypher a string of 148 characters.

After trying to send a signed transaction to the network, I receive such a reply:

{'error': 'Could not compute an address from provided signature: invalid transaction v, r, s values.'}

Most likely, I'm creating the wrong signature, but how to make the right one?

It seems I'm almost there, but still it's not working out.


texts:
I wonder if this is possible -- I want to create a smart contract when I call the contract with ETH amount, GAS amount & a random ICO address, it will

Send the amount of ETH with the specified GAS to the ICO address
Automatically receive the ICO token and hold it in the contract. (The ICO token could be any ERC20 tokens)
I might call it again for another ICO so the contract needs to hold multiple random ERC20 tokens.

Thanks!


texts: Tradeable token (cryptocurrency) with variable supply

texts:
The ethereum.org site says one can create a "tradeable token with a fixed supply" on top of Ethereum. What does this exactly mean?

What if I wanted to create a token with variable supply - I mean maybe a pre-set supply scheme (like Bitcoin) or a supply that will be agreed on by the clients/users (via some kind of consensus)?


texts: geth - How to unlock multiple accounts with multiple password files in command line

texts:
I have a private blockchain with two accounts in my genesis.json file and tried to unlock both. I tried multiple methods and all failed. I tried

  geth --networkid 42 --datadir
  "~/data/privateEthereum/client" --nodiscover --rpc --rpcport "8042"
  --port "30303" --ipcpath "~/Library/Ethereum/geth.ipc" --maxpeers 3 --nat=any --rpccorsdomain "*" --unlock "0 1" --password "password0.txt password1.txt"

Solutions?


texts: Automate faucet Ether request to access Ethereum Testnet from a mobile DApp

texts:
I want to develop a mobile DApp to interact with a smart contract deployed in a testnet (free of charges). The mobile DApp is designated for public users.

The DApp needs first to setup a local wallet (pair public-private keys) to be able to interact with the blockchain network, for instance, Rinkeby. However, to send a transaction to Rinkeby or other testnets, the wallet needs to request some funds (faucet Ether) via Twitter by sending a tweet (https://faucet.rinkeby.io). How this can be automated in the mobile DApp after setting the wallet?


texts: Any ideas on why I cant "Load contract from Address" in Remix?

texts:
I have compiled the code and the code is the same as the deployed contract

Any tips would be appreciated, I deployed this contract just yesterday.


texts:
Trying to setup solo mining using Geth, but every time I try to start mining I get:

X Failed to submit hashrate.
X Dynamic exception type: class jsonprc::JsonRpcException
std::exception::what: Exception -32003 : Client connector error: libcurl error:
7 -> Could not connect to http://127.0.0.1:8545

My blockchain is synchronized. What else could it be?


texts:
Is there a way to automatically run a script (such as copy files from a to b) when the truffle migrate command finishes?

I want to copy the json files from the build/contracts folder into the a folder where my webapp code is.

Currently I use the "truffle develop" command console, soit would be cool, if I could just type "migrate" to for a deployment script to kick in and copy the files.


texts:
I'm new to the smart contracts. I want to create a contract which accepts ether and will transfer the equivalent tokens to the sender ether address (crowdsale). after few days research, i was written this code.  but it doesn't accept the ethers (in ropsten testnet). every time sending an ether to this contract results me fails.

contract YourTokenToken {

string public constant name = "YOURCOIN";
string public constant symbol = "YRC";
uint8 public constant decimals = 8;  // 8 decimal places.
uint256 public constant tokenCreationRate = 1500;
uint256 public constant tokenCreationCap = 10000 ether * tokenCreationRate;
uint256 public constant tokenCreationMin = 1000 ether * tokenCreationRate;
address public coinOwner; // Receives ETH and its own YRC endowment.
uint256 totalTokens; // The current total token supply.
mapping (address => uint256) balances;

event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);

function YourTokenToken() {
    coinOwner = msg.sender;
}

// Crowdfunding:

function create() payable external {

    if (msg.value == 0) throw;
    if (msg.value > (tokenCreationCap - totalTokens) / tokenCreationRate)
        throw;

    var numTokens = msg.value * tokenCreationRate;
    totalTokens += numTokens;
    // Assign new tokens to the sender
    balances[msg.sender] += numTokens;
    // Log token creation event
    Transfer(0, msg.sender, numTokens);
}

}


texts:
Hey guys I am new to the Ethereum and mostly cyrptocurrency mining world!

I have a problem when trying to set up Geth using CMD

It says that the command - "geth account new"  is not working - Yes I am in CD drive.

I am using Windows 10 so would that be an issue?

Here is the result:

C:\>geth account new
'geth' is not recognized as an internal or external command,

operable program or batch file.


texts:
I've developed my own private chain for testnet using geth and CLique and i have some issues with web3.js environment. I starts my nodes using the console parameter in order to get to the Web3 console but now i discovered that some functions doesn't work. For example, i call the contract using

myContract.at("addressofminedcontract").foo

but if, following the doc i use

new web3.eth.Contract(jsonInterface[, address][, options])

it doesn't work, returning

"Contract is not a function".

Or again, if i try to call myContract.options i get an error back.The same happens for example with the  web3.eth.getPastLogs(options [, callback])

Anyway, it looks like my web3 is not complete or something is missing. How can i solve that? Since geth encapsulates a console environment i thought it was enough, am i missing something?

Thanks guys


texts: Blockchain taking abnormally long time to download?

texts:
I'm a newbie to Ethereum. I initialized the download process for the Ethereum network blockchain using geth yesterday (geth --rpc). It's been nearly 20 hours and blocks are still being imported. Is this normal? I know that blockchains can easily take multiple hours but this is quite long.

Thank you!


texts: How to prevent tampering of contract call from the web?

texts:
I have a project where users will be calling my contract from the web. I want to ensure they call the contract with exactly the parameters I give them. My strategy was to hash the combo of parameters, sign the hash with my webserver's private key and validate both the hash and signature in the contract.

This is essentially the authentication scheme described here:
https://security.stackexchange.com/questions/82716/whats-to-stop-someone-from-just-mitming-a-checksum

What I can't figure out is how to validate the signature on-chain. Based on other discussions here, it seems like this is not possible because it costs too much gas. How do people normally handle this?


texts: why is my connected peers so few and blocks syncronising so slow even it stops

texts: it took so much time to do the syncronising but still not completed, I want know if the syncronising is always this slow, or is there some way to make it quicker?


texts: Signing a raw transaction, wrong R and S values

texts:
I am trying to sign a raw transaction in javascript without relying on dependencies like web3, ethereumjs, etc.

I am following the python tutorial found here, and porting to JS as I go: https://lsongnotes.wordpress.com/2018/01/14/signing-an-ethereum-transaction-the-hard-way/

I start by building out the RLP-encoded transaction:

var FROM_PRIV = "00d862c318d05de0a1c25242c21989e15e35e70c55996fbc4238cd2f2f6a8f62";
//var FROM_ADDR = "8d900bfa2353548a4631be870f99939575551b60";

var NOUNCE = "80";
var GAS_PRICE = "85" + "0BA43B7400";
var GAS_LIMIT = "82" + "5208";

var TO = "94" + "7917bc33eea648809c285607579c9919fb864f8f";

var VALUE = "87" + "03BAF82D03A000";

var CODE = "80";

var EIP_155 = "018080";

//

var SIGN_DATA_NO_LEN = NOUNCE + GAS_PRICE + GAS_LIMIT + TO + VALUE + CODE + EIP_155;

var SIGN_DATA = "EB" + SIGN_DATA_NO_LEN;

console.log("SIGN_DATA " + SIGN_DATA);

Which correctly logs:

SIGN_DATA EB80850BA43B7400825208947917bc33eea648809c285607579c9919fb864f8f8703BAF82D03A00080018080

Next I convert this to a Message Hash for later signing:

var TXN = new Buffer.from(SIGN_DATA, 'hex');

var SIGNING_HASH = keccak256(TXN);//Edit: This is using pre-nist variation of keccack256 from sha3: https://github.com/emn178/js-sha3

console.log("SIGNING_HASH " + SIGNING_HASH);

This also correctly logs:

SIGNING_HASH a4060d01d4add248db470b4121616cbe5b2015daf328809000ec9a1d0954d649

So far everything seems to match the outputs from the python tutorial,

Next, I sign the message hash (aka SIGNING_HASH) with the private key (aka FROM_PRIV)

const SIGNATURE = secp256k1.ecdsaSign(Buffer.from(SIGNING_HASH, 'hex'), Buffer.from(FROM_PRIV, 'hex'));

console.log("SIGNATURE " + toHexString(SIGNATURE.signature));

var R_HEX = toHexString(SIGNATURE.signature).slice(0,64);
var S_HEX = toHexString(SIGNATURE.signature).slice(64,64*2);

console.log("RECIEVED R_HEX " + R_HEX);
console.log("RECIEVED S_HEX " + S_HEX);

console.log("EXPECTED R_HEX " + "067940651530790861714b2e8fd8b080361d1ada048189000c07a66848afde46");
console.log("EXPECTED S_HEX " + "69b041db7c29dbcc6becf42017ca7ac086b12bd53ec8ee494596f790fb6a0a69");

The output R and S values do not match what the tutorial generates, here is log:

RECIEVED R_HEX 4c1c84da0afb3b38984fcb56953481bc2c8262f3473e28591384f63baa5e979e
RECIEVED S_HEX 7aa01ea9cb0fc0af56102045c69b46d00c18e4f19fbb612c4ae43e13302c475d

EXPECTED R_HEX 067940651530790861714b2e8fd8b080361d1ada048189000c07a66848afde46
EXPECTED S_HEX 69b041db7c29dbcc6becf42017ca7ac086b12bd53ec8ee494596f790fb6a0a69

I have tried three different secp256k1 npm dependencies for ecdsa signing, they all produce this same incorrect output. (I am currently using const secp256k1 = require('secp256k1');)

The expected signature from tutorial is 067940651530790861714b2e8fd8b080361d1ada048189000c07a66848afde4669b041db7c29dbcc6becf42017ca7ac086b12bd53ec8ee494596f790fb6a0a69 but I am getting signature 4c1c84da0afb3b38984fcb56953481bc2c8262f3473e28591384f63baa5e979e7aa01ea9cb0fc0af56102045c69b46d00c18e4f19fbb612c4ae43e13302c475d

I must be improperly formatting the SIGNING_HASH or Private key prior to signing, or is secp256k1-ecdsa not what I'm supposed to be using?

What's more interesting is, if I finish following the tutorial and build a signed TXN with these wrong R+S values, the txn works, I just broadcast one on main-net to confirm and the funds did move and received 12 confirmations already... does this imply that it doesn't necessarily matter that the R&S values from JS implementation of secp256k1 are different from what you get in python? The python tutorial also succeeded in broadcasting so it's unclear at this time... we both output different R,S values, but when push comes to shove we both succeeded in broadcasting? Very puzzling...


texts: Transaction has been reverted by the EVM(Error encountered during contract execution [out of gas] )

texts:
I am trying to execute a function from the truffle console and getting the error without much information.
contract LPTokenWrapper {
IERC20 public lp_tkn = IERC20(0xf7a35Eef60dC35fa2D3188Dfb22e635E4308fc8b);
function stake(uint256 amount) public {
        _totalSupply = _totalSupply.add(amount);
        _balances[msg.sender] = _balances[msg.sender].add(amount);
        tkn.safeTransferFrom(msg.sender, address(this), amount);
    }
}

from truffle console doing(with the same account which has lp_tkn) lp_wrp.stake(web3.utils.toWie("1"));
https://testnet.bscscan.com/tx/0x2eba99c94ba96513794da6e10e1c88d80e3ca619b13fc994428abc0e6fa2fd4c


texts: Where is the contract bytecode stored when a contract creates a contract?

texts:
When a contract creates a contract, where's the new contract's bytecode stored?

For example:
This Maker contract was created by their deployment contract: https://etherscan.io/address/0x448a5065aebb8e423f0896e6c5d525c040f59af3
here's the internal transaction: https://etherscan.io/txsInternal?block=4752011

Etherscan says 0x448a5065aebb8e423f0896e6c5d525c040f59af3 was created in transaction 0xa066bef4d74ad5433cc89ea21799d7df3e2f37ec0879f9ca74c419e861064fbf and normally, when an external transaction creates a contract, that bytecode is in the blockchain in the input.

In this case, data was sent to the deployment (existing) contract to tell it to deploy a new contract, but the bytecode for the new contract is not in the blockchain data. Would the bytecode be in the event logs? or somewhere else?


texts:
I working on a Ethereum project and I would like to gather a list of top X (20 for example) Ethereum accounts. This would behave similar to etherscan.io (https://etherscan.io/accounts)

Is there an API that does this ? If not does anyone know of a way to accomplish this. Im curious how etherscan accomplished this. I looked at their and there is no endpoint that behaves like it.

I would like to do this for other ERC20 tokens as well.


texts: how to implement an airdrop function inside a smart contract

texts:
I have a Erc20 token X and an Smart Contract A

Smart Contract A contains 1000 X Tokens.

How can an User get an defined amount of X Tokens from this Smart Contract? (something like an Airdrop)

So Basically a user should call a method like: getAirdrop() and then should get 100 X tokens from A's wallet

I tried the following:

function getAirdrop(){
    erc20TOken.transferFrom(this, msg.sender, 10000000000000000000);
}

... and...

function getAirdrop(){
    erc20TOken.increaseApproval(msg.sender, 100000000000000000000);
}

... but do not work.


texts: New temporary struct causing state variables to be overwritten

texts:
I'm running an experiment where I'm trying to create the following behavior:

Service owner deploys Experiment1 to the blockchain and is recorded as the owner.
Owner then adds a user address, a user-defined uint, and a user-defined bytes32.
The information is pushed to the arrA array, and the index of the record is mapped to the user's address and pushed to the arrAIndices array.

The problem is in the addToArrA function: it seems that state variables are being overwritten, and I can't understand how to prevent that from happening.  In particular, owner is overwritten by _user, and arrA is set to be _AdataA in length.  Completely at a loss on how to fix this.

pragma solidity ^0.4.17;

contract Experiment1 {
    address public owner;

    modifier onlyOwner {require(msg.sender == owner); _;}

    struct structA {
        address user;
        uint AdataA;
        bool AdataB;
        bytes32 AdataC;

        structB[] arrB;
    }

    struct structB {
        uint BdataA;
        uint BdataB;
    }

    structA[] public arrA;

    // Solidity cannot return structs, and can only return arrays of addresses, bools, or uints
    mapping (address => uint256[]) private arrAIndices;

    // CurrencyHedge: Contract creator.
    function Experiment1() {
        owner = msg.sender;
    }

    // addToStructAArr: add an element to structAArr
    function addToArrA(address _user, uint _AdataA, bytes32 _AdataC) public onlyOwner {

        structA tempStructA;

        // Populate the information in the new structA.  This method must be used,
        // since struct arrays cannot be passed as parameters.
        // Refer to https://ethereum.stackexchange.com/questions/3525/how-to-initialize-empty-struct-array-in-new-struct
        tempStructA.user = _user;
        tempStructA.AdataA = _AdataA;
        tempStructA.AdataB = false;
        tempStructA.AdataC = _AdataC;

        // Add the structA to the global list, and associate the index of the hedge with the beneficiary
        arrA.push(tempStructA);
        arrAIndices[_user].push(arrA.length - 1);
    }

    // getArrALength: Check on length of arrA
    function getArrALength() public onlyOwner returns (uint) {
        uint length = arrA.length;
        return length;
    }

    // getArrAIndices: Retrieve a list of indices of the allHedges array associated with a particular beneficiary's
    // Refer to https://ethereum.stackexchange.com/questions/3589/how-can-i-return-an-array-of-struct-from-a-function
    function getArrAIndices(address _user) public onlyOwner returns (uint256[]) {
        return arrAIndices[_user];
    }
}


texts:
I wrote this contract but Remix complains that it uses too much gas. What am I doing wrong?

"Fallback function of contract browser/SplitBalance.sol:SplitBalance requires too much gas (40612).
If the fallback function requires more than 2300 gas, the contract cannot receive Ether."

pragma solidity ^0.4.10;

contract SplitBalance{

    address a1;
    address a2;
    uint account1;
    uint account2;

    function SplitBalance(address _a1, address _a2) public{
        a1 = _a1;
        a2 = _a2;
    }

    function withdraw(address _addr) public {
        if (_addr == a1)
        {
            account1 = 0;
            a1.transfer(account1);
        }
        else if (_addr == a2)
        {
            account2 = 0;
            a2.transfer(account2);
        }
    }

    function updateAddress1(address newAddress) public {
        if(msg.sender != a1)
           revert();
        a1 = newAddress;
    }

    function updateAddress2(address newAddress) public {
        if(msg.sender != a2)
           revert();
        a2 = newAddress;
    }

    function() payable public {
        uint amount = msg.value/2;
        account1 = account1 + amount;
        account2 = account2 + amount;
    }
}


texts: What is maximum limit of GAS in a smart contract

texts:
Can you please explain the concept GAS in smart contract properly if possible with example. And what is the max limit of GAS in a contract?

It is clear if i use more gas i have to pay more...so where i can get that actual calculations.


texts: Ether price prediction after PoS consensus protocol in Ethereum 2.0

texts:
What do you think about the Ether price after Ethereum 2.0 moves to Proof of Stake consensus protocol?
will it rise or fall? and why?


texts: How to fractionalize ownership of a collection of NFTs across multiple investors?

texts:
An Ether wallet contains a large collection of ERC-721 NFTs. Normally only one owner knows the seed phrase for a wallet and therefore is the owner of all the NFTs inside the wallet.
How can such a wallet's digital assets be fractionalized amongst multiple owners instead so that new money facilitates further acquisitions? Is there a smart contract wizard/app that allows the genesis owner to distribute shares of ownership across multiple incoming investors? The idea is to attract and convince investors that their fractional ownership is guaranteed and immutable on the blockchain.
A conceptual schematic map of how this works economically and mechanically, maybe in the form of a numbered list, might be good enough.


texts: I want to create an Ethereum wallet, and I need an address and a private key, but I am unable to generate both. Please suggest a way to generate key pairs.


texts: Can we run GETH light client and full client at same server at the same time?

texts:
I have a dumb question. Can we run light client and full client at the same time in the same server? I want this because the server where I was running full node crashed. After recovery, GETH node is not working at all. So, just to be on safe side I also want to run a light client where if need be, I will point my web3 provider IPC to the light client.
Thanks


texts: How can I debug a live contract on Testnet

texts:
I have posted a simple token contact on Ropsten and have a basic function to Buy tokens and now due to some error EVM is reverting the transaction ..

https://ropsten.etherscan.io/tx/0xdafc102f2bf7a623034ae09d521f327ea6e9277076eaa7d7c98ba55994b880b5

I would like to debug the transaction and wnat to check out the run time states along with why it is fail in interacting way like we do other dubugging on Node etc..

Is there a good way to dubug and investigate the code.

Regards
Dev


texts:
I put my private key on etherscan.io and retrive my public adress and put it on coinbooks.io for watch.

In the token holdings i see an another adress with a high value of tokkens.

haw can i understand this.are this my tokkens ?


texts: Configuring a new ethereum network, using geth and PoA as consensus

texts:
I am trying to create a PoA private network using geth but I didn't find a good guide lines especially with the PoA addition. I couldn't get a definition and examples of the genesis block configuration.

Is there any resources that is deemed reliable and I can look into ?


texts:
I watched some videos about Metamask but I am so confused by it

  Metamask: To use the final application like the end user would.

Based on that, what is the purpose of React then?

What are the differences between Ganache and Metamask?


texts: How to interact with a MainNet contract from a console?

texts:
This question may be really dumb, but I fail to understand how to do this.

I have deployed a smart contract to MainNet, and so far I've been interacting with it via Web3JS and Truffle (via the truffle console), using promises. For example:

ContractOne.deployed().then(function(i) {return i.doSomething({from: "ADDRESS"})})

But now, I deployed the contract via Geth/Infura, and truffle console is not working. What is the best way to interact with the deployed contract?


texts: How to use BTCRelay for my ICO to get funds in BTC?

texts:
I want my ICO get investment in BTC also ,When i browse over internet I came up with BTCRelay concept . I tried to read their docs but it make me confused .Anybody give me a simple way to use BTC relay for the distribution of the ERC20 based token.

Any help is appreciable!


texts: Contract Name Types in Truffle Solidity Tests

texts:
The example in the docs for truffle .sol tests has these lines:

MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin());

and

MetaCoin meta = new MetaCoin();

I've had a good read through the docs and don't understand why the MetaCoin type shows up so often. Wouldn't it be easier to access the deployed address with:

var meta = DeployedAddresses.MetaCoin(); ?


texts: When Ethereum price goes up does complexity go up too?

texts: And what is their relationship? Is it linear, exponential. For example, if ether were to double in price tomorrow, does that mean the complexity is twice as much, or... ?


texts: Yellow Paper eq 221: Why and how the sender of a signed transaction equals to the address of the signer?

texts:
Ethereum Yellow Paper: Please see equation 220 and 221.

On equation 220, we obtain the transaction that can be sent to the network and will be tracked by a 256 bit transaction-id. Its right most 160-bits is equalled to S(T) which is the defined as the sender function S of the transaction.

My question is related to Equation 221 which is an assertion about: :

  The assertion that the sender of a signed transaction equals the
  address of the signer should be self-evident

[Q] Why and how the sender of a signed transaction(S(T) on the eq. 220) equals the address of the signer (A(pr)) ? Is there any well explained documentation related to this.

Could we conclude the following statement:

B96...255(KEC(ECDSARECOVER(h(T),Tw,Tr,Ts))) == B96...255((KEC(ECDSAPUBKEY(pr)))

Thank you for your valuable time and help.


texts: Filtering events by contract address and sender address

texts:
I need to watch events by two parameters: address of token contract and sender address. I found how to watch contract address, but not sure how to watch also by sender address? Shoud I specify address to topics like this?:

var eventFilter = web3.eth.filter({
    fromBlock:0,
    toBlock: 'latest',
    address: '0xefcc9f9a5cb3d6062c18eeffdf90a29bb771fccc',
    'topics':[web3.sha3('Transfer(address,address,uint256,uint256)'), web3.sha3('0xdd7b798cbfe06af77fdc4b64e48f71672595adcf')]});
eventFilter.watch(function(error, result) {
    if(error) throw error;
    console.log(result);
});

or maybe there is a different way?