texts:
I'm trying to build a login system using MetaMask. Everything is working thus far except for sending a signed message. The signed message goes through to MetaMask but then it gets stuck resolving the web3.eth.personal.sign promise, it never moves onto the next item in the promise chain.
Here is the full code:
import React, { Component } from 'react';
import Web3 from 'web3';

import './Login.css';

let web3 = null;

class Login extends Component {
    state = {
        loading: false
    };

    handleAuthenticate = ({ publicAddress, signature }) => {
        fetch(`${process.env.REACT_APP_BACKEND_URL}/auth`, {
            body: JSON.stringify({ publicAddress, signature }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
        }).then(response => response.json());
    };

    handleClick = async () => {
        const { onLoggedIn } = this.props;

        if (!window.ethereum) {
            window.alert('Please install MetaMask first.');
            return;
        }
        if (!web3) {
            web3 = new Web3(window.ethereum);
        }
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        if (!accounts[0]) {
            window.alert('Please activate MetaMask first.');
            return;
        }
        const publicAddress = accounts[0].toLowerCase();
        this.setState({ loading: true });

        fetch(`${process.env.REACT_APP_BACKEND_URL}/users?publicAddress=${publicAddress}`)
        .then(response => response.json())
        .then(users => (users.length ? users[0] : this.handleSignup(publicAddress)))
        .then(this.handleSignMessage)
        .then(this.handleAuthenticate)
        .then(onLoggedIn)
        .catch(err => {
            window.alert(err);
            this.setState({ loading: false });
        });

    };

    handleSignMessage = ({ publicAddress, nonce }) => {
        return new Promise((resolve, reject) =>
            web3.eth.personal.sign(
                web3.utils.utf8ToHex(`I am signing my one-time nonce: ${ nonce }`),
                publicAddress,
                (err, signature) => {
                    if (err) return reject(err);
                    return resolve({ publicAddress, signature });
                })
            );
        console.log("success");
    };

    handleSignup = publicAddress => {
        fetch(`${process.env.REACT_APP_BACKEND_URL}/users`, {
            body: JSON.stringify({ publicAddress }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
        }).then(response => response.json());
    };

    render() {
        const { loading } = this.state;
        return (

                    Please login with MetaMask.

                <button className="Login-button Login-mm" onClick={() => {this.handleClick()}}>
                    {loading ? 'Loading...' : 'Login with MetaMask'}
                </button>

        );
    }
}

export default Login;

The problem is with the handleSignMessage function. It never moves on to handleAuthenticate.


texts: Error when trying to implement Multisig wallet

texts:
When we try to send ether transaction execution in multisig got error in signing.

Error: Invalid signature value.

while calling contract execute function in solidity code

Error: invalid address at inputAddressFormatter.

We are using Christian Lundkvist's Simple MultiSig Wallet contract.
https://medium.com/@ChrisLundkvist/exploring-simpler-ethereum-multisig-contracts-b71020c19037

Github Link :- https://github.com/unchained-capital/ethereum-multisig

Above code is Transfered using Metamask.


texts: smart contact to release funds with a random password?

texts:
I'm interested in building an app that would generate a new smart contract every time two users of my app come to an agreement:

The first user would then send eth to the smart contract, and would receive a simple passphrase (something like a pin code) in return. the second user would provide an eth address to receive the funds.

Then, sending the passphrase to the smart contract would allow for the release of the funds.

It would also be great if the funds are actually sent back to user1 after a certain period if the passphrase hasn't been entered.

Does that sound easy to do? I assume this is exactly the sort of stuff one can do with ethereum, right? I'm pretty new with these sort of things, would there be an example I could use as a base? Thanks a lot in advance!


texts: Submitted transaction not propagated to all nodes

texts:
I have a private ethereum blockchain network running set up in 3 nodes using geth.
If i submit a transaction(smart contract function call) to one node and go to another node and type in eth.pendingTransactions it is returning empty.

I want to be able to submit a transaction to one node and mine it using any node in the network. But currently I am able to mine from the same network only. Why is that ?

P.s. I am using Nethereum to interface with the geth node and make function calls.


texts: pass storage through interface to library

texts:
Here is what am i doing:

There is a library, accept storage argument as parameter, then do some math and return the result.

And there is a contract to call the function in the library, and an extra thing I want to do is maybe the implementation of the library should upgrade and accept by the contract, so in the constructor, the address of library has passed in.

Here are the example codes.

pragma solidity ^0.5.2;

library ChangeableLib
{
    function callme(uint x, uint y) external pure returns(uint) {
        return x+y;
    }
    function callme2(uint[] storage x, uint y) external returns(uint) {
        x.push(x[0]+x[1]+y);
        return x[3];
    }
}

interface interfaceLib {
    function callme(uint x, uint y) external view returns(uint);
    function callme2(uint[] calldata x, uint y) external returns(uint);
}

contract Test {
    interfaceLib _interface;
    constructor(address i) public {
        _interface = interfaceLib(i);
    }

    uint[] public xs;

    function callLibFunc(uint x, uint y) public view returns(uint) {
        return _interface.callme(x, y);
    }

    function callLibFunc2(uint y) public returns(uint) {
        xs.push(1);
        xs.push(2);
        return _interface.callme2(xs, y);
    }
}

"callLibFunc" return correct result, however "callLibFunc2" will return with error, it supposed that the storage could not pass in this way? Thanks.


texts: I am sorry if this is a stupid question but if someone can help I would appreciate it. first I have the keystore to where the tokens were linked to, I already sync completely to the network. I show the right ethereum balance but my tokens never got recovered. I checked Etherscan to make sure they are still there and they are, but I can't find anyway to recover it in my account. I've looked at tons of forum posts but nothing I can see tells me how to recover tokens in general just the ether itself, can someone please tell me what I need to do? Keep in mind I'm not the best at understanding the ethereum wallet.


texts: i want get random number between 100-999, as follows

texts:
function random() internal returns (uint) {
    uint random = uint(keccak256(now, msg.sender, nonce)) % 1000;
    nonce++;
    return random;
}

In this way, you can generate random numbers, but there will be less than 100, how to solve, thank you


texts: how can I get the account locked information via python web3?

texts:
There is a command personal.listWallets in geth cli to get the account locked/unlocked status such as below:

> personal.listWallets[1]
{
  accounts: [{
      address: "0x175ec34c2b545a4e2195bfbfe03a82b67e594390",
      url: "keystore:///var/geth/keystore/UTC--2018-07-16T09-18-23.192773724Z--175ec34c2b545a4e2195bfbfe03a82b67e594390"
  }],
  status: "Locked",
  url: "keystore:///var/geth/keystore/UTC--2018-07-16T09-18-23.192773724Z--175ec34c2b545a4e2195bfbfe03a82b67e594390"
}

How can I get the similar account status from python web3 package or send the  same command to fetch the information via python web3?


texts: Correct way to easily call function with web3j from deployed contract

texts:
I am trying to call a function from a modified ERC20 contract and I can't manage to make it work. I am doing this with web3j from Android.

I can connect to Infura. The contract is already deployed on Rinkeby. I checked everything and the address is good. I'm trying to create credentials from a private/public key pair and pass it to use gas from that account.

String publicKey = "0x1900a41f2777ab70aad2074e3F4B9c5429c7f243";
    String privateKey = "some private key";
    String sparkTokenAddr = "some_addr";

    Credentials creds = Credentials.create(privateKey, publicKey);

    SparkToken spark = SparkToken.load(
            sparkTokenAddr, web3, creds, ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT);

    try {

        TransactionReceipt transactionReceipt = spark.chargedPhone(
                BigInteger.valueOf(50), publicKey).send();

        Log.e("ethereum", String.valueOf(transactionReceipt));

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("ethereum", "Could not send tx");
    }

It always logs that the tx could not be sent. What do I do wrong?


texts: a few days ago my miner ended up in nanopool and they made me the first payment here is " https://etherscan.io/address/0xd2e22dcb1eca93d679cdd2de4a9b31dafca882de " but it is not reflected in my Ethereum wallet account, can someone help me?


texts: Retrieving transaction hash in all blocks after fast sync

texts: I have set up an ethereum node using fast syncmode. I want to retrieve all the transaction hashes and the recipient between a range of blocks, let's say 0 - 13000. Will I be able to retrieve the required information using this fast sync method.


texts: On each block does all the miners compute the output of deployed transactions into them?

texts:
For each block of transactions, miners use computers to repeatedly and
  very quickly guess answers to a puzzle until one of them wins. [1]

[Q] In parallel to solving this puzzle, also does all the miners on the blockchain compute the output of the deployed transactions into them? or when the winners are decided, will only the winners compute the deployed transactions and generate their outputs?

Thank you for your valuable time and help.

[1] https://www.coindesk.com/information/ethereum-mining-works/


texts: Deployed truffle contract: Cannot create instance of ; no code at address

texts:
I deployed my contract at 0xa518a732606baae1c72490313cb7bb42c62c7a50. Now, what I try to do is to interact with my functions.. I've created an node.js application over web3 and truffle/contract but I can't access my smart contract(it is named Diploma). My error: UnhandledPromiseRejectionWarning: Error: Cannot create instance of Diploma; no code at address 0xa518a732606baae1c72490313cb7bb42c62c7a50
Also, I made this post for asking more things I don't know if I understand good..
This is what I tried:
const express = require("express");
const app = express();
const Web3 = require("web3");
const contract = require("@truffle/contract");
const artifact = require("./build/contracts/Diploma.json");

app.use(express.json());

if (typeof web3 !== "undefined") {
  var web3 = new Web3(web3.currentProvider);
} else {
  var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}

// when I npm start my default provider is taken as Ganache. I suppose it's normal since my node
// can't see my Metamask, right?

const Diploma = contract(artifact);
Diploma.setProvider(web3.currentProvider);

app.listen(8082, async () => {
  const accounts = await web3.eth.getAccounts(); // if I console.log this, all my 10 ganache
                                                 // accounts are shown
  const balance = await web3.eth.getBalance(accounts[0], function(err, result) {
    console.log('result', result);
 })

  var contract_address = "0xa518A732606baae1C72490313Cb7bB42c62c7a50";
  Diploma.at(contract_address).then(function (instance) { // here is where I get the error
    console.log(instance);
  });

});

Also, I have one more question. If I make transactions which I want to persist on Ropsten using my smart contract methods, can I choose the transaction hash / address where my data to be stocked or something like this? And after to retrieve them from that address?
Let's say this are my method:
function method(bytes32 _checksum, uint _data) public {
        require(!myMapping[_checksum].isSet);

        myMapping[_checksum].isSet = true;
        myMapping[_checksum].timestamp = block.timestamp;
        myMapping[_checksum].data = _data;
        myMapping[_checksum].setBy = msg.sender;

        some Event for logs
}

function getDiploma(bytes32 _checksum) public view returns(uint, address) {
        return (myMapping[_checksum].data, myMapping[_checksum].setBy);
    }

I suppose it's pretty obvious what I try to make. If this is not an optimum method can you give my an advice of how can I implement something to work how I want to..? If this is possible.
I've already saw this post and this post and more others..


texts: uniswap transaction issue. unable to locate txnhash

texts: I am trying to exhange one token for the other however the transaction is not going through, on etherscan when i go to view the transaction overview it states "sorry, we are unable to locate this txnhash" and the transaction is just stuck


texts: Sending secure transactions using web3.py

texts:
An ethereum account I had has been hacked, where whenever I send it, say, 0.1 eth, some evil bot immediately sends 0.0009 eth from that account to a dummy account, and then spends the remaining 0.0991 eth in gas. I'm not sure how they are monetizing that, but clearly, someone has the private key.

The hack can be seen at https://etherscan.io/address/0xd7184fafc2b4337e49fd059ca9fd04a98b63537a
Note the outbound transactions to 0x7BF...576 and 0xE469...c5b, where the amount is small but the transaction fee is large.

I had been using that hacked account in a python file that sent data to an ethereum contract using a private key. It had sent transactions to the ethereum address, and so perhaps people could intercept its private key. Also, people could see everything but my_wallet_private_key, as I had all the other info (infura project ID, contract address) on github, where the file was available. The code I had was as follows:

infura_url = "https://mainnet.infura.io/v3/myinfuraProjectID"
w3 = Web3(HTTPProvider(infura_url))
contract = w3.eth.contract(address=contract_address, abi=contract_abi['abi'])
nonce = w3.eth.getTransactionCount(my_wallet_address)
txn_dict = contract.functions.updateMyMethod(x, y).buildTransaction({
      'gas': 100000,
      'gasPrice': w3.toWei(gas_p, 'gwei'),
      'nonce': nonce,
    })
signed_txn = w3.eth.account.signTransaction(txn_dict, private_key=my_wallet_private_key)
result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)

I suspect that this is insecure because this is the only way I can fathom someone got this private key (eg, they didn't get the private keys to other accounts based on that seed phrase). But, I'm guessing. Should I be using sendSignedTransaction? Was it a mistake to show my infura Project ID?


texts:
In this little sample I try to play with modifiers, master1 creates the contrat and pass the master2 address as a parameter in the constructor.

contract testOnlyBy {
    address master1;
    address master2;

    modifier onlyByMaster1 { if (msg.sender != master1) throw; _ }
    modifier onlyByMaster2 { if (msg.sender != master2) throw; _ }
    modifier onlyByMaster1or2 { if (msg.sender != master1 || msg.sender != master2) throw; _ }

    // "0x6eec66e0133feb5e432584515880afad4be047f0"

    function testOnlyBy(address _master2) {
        master1 = msg.sender;
        master2 = _master2;
    }
    function get() external constant returns(address ret1, address ret2) {
        if (msg.sender == master1 || msg.sender == master2){
             return (master1, master2);
        }
    }
    function getonlyByMaster1() onlyByMaster1 external constant returns(address ret1, address ret2) {
        return (master1, master2);
    }
    function getonlyByMaster2() onlyByMaster2 external constant returns(address ret1, address ret2) {
         return (master1, master2);
    }

    function getonlyByMaster1or2() onlyByMaster1or2 external constant returns(address ret1, address ret2) {
         return (master1, master2);
    }
}

the get function works as intended, but the idea is to use modifiers instead.

I don't get why getonlyByMaster1or2 returns 0x0, I though the two functions would be equivalent.
Am I missing something ?


texts:
I've been looking in the go-ethereum code (where it appears 24(!) times, mostly in comments) and around, I can't find any reference for Ether having any signification rather than a naming convention.

While it is mentioned in the docs (and in a nomenclature file) that 1 wei = 10^-18 Ether, it seems that the opposite is the real definition, 1 Ether being defined as 10^18 wei since calculations are always made in wei. And indeed while working with Ethereum all units are defined in wei unless some explicit number casting is done.

So, is Ether just a naming convention, easy to remember and convenient considering the market value, or has it a concrete meaning?


texts: Parity wallet: how to reverse execute function?

texts:
While attempting to transfer ETH from my Parity wallet (multisig contract) to a cryptocurrency exchange, I have apparently taken the wrong approach and now it seems my ETH is stuck somewhere in the wallet (multisig contract) but not visible to me.

My actions leading to this problem were as follows:

Opened my contract in Parity wallet
Clicked the "execute" tab
In the "from" field I chose my account (owner of the wallet)
In the "function" field I chose "execute"
In the "to address" field I listed the exchange ETH address
In the "value" field I listed the amount of ETH I wanted to transfer
I left the data field empty

The resulting transaction came up on etherscan as follows:

From: my account address
To: contract: my wallet address
Value: 0 ether (this I don't understand)
Gas used by TXN: 51271
Input data: Function: execute(address _to, uint256 _value, bytes _data) *** followed by the binary data that includes the exchange ETH address and on the second line I see the amount of ETH I actually wanted to transfer

The problem with this is:

The ETH never arrived at the exchange's address (they've already stated they can't help me with this problem, merely referring to their ETH address on etherscan and saying; "look, there's no ETH coming in from you")
The ETH was deducted from my wallet

I'm looking for answers to 2 questions:

What did I do wrong in my attempt to send the ETH via Parity?
How (if at all) can I retrieve my ETH?

Thanks in advance for any suggestions.
For security reasons please understand I'd rather not list the transaction or my addresses here.


texts:
Simple logic event with firing in function, work perfectly as expected in truffle develop console, but never firing on my Dapp created with create-react-app, it's just seems to not listen/monitor the network, I've people saying it should continuously load POST request to monitor network, but not in my case. I use Metamask, and all smart-contract function calls works fine on react, except events.

event RoundStarted(uint256 closingBlock);

function roundStart() public ownerOnly {
    RoundStarted(block.number + ROUND_LENGTH);
}

And the line of code I used in truffle develop console, which is not working when I paste it in componentWillMount()

  Loto.deployed().then(function(instance){
    return instance.RoundStarted({},{fromBlock: 0, toBlock: 'latest'});
  }).then((result) => {
    return result.watch((error,result) => {
      console.log('Found him!')
    })
  })

UPD:
I found out that events works fine in truffle react box, so this kinda solves the problem, but I still don't know how did they manage it, it's not my code problem, something about dependencies, I'd like to know what do I miss in my create-react-app.


texts: What should I do to get the same output using `sha3` by providing multiple input on nodejs?

texts:
I have following contract:

pragma solidity ^0.4.0;

contract Lottery {
  address public owner;
  bytes32 public hash;

  function Lottery() {
    owner = msg.sender;
    hash = sha3(10, owner);
  }

  function get() constant returns (address, bytes32) {
    return (owner, hash);
  }
}

Which returns:

{
    "0": "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c",
    "1": "bytes32: 0x68690d4f19be42f79fab7837a1959281e0cb7c0a67c4c1efb7a1fcb008e5806e"
}

sha3() can get multiple input into each other.
I want to obtain same bytes32 hash on the nodejs by providing same inputs as some uint value and "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c".as sha3(uint, address).

I have followed following guide: (https://ethereum.stackexchange.com/a/34420/4575)

The javascript code I have:

module.exports = require('js-sha3');

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

if(!web3.isConnected()){
    console.log("not connected");
    process.exit();
}

var owner = "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"; //given input on the smart-contract.

hash = web3.utils.sha3( 10 + web3.utils.hexToBytes(owner) )
console.log(hash)

Which prints:

0xaf62552265611d75712f03dd8d2ae6efcb4c140dc8357ea015bd0572dd33ca82

That is not the same output I got on the solidity.

[Q] What should I do to get the same output using sha3 by providing same uint, address as multiple parameter input on nodejs?

Thank you for your valuable time and help.


texts:
I need to create a struc to store the funds, the asdress who send the funds and date/time, It’ll store these three values for all transactions when some one sends ethers to a contract.
So I came up with the thought of using structs and create an array to populate that.
Can some one help me out how to create struct with above mentioned three properties, and populate an array (who’s size should be dynamic obviously).

It’s urgent to do in an hour, so any suggestions will be appreciated. Please come up with any other suggestions (if u find some other idea more suitable for my work).

Thanks


texts: How to make my token in private network exchangeable?

texts:
I am recently creating a token in my private network and want my DAPP users to exchange the token within the network. But at any point of time, i want my users to exchange the tokens they have for real ether or any other currency. Is it possible if my token lives in my private network?

I know that moving my token to main network will solve. But i want my users to transact within my private network, and at some point if they want to exchange the token for another token or ether they need to do so


texts: Is there still a way to buy or change Ethereum classic?

texts: I'm still looking for a possibility to change my ETH (after HF) to ETC or directly buy ETC. Do anyone know what is the most convenient way?


texts: How to mining using GPU in private chain?

texts:
Sir,
  We build a Ethereum private chain for one application.We use geth to mine and find the performance is not good. Geth use CPU to mine.So,what method I can use to mine using GPU?
   Barkely


texts: Questions Regarding Creating New ERC20 Token & ICO

texts:
Hi

  I want to create an ERC20 token and launch an ICO. I am new to
  ethereum solidity.

  I have checked smart contracts on http://ethereum.org and
  https://theethereum.wiki/w/index.php/ERC20_Token_Standard But I am
  confused which is the standard way to create a smart contract. Some
  websites says to create a token you need to follow the ERC20 token
  standard but I don’t understand from where I should start.

  I deployed different contracted which are copied from above sites and
  test it.

  I want to know that what are the mandatory functions for a smart
  contract to create a new token?


texts: When an Ethereum transaction event occurs, is there a case when it was not included in the main chain later due to a fork?

texts:
I know Ethereum is a POW blockchain where forks take place.
The transaction event is issued after executing the transaction on the node. If a fork occurs, is there a possibility that the transaction will not be included in the main chain? How do you verify that the dapp is completely in the chain when that event occurs?


texts: My MyEtherWallet address is different than the first address it gave me

texts:
I invest to TheDAO this week and I don't see my transaction.

My address is: 0x72eb41AE7f943445Da9932662d31A06D56A3cfAa

But when I look my wallet whith my private key I see an other: 0x110C7C6a224122F72619b18A1b3f712957E4EbF1

I dont understand why ist changing ... Where is my coins ?


texts: TypeError: Cannot read property ':Lottery.sol' of undefined. Please help in solving this!

texts:
I am a newbie and have just started building contracts. I am getting this error for
this contract. Kindly help in solving this
Code-
For compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');

const lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf-8');

module.exports = solc.compile(source,1).contracts[':Lottery'];

For Lottery.sol
pragma solidity ^0.4.25;

contract Lottery{
    address public manager;
    address[] public players;

    function lottery() public{
        manager = msg.sender;
    }

    function enter() public payable{
        require(msg.value > 0.01 ether);

        players.push(msg.sender);
    }

    function random() private view returns (uint){
        return uint(keccak256(block.difficulty, now, players));
    }

    function pickWinner() public restricted{

        uint index = random() % players.length;
        players[index].transfer(this.balance);
        players = new address[](0);
    }

    modifier restricted(){
        require(msg.sender == manager);
        _;
    }

    function getPlayers() public view returns (address[] memory){
        return players;
    }
}


texts: Web3js & Web3.py ERC20 Name, Symbol, & Decimals call(): Results in Web3.exceptions & OverflowError for Some But Not All Existing Contracts

texts:
I'm building simple Javascript & Python 3 scripts using the Web3 module to output ERC20 token names, symbols, and decimals from any given contract address.
The standard ERC20_ABI json file was copied directly from the Ethereum ERC20-ABI Github page found below, and is imported into my main code:

https://github.com/ethereum/wiki/wiki/Contract-ERC20-ABI

This script successfully outputs token data from the majority of contracts, however, fails with a handful on both Javascript & Python... including but not limited to ERC20 tokens that were later swapped to their own mainnet chains. The problem here appears to be contract related, as I'd assumed the standard ABI file would be able to pull what I needed.

Does anyone have any idea how to successfully retrieve this data for every ERC20 token available, without having to pull from Etherscan?

Below are scenarios, specifically with Python 3 for simplicity-sake.

Scenario #1:

Attempt at retrieving the 'Token Decimals' for High Performance Blockchain (HPB), a token still traded as an ERC20, results in the following error:

from web3 import Web3
import ERC20_ABI
import json

web3 = Web3(Web3.IPCProvider('/data/ethereum/geth/mainnet/geth.ipc'))

# Contract Address for High Performance Blockchain (HPB)
contract = '0x38c6A68304cdEfb9BEc48BbFaABA5C5B47818bb2'

token_info = web3.eth.contract(web3.toChecksumAddress(contract), abi=ERC20_ABI.ERC20_ABI)
token_decimals = token_info.functions.decimals().call()
print(token_decimals)

Python3 Error:

  web3.exceptions.BadFunctionCallOutput: Could not decode contract
  function call decimals return data b'' for output_types ['uint8']

Scenario #2:

Attempt at retrieving the 'Token Name' for ICON (ICX), a token swapped to its mainnet chain in 2018, results in the following error:

from web3 import Web3
import ERC20_ABI
import json

web3 = Web3(Web3.IPCProvider('/data/ethereum/geth/mainnet/geth.ipc'))

# Contract Address for ICON (ICX)
contract = '0xb5a5f22694352c15b00323844ad545abb2b11028'

token_info = web3.eth.contract(web3.toChecksumAddress(contract), abi=ERC20_ABI.ERC20_ABI)
token_name = web3.toText(token_info.functions.name().call())
print(token_name)

Python3 Error:

  web3.exceptions.BadFunctionCallOutput: Could not decode contract
  function call name return data b'' for output_types ['string']

Scenario #3:

Attempt at retrieving the 'Token Symbol' for EOS, a token swapped to its mainnet chain in 2018, results in the following error:

from web3 import Web3
import ERC20_ABI
import json

web3 = Web3(Web3.IPCProvider('/data/ethereum/geth/mainnet/geth.ipc'))

# Contract Address for EOS
contract = '0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0'

token_info = web3.eth.contract(web3.toChecksumAddress(contract), abi=ERC20_ABI.ERC20_ABI)
token_symbol = web3.toText(token_info.functions.symbol().call())
print(token_symbol)

  OverflowError: Python int too large to convert to C ssize_t


texts:
I have deployed my contract here https://etherscan.io/address/0x9b03d6b95bb730d1be29658f6b879ecf6c1c64a8

I would like to change its logo to my custom picture. How can I do that?


texts:
Is Esrcow could be applied in ST 20 tokens ?
If yes, please guide for the same.


texts: What exactly is the default Javascript VM environment in Remix?

texts: When using the online Remix IDE, the Run tab has default values of Environment="JavaScript VM" and Account=<a list of addresses I don't own that already have 100 ether each>. What exactly is this environment? Is it a private (test) network that gets set up each time I refresh the browser (which would explain how it seems to be able to simply give me ether to play with) or something else?


texts: How can I send alerts to others on ethereum blockchain?

texts:
I want to know if it is possible to build an app that can send alerts to others on ethereum blockchain.

If it's possible then how fast do you think the alerts can be sent and then received by the recipients?


texts: get the return of a function with multiple returns

texts:
How can i get the a and b from the following function:

function f() returns (uint a, uint b){

}

funtion g(){
    uint s = f();
}

do i need to just use one return parameter?


texts:
Is it possible to store a base64 image code as string in block chain?
I know we can use IPFS or Swarm as a tool to store an image or a document, but if someone gets to know about the hash anyone can tamper the image/document.
Is there any other alternative to store an image or a entire document directly to a private block chain??
I also know if i increase the gas price i can store the image but why do i need gas price in a private block which has very minimum nodes say 3-4.


texts: uint value usage as a parameter in truffle

texts:
How can I send a uint parameter value to the contract in truffle?

i have a function that has two uint parameter and I wrote test that function but I guess the uint parameters cannt be sent as a correctly. Also I cannot see in mapping too the boolean value result of the uint parameter. (the HashList is mapping )

I'm putting log messages in truffle :

it('should be mint the token only owner', async()=>{
  const _hash = await actions.generateHash.call(50, '123');
  const inList = await actions.HashList(_hash);
  console.log('is there in list?    '+ inList);
  console.log('hash: '+_hash);
  console.log('all info: '+accounts[3], 50, '123', _hash);

  const res = await actions.create(accounts[3], 50, '123', _hash{from: accounts[0]});

  assert.isTrue(res, 'could not create. Please check contract or test code.' );

  });

My test outputs in here :

is there in list?false
hash: 38391047091755091013202618179480389830368877342597680687864504738175347992246
all info : 0x916666dBb04c97ea3D92647dF5b0De5Be5cD038B 50 123 BN {
  negative: 0,
  words: [
    51521206,       11804147,
    59004577,       116902,
    25125010,       60098687,
    16719740,       18977897,
    526954,         1390628,
    <1 empty item>
  ],
  length: 10,
  red: null
} BN {
  negative: 0,
  words: [
    51521206,       11804147,
    59004577,       116902,
    25125010,       60098687,
    16719740,       18977897,
    526954,         1390628,
    <1 empty item>
  ],
  length: 10,
  red: null
}

what is BN in all info output? why the Uint parameters shown as BN ?

thank you,


texts: Truffle test: inputting an uint256 outputs a different result

texts:
To simplify my question, let's say I have a Test.sol with a function that simply output the input:

function testFunc(uint256 value) public pure returns (uint256) {
  return value;
}

Now I want to test it in truffle

it('uint input test', async () => {
  var test = await Test.deployed()
  res = await test.testFunc.call(0x10000000000000000000000000000001)
  console.log(res)
  console.log(res.toNumber())
  console.log(res.toString(16))
  assert.equal(res, 0x10000000000000000000000000000001, 'wrong')
})

I'm expecting the result should be same as the input, but it fails the assert. Outputs:

BigNumber { s: 1, e: 37, c: [ 2126764793, 25586540000000 ] }
2.1267647932558654e+37
1000000000000001d172c5f60ac00000

So 0x10000000000000000000000000000001 is changed to 0x1000000000000001d172c5f60ac00000, I assume it's the JavaScript number overflow problem?

It causes problem when I try to test the bit operations, such as checking ERC721 token ID. How can I bypass it?


texts: Is there a provision to inform smart contract deployer of the function call on that contract?

texts: I have a scenario like this. I am creating a private blockchain for non financial purpose. If I deploy a contract from one node (owner of pets) of the network which contains a mapping of pets ID and adopter address(initally set to empty addresses). Whenever someone calls the placeAdoptRequest(petID) function of the smart contract. Is there a way the smart contract owner be informed of this request, so that they call a function changePetOwner(petID, address) from their side to set the adopter address corresponding to the pet they choose.


texts: Is it possible to sign a message in Solidity?

texts: I am trying to sign and verify a signature in Solidity. I understood that it is possible to verify a signature using ecrecover. However, I am not able to find any useful information on signing.


texts: Does the consensus going to fail if contract has "now" filed?

texts: now keyword stands for current time. So if contract has now filed, peers may have different times leading to different data in blockchain.


texts: Is it safe to perform calculations on past events?

texts:
I would like to store all balances of my ERC20 contract on my website's database: addresses and their balances and be able to call the script anytime to sync it with new balances using Transfer event.
This is how it looks like so far. Let's say my contract starts with my account 1 with 10000000000 balance. Then I transfer tokens and next users do next transfers.
Now I'm going to fetch them on my website, so I'm going to get all past events "Transfer" from "last_saved_block" and work with them. If this is the first time, I manually save account 1 with 10000000000 . Then, in a loop, there is "from", "to", "value", so I'm adding "value" to "to", subtracting from "from" and saving the result to the database. Finally I'm saving last_saved_block from the last event.
It seem to be working but do I have any guarantee if there are thousands of transfers, will fetched events always be in a right order with block id increasing and without any gap between them or something? Maybe is there any better way to fetch all balances?


texts: Querying the blockchain: Search transaction by data

texts:
Is it possible to perform queries on the blockchain, based on transaction properties (other then hash), such as its data/sender/value/etc fields?
For example, is it possible to "ask the blockchain" to return all transactions whose data match a certain regular expression (or string)?


texts: Is an RPC-enabled Geth with no accounts secure?

texts: For my dapp, I want to host a web server (Geth + web3) which allows the users to relay the transactions they signed "offline". Is this safe? Are there other (than unlocked accounts) security concerns with RPC?


texts: Can exposing personal be made safe anyhow?

texts:
I know exposing personal over rpc is vulnerable. But is there any way I can make exposure of personal over rpc safe?

Let me state my requirement. I have deployed a cryptocurrency. Now I want to expose it's functions as api.
But for that I have to expose personal over rpc to carry out transactions. For eg. to perform transfer , I can write following code:

function transferCoin(to, amount,frm, passphrase){
    web3.personal.unlockAccount(frm,passphrase);
    var tx=contract1.transfer(to, amount, {from: frm});
}

Problem:
But if someone can connect to my node then he can misuse personal and empty my account.
Edit:
As I was writing the question I realised that it's not only about personal but it's rpc that is insecure. For example let's consider a case where personal is not exposed over rpc. But, if someone can connect to my node via rpc, they can execute a function like:

function EtherTransfer(){
    while(true){
        //console.log("hello");
        web3.eth.sendTransaction({from:"addr1", to:"addr2", value: web3.toWei(100,"ether")});
    }
};

and carry all my ethers.
So is there any solution to the problem. As I stated in my requirement I need to expose personal over rpc in order to provide api's of my contract functions to my other application.


texts: Can unlock account, but not send transaction

texts:
I've compiled a version of geth where I modified CalcDifficulty() in core/block_validator.go to make mining difficulty constant, see reference. Starting up the private chain, creating accounts and mining works fine.

If I try via the javascript console to unlock an account, it works, and returns true.

  personal.unlockAccount(eth.accounts[0])

But when I try to send a transaction:

  personal.sendTransaction({from:eth.accounts[0], to: eth.accounts[1],
  value: 20000000})

I get the following:

Error: could not decrypt key with given passphrase
    at web3.js:3104:20
    at web3.js:6191:15
    at web3.js:5004:36
    at <anonymous>:1:1


texts: Trying to check if mapping exists, TypeError: Type uint256 is not implicitly convertible to expected type bool

texts:
I am checking if a struct exists in vehicleList and returning true if it exists and false if it does not.
However, the function produces an error and I can't understand why it does not work.
TypeError: Type uint256 is not implicitly convertible to expected type bool.
if (bytes(vehicleList[_registrationNo].vehicleRegistrationNo).length =! 0) {
function checkVehicleExists (string memory _registrationNo) public view returns (bool) {
        bool vehicleExists = false;
        if (bytes(vehicleList[_registrationNo].vehicleRegistrationNo).length =! 0) {
            vehicleExists = true;
        }
        return (vehicleExists);
    }


texts: Can anyone with part of the chain (e.g. a light node) read unencrypted transaction data?

texts:
I need clarification on the fact that "the blockchain is public and anyone can read it".

Given a node which is storing only, say, 1 block from the blockchain, can that node read the transaction data from within the block without downloading the rest of the chain?

Sorry if this is a stupid question - is unencrypted data always stored as plaintext?


texts: Is the DAG the same for all (private/main/test) nets?

texts:
Reading about the proof of work, I got to the data generation part (mainly the DAG) and found it in:

~/.ethash/full-R23-0000000000000000

In the ethash it is mentioned that the DAG is generated from a seed, then a 16 MB cache and finally a 1 GB data set. When I ran geth and pyethapp as part o f a private network a new DAG was not generated meaning that the one that the one in the home directory has been used.

Why? Isn't the DAG supposed to be uniquely generated from a seed and then based on block header data, namely the nonce and the mixhash which in this case would be the ones in the custom genesis block?


texts: How can I extract sidechains (transient forks) from a geth node before they get discarded?

texts:
According to my understanding, transient forks (also known as sidechains in geth's source code) are discarded or overwritten when a reorganization happens.

But before that, when the node detects a fork (i.e. two different blocks with the same blockNumber), it stores the chain it received from other nodes as a sidechain and then compares it with the one it currently has to decide which is the canonical chain based on the total difficulty.

My goal is to extract the chain that is not considered as the canonical chain (i.e transient fork) before it gets overwritten or discarded by the node.

I would like to know if this is possible and if there is a way to do it using APIs or I should modify the source code.

Finally, is there any references or guidance that explains the workflow of the geth's source code or geth's components?


texts: Why is my code calculating incorrectly, it feels right to me?

texts:
Why does this keep returning 0? And yes, it is above the claimtime. It does it for every address. I don't know what's wrong?

function ViewDividendOwed(address _addr) public view returns (uint256) {
  uint256 _SavedDividend = _balances[address(this)].mul((_balances[msg.sender]).div(_totalSupply));

  if (ClaimTime[_addr] + 2 minutes <= now) {
    return _SavedDividend;
  }
  else {
    return 0;
  }
}


texts: Need help with start mining(I am getting like this)

texts:
I am new to ethereum private blockchain

System information:
 geth version:1.8.2 os&version:linux

synopsis: when i tried to connect peers to my private blockchain it showing like

WARN [03-20|11:41:32] Node data write error err="state node c56d5a…f2fb4a failed with all peers (1 tries, 1 peers)"

node is not at all syncing . i am running this since from a week please help me out

Steps to reproduce the behaviour:

         1.created two nodes using the geth
         2.join them using admin.addPeer()
         3.peer is connected.                                                   Same error getting in node system and getting also  peer system.          I got this problem since last week.


texts: MY ETH DOESN'T ARRIVE AT MY METAMASK WALLET BUT SENT TO A LIVECOIN ETH ADDRESS

texts:
I transferred Eth from Bilaxy to my Metamask Wallet,I used copy method and pasted the address on my bilaxy withdrawal and sent 150$ worth of Eth,after waiting for so long,I had to check the transaction hash and discovered my eth was sent to a livecoin eth address:
here is the txn
0x3bc572e48c4d1bfdad65ca549ca340b8db3c6e181e56e157716b1aabf2c6e5b5
here is the address the eth was sent to:
0xc636a1b56197bab274ff7a4b0c10c8c6f715ddcb
This address stated above is not my address,when I checked I noticed after copying and pasting the address cahnges to this address above.I have an updated antivirus on my system,how could this happen.And I have been using metamask now for over a year without this kind of problem. Please I need help recovering my funds


texts:
I'm installing some developer tools on Mac to work on some bigger projects but some of the packages need funding. What does that mean and how do I fund them?
KALEBS-MacBook-Pro:~ root# npm install truffle -g
npm WARN deprecated fsevents@2.1.3: "Please update to latest v2.3 or v2.2"
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)

changed 144 packages, and audited 145 packages in 14s

37 packages are looking for funding
  run `npm fund` for details


texts: Msg.data returns wrong format through fallBack function

texts:
When I call the same function twice, first through a direct call an event logs the exact parameters, second through a delegateCall from another contract, it returns the same parameters but the format is wrong, here are the logs from both calls:

Direct call:

"topics": [
            "1",
            "0x294F36a4c1d1be614f8D1CAB33C0e0dcd39031AF",
            "0xeD85D4d8C76a027DDac93654221D31f5c17056A0"
        ]

Delegate call:

"topics": [
            "0xab8530f87dc9b59234c4623bf917212bb2536d647574c8e7e5da92c2ede0c9f8",
            "0x000000000000000000000000294f36a4c1d1be614f8d1cab33c0e0dcd39031af",
            "0x000000000000000000000000ed85d4d8c76a027ddac93654221d31f5c17056a0"
        ]

Thanks in advance for your help


texts:
I am currently synchronizing an Ethereum geth full node and am noticing some oddities in my log after roughly 4 days.
I followed the below tutorial, using the same version etc. : https://kauri.io/#communities/Ethereum%20Node%20Runners/running-an-ethereum-full-node-on-a-raspberrypi-4-/

Additionally inside of the geth --dev console;
web3.eth.syncing returns false
Based on the other geth node error threads I have read that getting false indicates that you have synced up to the current block but based on https://ethstats.net/ I still have roughly 3mil blocks to go...
Is it just part of the process or do I need to start from scratch?
Any feedback and help is appreciated
UPDATE - the change in version(1.10.3) got the node back to syncing
note that out-of-memory error came up later; would recommend using version 1.10.2(stable)as of 4/30/21 just in case that played a roll
-arelius


texts: get all data for a specific user in solidity

texts:
how can  i get all the associated data with a specific a customer by providing customer id and is it smarter to save any the basic data such as ids, names, etc in blockchain or IPFS ?

struct {

  uint256 customer_Id;
  bytes32 customerName;
  bytes32 customerAddress;

}


texts: Uncaught error: VM Exception while processing transaction:out of gas

texts:
pragma solidity^0.4.18;

contract project3{

address owner;

struct Users{
string companyName;
string role;
string country;
string city;
uint phoneNo;
string physicalAddress;}

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

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

mapping(address=>Users)users;

address[] private stakeholders;

function addUsers(address _address, string _companyName,string _role, string
_country,
string _city, uint _phoneNo, string _physicalAddress)only_admin public{
var user= users[_address];
user.companyName=_companyName;
user.role=_role;
user.country=_country;
user.city=_city;
user.phoneNo=_phoneNo;
user.physicalAddress=_physicalAddress;
stakeholders.push(_address);}

function getUser(address _address)public constant
returns(string,string,string,string,uint,string){
return(users[_address].companyName,
users[_address].role,users[_address].country,
users[_address].city,users[_address].phoneNo,
users[_address].physicalAddress);}
}

Above is my smart contract on the remix IDE, i have installed web3.js and are able to connect to the smart contract. I also created a user interface to interact with the smart contract. I was always get: Uncaught error: VM exception while processing transaction:out of gas, whenever im using web3 but its fine on EVM. i am hoping you can help me decrease the gas cost for this contract tell me how i can fix this error. Your help would be highly appreciated.


texts: Node lags behind 100 blocks, states are finished syncing

texts:
I run my geth node with the following command:

./geth --cache 8192 --syncmode full

It has been syncing for a long time, and it looks like it has finished syncing:

> eth.syncing
{
  currentBlock: 7070318,
  highestBlock: 7070420,
  knownStates: 243826689,
  pulledStates: 243826689,
  startingBlock: 7070265
}

As you can see the node lags behind about 100 blocks. An explanation for this seems to be that the states have not yet finished syncing. In my case however all states are pulled. So why is it still constantly lagging behind? If it is still syncing something, is there a command which tells me the progress?


texts: I am using web3j and geth. How to create default accounts with some ether allocation to it?

texts:
I need a default account with huge ether allocation. This I need to set up manually in genesis.json
Hereafter,all accounts need to be created dynamically in java, and they should also be given some default funds.

I tried this using web3j, but its creating its own genesis block . How can I do my default setup in that genesis ?

Also, not sure whether to use smart contract here or web3j ?

Edited here

How to start geth and web3j in a private network ?My application requires default account to be created with some default ether allocation to it. I did that using

a. "geth account new" command

b. updated genesis.json with this newly created account and allocated some balance to it

c. and then ran the init command "geth --datadir ./datadir init genesis.json"

It worked all fine.So, now I have main account with some default ether.

Now, hereafter I should be able to create new accounts dynamically. And transfer some default funds to these accounts from the main account created in the above steps.

I tried using web3j - java API ,
"geth --rpcapi personal,db,eth,net,web3 --rpc --testnet"
But this should point to existing genesis.json and keystore . It is creating new genesis.json . How can I do this?


texts: Which is faster: loop inside contract or loop of transactions?

texts:
I have this contract:

pragma solidity 0.5;
pragma experimental ABIEncoderV2;
contract TestStruct {

      struct User {
        string name;
        uint256 age;
     }

    mapping (bytes32 => User) users;

    function addManyUsers (User [] memory _users) public {

        for (uint i = 0; i < _users.length; i++) {

           bytes32 hash = keccak256(abi.encode(_users[i].name));
           users[hash] = _users[i];

        }
    }

    function addOneUser (User memory _user) public {

         bytes32 hash = keccak256(abi.encode(_user.name));

           users[hash] = _user;

    }

    function getUser (string memory username) public view returns (User memory) {

        bytes32 hash = keccak256(abi.encode(username));

        return users[hash];
    }
}

Let's say we have a list of 100 users,

which is more faster in terms of execution: insert one by one (using addOneUser) or insert all the one once (using addManyUsers) ?


texts:
When I install Mist, and after a bit of loading, it starts downloading the blockchain for the mainnet, but when I change the network, I get an error that it's not connecting. If I try to restart mist (with the new network which is Ropsten selected), I get this:

Question:
Would anyone know why this is happening?


texts: No output when writing data to IPFS and storing its hash through Solidity

texts:
So I am using truffle.
Following from Creating a form in IPFS for users to enter data [check the code in answer], doing some changes:

Contract name - IpfsContract.sol
test.js uses the following JSON Structure within the test():

const data = JSON.stringify({
        name: "Rahul Kothari",
        age: "21",  // maybe "21"?
        sex: "male"
})

My 1_initial_migration.js and truffle-config.js files work fine!

Using truffle develop, on CMD I run truffle compile truffle migrate. Works perfectly! I then run truffle test and it displays: 0 passing (1ms) in green. No other output although, my test.js used console.log!

Any help will be appreciated! Thanks!


texts: Writing contracts without fully syncing blockchain

texts: I've read this post and this one and I'm still wondering if there is a way to deploy a contract without fully syncing the blockchain, for example by using a light client. I would like try my hand at writing contracts (and be more helpful to people on StackExchange!) but I'm short on disk space and would prefer to use a public test net rather than a private chain. My backup plan is to deploy a test net node on a small VPS instance I'm already paying for, so I won't cry if the answer is "you need to fully sync the blockchain".


texts:
I'm trying to use web3.js with infura.io to interact with my smartcontract. here is my simple greeter contract code

pragma solidity ^0.5.7;
contract greeter{
    string greeting;

    function greet(string memory _greeting)public {
        greeting=_greeting;
    }
    function getGreeting() public view returns(string memory) {
        return greeting;
    }
}

Here is what I found from web3.js documentation.

var tx = web3.eth.sendTransaction({
             from: '0x3dCDe57Ad49d639c4D702b607Dd5eBc0aB54A671',
             nonce: web3.toHex(txCount),
             gasLimit: web3.toHex(1000000),
             gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
             data:0x756774689538938966626728299293638893o
         });
web3.eth.accounts.signTransaction(tx, privateKey [, callback]);

But it doesn't take me anywhere. Because,where can I pass greeting data? All the documentation talks about sending ether. Then what about sending string data like this? with web3.js 0.20 I can read greeting from chain. I wanted to add new greeting string with greet function. but somehow I have no idea about signing transaction. could anyone help me in understanding how to sign transacion and adding greeting to the contract using web3.js?


texts: How to loop over soft deleted items on contract?

texts:
I have a smart contract that contains posts. Let's say that it's a twitter-like dapp.
Contract Blog {
    struct Post {
        string content;
        bool isDeleted;
    }
    mapping (uint256 => Post) private posts;
    uint256 postCounter = 0;
}

In this contract, I have a get method that returns post if post is not deleted.
function get(uint256 index) public view returns (string memory) {
    Post memory post = posts[index];
    required(post.isDeleted == false, "This post is deleted.")
    return post.text
}

In this case, when I need to loop over Tweets I'm something like this on the frontend.
Get num of posts from the contract = X
for (let i=0; i<=X; i++) {
   try {
       post = try to get post from contract.
   } except {
       if contract returns error suppress it
       continue
   }
}

Most of the time the frontend side is trying to consume the contract for non-existing posts. Is there any better approach to do this?


texts: Does an ethereum node save all transaction history?

texts:
I know that a full node keeps the record of a state tree, and in every block there's a list of transactions. My question is, does a full node have to keep all the tx lists? The state tree already saves all the information about the current states of all accounts, so it seems kind of meaningless to remember the whole blockchain history(all the tx), but if this is the case, how can we check our transaction histories?

My guess is that the nodes will keep all the transactions, but they're just for users to look up, not for validating future transactions. Is this correct?


texts: How to restrict mining to a certain nodes in ethereum private network

texts:
I have created a private network of ethereum block chain. The network is open for anybody to join and run their  own node.

But I dont want them to mine blocks. I Want to restrict mining to certain nodes.

Any lead is appreciated.


texts: Solidity Error: Cannot destructure property `interface` of 'undefined' or 'null'

texts:
I've got his error in Solidity when compiling my test file:
      TypeError: Cannot destructure property interface of 'undefined' or 'null'.

I know it is related to my compile.js file, but what is unusual is that my tests compiled just fine until I tried to update the solidity compiler version. I then uninstalled the updated compiler version and restored the version it compiled with before but now have got this error.

This makes me think it is not related to a mistake in my compile.js file but to do with the solidity compiler. However, when I check the solc version (using solcjs --version), I have correct version that is compatible with my code.

My compile.js file is:

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

const lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf8');

module.exports = solc.compile(source, 1).contracts[':Lottery'];

my test file is:

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

const {interface, bytecode } = require('../compile');

let lottery;
let accounts;

beforeEach(async () => {
    accounts = await web3.eth.getAccounts(); // unlocked accounts
created automatically for us with ganache

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

describe('Lottery Contract', () => {

    it('deploys a contract', () => {
        assert.ok(lottery.options.address);
    });
});

Please help, this error has paralysed my work!

Some additional information, when I changed the solc compiler version, the pragma solidity ^0.5.0 declaration was underlined with a red squiggle indicating and error. When I hovered on the error it said the file requires a different compiler version (the old version that was used). How can the file be unable to recognised that the solc version has been updated? Could this be to do with the JSON files?


texts: Are there any specifications/details on the call stack?

texts: I am trying to understand how the call stack inside the EVM works. I can't find anything in the yellow paper not else where online. Can anyone explain how the call stack works and if you can access its values in any way (EVM or solidity)?


texts: myFunction.call() not working with MetaMask

texts:
I can't seem to figure out why the function symbol() isn't working. I've made sure that MetaMask is on the right network (main net). I tried console.logging the myContract.methods... line and seem to get an error, but can't seem to figure out what it means.

$( document ).ready(function() {

  var myContract;

  function startApp() {
     myContract = new web3.eth.Contract(crowdsaleABI,
     "0x618E75Ac90b12c6049Ba3b27f5d5F8651b0037F6")
  };

  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
     // Use Mist/MetaMask's provider
     web3 = new Web3(web3.currentProvider);
     document.write("You are connected to MetaMask");
  } else {
     // Handle the case where the user doesn't have web3.
     document.write("You are not connected to MetaMask");
     web3 = new Web3(new
     Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
  }
  // Now you can start your app & access web3js freely:
  startApp();

  myContract.methods.symbol().call().then((result) =>
  {console.log(result)});

  });

  /*ERROR DETAILS:
  "Error
  at A.R [as _captureStackTrace]
  (http://localhost:3000/src/js/web3.min.js:1:350318)
  at A._then (http://localhost:3000/src/js/web3.min.js:1:373974)
  at A.then (http://localhost:3000/src/js/web3.min.js:1:372344)
  at HTMLDocument.<anonymous>
  (http://localhost:3000/src/js/app.js:22:50)
  at i (https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js:2:27449)
  at Object.fireWith [as resolveWith] (https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js:2:28213)
  at Function.ready (https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js:2:30006)
  at HTMLDocument.K (https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js:2:30368)"*/

EDIT: I also tried replacing web3.currentProvider with an Infura API to the main net and it actually worked. So it seems to be something with MetaMask, but I still can't seem to figure out what exactly.


texts:
I synchnorized Ethereum blockchain in my AWS Ubuntu 16.04 server with 110GB Hard Disk.

The command I used is geth --syncmode=fast --cache=1024

According to bitinfocharts, the total size of Ethereum Blockchain is 103.10 GB total as of today (2017.11.26).

After synchronization is completed, I typed dh -h to find out how much disk space it consumed.

  It is ONLY USED 38GB, which is 1/3 of the blockchain size!

Does anyone know why?

EDITED:

  From this link, 5chdn answered that the Geth only offers database pruning on initial sync.

Is that the reason? what If i want to synchronized full blockchain node?

What command should I use to sync the full node?


texts:
I've just downloaded Mist 0.8.1 under Windows 10 (fully up to date). It was working at first, but is now crashing after the sync.

I followed these steps, maybe something here munged the preferences?

Downloaded and ran Mist 0.8.1. I saw the new announcement but didn't click anything.
At that point, I realized I wanted to back up my wallet before proceeding. So I clicked close (X) and opened v 0.7.6. I went to Backup > Accounts and made a copy of everything.
Closed v0.7.6 and re-opened v0.8.1., and clicked Yes for the DAO fork. Mist was having a lot of trouble syncing: it would say it found 2 peers, then 3 peers, then they would disappear. But after a while it synced. In the meantime, I was able to launch the application and see the new interface.
After a long sync, I don't know if I quit or the application crashed. However now, when I open it and click Launch the Application before it syncs, it crashes, and if I wait to let it sync, it crashes when done syncing. So I can't get to the interface.

I found the log, but I wouldn't know what to look for.

Thanks for any help.


texts: Getting exception while getting the ethBalance

texts:
web3 = Web3j.build(new HttpService());

         EthGetBalance ethGetBalance = web3.ethGetBalance("0xb34a5b6a39bceafeb8e23c2cc526889d85bf664e", DefaultBlockParameterName.LATEST).send();
         BigInteger balance = ethGetBalance.getBalance();
         System.out.println("balance - "+balance);

java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:8545
    at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:225)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:149)
    at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:195)
    at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
    at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:211)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
    at okhttp3.RealCall.execute(RealCall.java:69)
    at org.web3j.protocol.http.HttpService.performIO(HttpService.java:106)
    at org.web3j.protocol.Service.send(Service.java:30)
    at org.web3j.protocol.core.Request.send(Request.java:68)
    at com.mobiloitte.coinbase.TestEthreum.createConnection(TestEthreum.java:56)
    at com.mobiloitte.coinbase.TestEthreum.main(TestEthreum.java:74)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at okhttp3.internal.platform.Platform.connectSocket(Platform.java:124)
    at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:223)
    ... 25 more


texts: Miner RIG does not initial all NVIDIA for mining

texts:
I have a Ethereum RIG with 8 NVIDIA 1070 and UBUNTU 16.04 OS.
When I check my hardware with lspci command, it shows 7 NVIDIA graphic cards;
When I start ethminer (ethminer -G -F http://eth-eu.dwarfpool.com:80/0xf88f3392c3cca1890b522a6154d16703d4627fab/Rig01/hesam.es@gmail.com), it uses only 4 graphic cards.
How could I update my ethminer hardware list?


texts: Can you use Ethereum or blockchain in general for emails?

texts:
And I don't mean to send emails but to make sure they are authentic.

So let's a big bank in US or company like Microsoft sends an user email about them subscribing and Click here. If they're not very careful, they might click on a phishing site and give up their credentials.

Could the company use blockchain with which the recipient's client would check against and display a badge or something stating that it came from that source. It'd be similar to digital signature but without the need of purchasing digital signatures.

A way of defeating spam and making sure legitimate emails can be checked/verified.


texts: What are normal entry / execute / exit conditions for DApps?

texts:
Very new to this space, so forgive the lack of foundation knowledge.  Looked at the yellow paper,
but honestly the set theory in it is a bit more than I want to bite off right now.

I think I have an ELI5 understanding of DApps.  They react to deposits (entry) of ETH, I understand that.  They can do some process while they have ETH (execute), I think I get that.  But what are their exit conditions?  I guess for something like a ticketBooth.Dapp I get it, but for something like a crowdfund, what verifiable proof does the Dapp have to trigger its exit on.

For example... let's say I want a Dapp to fund a feature I want in some game.  So I do same marketing and convince enough people to send the Dapp ETH.  Now, presumably it will start a timer to refund the ETH if the time runs out, or reward it to the company that release the feature update for the game.

This is all well and good, but without centralized control, how does the Dapp know

That the feature was really implemented and is not just shell-ware.
Where to send the money when done.

Do the Dapp developers need to pre-seed these conditions into the Dapp before it is launched, and if so, how would it verify something like softwareQuality == GOOD?


texts: Insufficients funds to Deploy Contract on Test Network

texts:
Here are my files on github, https://github.com/ArtieLadie/gas_limit

https://github.com/ArtieLadie/gas_limit/blob/master/deploy.js sets gas limit here,

async function deployContract(web3, contract, sender) {
    let Voter = new web3.eth.Contract(contract.abi);
    let bytecode = '0x' + contract.evm.bytecode.object;
    let gasEstimate = await web3.eth.estimateGas({data: bytecode});

This is the account I am using to deploy contract. It has 18 ether.

https://rinkeby.etherscan.io/address/0xf8f07fc5301d4644ab33f59496a03363233b8f79

When I deploy contract, I get error,

Failed to deploy contract: Error: Returned error: insufficient funds for gas * price + value

I tried starting geth with

sudo geth attach /home/solidity/.ethereum/rinkeby/geth.ipc — targetgaslimit 2000000

but still no luck :-(

If it helps ....

1st Terminal

2nd Terminal

3rd Terminal


texts: Converting oraclize result from string to address

texts:
I am trying to set up a contract that gets an ethereum address from a json file using oraclize, and in turn i'd like to send ether to that address.

function __callback(bytes32 myid, address result) {
  if (msg.sender != oraclize_cbAddress()) throw;
  _address = result;
  if (!_address.send(_withdrawAmount)) throw;
  Withdraw(now, _withdrawAmount, this, _owner);
 }

function withdraw(uint value) {
  _withdrawAmount = value;
  oraclize_query("URL", url);
}

And here is the json

{
  "address" : "0xf519f8bf364fb6bf0185f0bacf19fb8e5c3f134a"
}

I havent been able to send ether in the __callback function and i am not sure how to resolve it.

I am guessing it is because it returns a string, so in the __callback function the type of 'result' would be a string. But how would i convert a string to an address i'd be able to send ether to?

EDIT: In addition to Xavier's answer, I found that I can't send transactions from within the callback function. So i added an executeWithdrawal function that the user would have to call to execute the transaction once the callback has been made from oraclize.


texts: Bytecode execution during contract deployment

texts:
during the process of contract deployment the 'loading' code is executed (60606040523415600e57600080fd5b5b603680601c6000396000f300). This bytecode sequence loads the actual contract into the evm/memory for deployment and do stuff like the initialization of the memory pointer.
Is there any other bytecode executed (except the bytecode of the constructor)?

For example, is the whole bytecode of the contract executed during deployment?
Or are just the bytecode sequences corresponding to a method executed if the method is invoked?


texts: How to create conditional unit testing with truffle

texts:
I've been using truffle for unit testing and I can't find a way to execute two excludent tests. I mean, I'm creating an ICO contract and my tests depend on lower and upper cap limit, start and end blocks. Sometimes when I execute a series of tests I would need to restart the blockchain (of course only possible in dev chain) to be able to execute the other tests and I don't know how to do this or if this is possible.

I'm using truffle + testrpc for unit testing.

Here is one example of two tests that can't happen at the same test flow:

it("User trying to send eth after max pre ico cap reached by last user", function () {
return AuctusPreIco.deployed().then(function (instance) {
  // send a 5 eth transaction from user test account to contract
  var account = web3.eth.accounts[3]
  return instance.sendTransaction({ from: account, value: web3.toWei(3, "ether") })
    .then(assert.fail)
    .catch(function (error) {
      if (invalidOpCodeException(error)) {
        assert(
          true, 'max cap reached. Can\'t send more eth to contract.'
        )
      }
      else {
        unexceptedException(error)
      }
    })
  })
})

and

it("Sending eth after ico max block limit", function () {
return AuctusPreIco.deployed().then(function (instance) {
  // send a 5 eth transaction from user test account to contract
  var account = web3.eth.accounts[4]
  return instance.revoke({from: account})
    .then(assert.fail)
    .catch(function (error) {
      if (invalidOpCodeException(error)) {
        assert(
          true, 'revoke not allowed yet'
        )
      }
      else {
        unexceptedException(error)
      }
    })
  })
})

So, I don't know if I was clear enough, but if the max cap was already reached, the second test that tests if it will fail because of the max block limit wouldn't throw anyway.

How can I deal with this scenario? I want to execute all tests in a row.


texts: Can someone report me for a Smart Contract bug?

texts:
Today I was talking to a company to work for them as a Smart Contract developer. The thing is that they asked me if I have any insurance in case there's a bug in the Smart Contracts.

Do we really need insurance as Smart Contract developers?
Can someone report me for a Smart Contract bug that caused people to lose Ether?


texts:
I wanted to build go-ethereum source code in my local side and test it in geth.
I have followed up the instructions in the github go-ethereum as it is.
However, I have got fail with some errors when I try command to build as below.

go-ethereum>go install -v github.com/ethereum/go-ethereum/cmd/geth

Is there any ways to build go-ethereum source code on either windows or ubuntu?
I have tested it in both windows10 and Ubuntu18.04 with go version 1.13.4.


texts: Etherscan how to get latest transactions?

texts: I am using this api to get all transactions at an address, however I see it returns the last 1000 transactions, is there any way to make it return first 1000 transactions by date?


texts: Verify transaction was included in certain block within smart contract

texts: Is there a good resource for proving that a particular transaction was included in block x?


texts: Solidity function receiving value, passing it to another contract function

texts:
I'm trying to create a contract which receives value to a function called contribute.

Then I shall call another contract function with value. I wonder how this is done, it's not very clear.

This is the code I got so far (all other functions and variables are left out for simplicity):

contract Hub {
    function contribute(address _address) payable {
       Project project = Project(_address);
       project.fund.value(msg.value)();
    }
}

contract Project {
    function fund(address sender) payable {
       amount += msg.value;
       contributors[sender] = msg.value;
    }
}

This gives me invalid opcode for some reason. What might be wrong? Am I trying to do it wrong?

Opcode stack is here: https://gist.github.com/vongohren/160b61e5fd2b6c0c85fb8829aed9b3b2


texts:
hi guys i am confuse about the web3j library for android i search about this but i did not get any materiel about this (https://github.com/web3j/web3j). this is lib for using ether node on java and for android i don't know how to use this. following things i already done .
1 -> Ethereum Node syncing (full node)
2 -> make web interface using Web3.js lib.
3 -> creating address and managing account on ether using cli with Web3.js

now i want to use this thing on android also please help me how i can use this web3j lib on android how to configure .


texts: Creating a contact to register usernames

texts:
I have an idea and wish to make a site which will let users register a username on a contract. By calling the contract from their address this will also confirm ownership.

I am wondering is there any examples currently out there for a simple username register?


texts:
Sometimes it takes an around of 25ms to import new block by the other peered node after mined by miner. But sometimes it increases directly around 400ms to import block by peered node after mined by miner.  In PoA: Clique consensus there is no such delay I found.

Is this due to latency ?
ans : No, Ideally zero latency for same machine/region

And my question is,

  What is the reason for the non-uniform block receiving delay?


texts: Error : Called function should be payable

texts:
I am trying to create a token contract and the token sale contract.
Token Contract : ERC20 token is ready and it is flawless
TokenSale Contract : I have passed the "Token"" contract to "TokenSale" and created it. It has the function "pushTokens". It just pushes the coins from owners address to beneficiary address
When I tested in remix using "JavaScript VM" environment, I have the issue in the below location where I transfer the created ERC20 tokens, it fails. I am not able to understand the issue.
I have changed the ownership to "TokenSale" Contract
Note : I don't receive the ETH from user while they using the "TokenSale" contract
Source code of contracts (Flattened file)
Token     : https://textuploader.com/1e2jg
TokenSale : https://textuploader.com/1e2jx
Relevant code from Token Contract
library SafeERC20 {
using SafeMath for uint256;

function safeTransfer(IERC20 token, address to, uint256 value) internal {
    require(token.transfer(to, value));    **---------  Issue Line -------**
}

Relevant code from TokenSale Contract
contract TokenSale is Crowdsale{

event CrowdsaleFinalized();

constructor(
ERC20Mintable token
)

public
Crowdsale(token)
{
    require(address(token) != address(0),"Token is not an address");
}

}

contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;

// The token being sold
IERC20 private _token;

// Amount of wei raised
uint256 private _releasedToken;

event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 amountOfTokens);

constructor (IERC20 token) public {
    require(address(token) != address(0));
    _token = token;
}

function () external payable {
}

function token() public view returns (IERC20) {
    return _token;
}

function releasedToken() public view returns (uint256) {
    return _releasedToken;
}

function pushTokens(address payable beneficiary,uint256 rate,uint256 amountOfTokens) public nonReentrant payable  {
    _preValidatePurchase(beneficiary, rate, amountOfTokens);

    // update state
    _releasedToken = _releasedToken.add(amountOfTokens);

    _processPurchase(beneficiary, amountOfTokens);
    emit TokensPurchased(msg.sender, beneficiary, amountOfTokens);

    _updatePurchasingState(beneficiary, amountOfTokens);

    _postValidatePurchase(beneficiary, amountOfTokens);
}

function _preValidatePurchase(address beneficiary, uint256 rate, uint256 amountOfTokens) internal view {
    require(beneficiary != address(0));
    require(rate > 0);
    require(amountOfTokens > 0);
}

function _postValidatePurchase(address beneficiary, uint256 amountOfTokens) internal view {
    // optional override
}

function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
    _token.safeTransfer(beneficiary, tokenAmount);
}

function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
    _deliverTokens(beneficiary, tokenAmount);
}

function _updatePurchasingState(address beneficiary, uint256 amountOfTokens) internal {
    // optional override
}

}

contract TokenSale is Crowdsale{

event CrowdsaleFinalized();

constructor(
ERC20Mintable token
)

public
Crowdsale(token)
{
    require(address(token) != address(0),"Token is not an address");
}

}
Error Location

Error

Deploy / Run


texts:
I'm trying to use BrowserSolc in my dApp, but it's just not loading, it seems. I've got browser-solc.min.js in the same folder as index.html, with the following near the top of the page:

<script language="javascript" type="text/javascript" src="browser-solc.min.js"></script>

and later:

BrowserSolc.getVersions(function(soljsonSources, soljsonReleases) {
  console.log(soljsonSources);
  console.log(soljsonReleases);
});

This results in an Uncaught ReferenceError: BrowserSolc is not defined.

What am I missing?


texts:
I am trying to start programming with solidity for Ethereum.
I am working with this tutorial: https://medium.com/@ConsenSys/solidity-integration-with-visual-studio-8bdab2ff8a74#.hunrp4l0i

Apparently I need "Bloc". npm install blockapps-bloc works and gets me a copy of bloc. But I am doing something wrong with "bloc init". What I am supposed to do with that? Just typing it in cmd in the same directory that I have just used to download bloc doesn't work. The Command bloc cannot be found.

What do I have to do to make it work?


texts:
Correct me if Im wrong but from my understanding each block has a "stateRoot" property that point to status of the State tree at the time of mining. I also believe that tha state tree contais a list of accounts (user accounts and contracts) and their balance\code.

Is it possible to get the list of accounts and their balance (if not contracts) on each block? I know I can use the "eth_getBalance" RPC call to get the ballance of each account but that wold require me to know before hand which are the accounts.

thanks


texts: Truffle cant deploy contract with reverting constructor

texts:
I'm developing a dapp with the truffle suite and now I'm running into a problem.
Everything is working locally in the ganache instance.
My contract should disallow direct payments to the contract, so my constructor looks like:
/**
 * @dev Disallow payments to this contract directly
 */
constructor() public {
    revert("No direct payments");
}

https://github.com/ethereumbook/ethereumbook/blob/develop/code/auction_dapp/backend/contracts/AuctionRepository.sol
But now the Deploy by truffle reverts with the given message.
Removing the line where the constructor is reverting and everything works fine. The contract is deployed and tested.
The contracts are deployed like this:
var SecondPriceAuction = artifacts.require("./VickreyAuctionHouse.sol");
module.exports = function(deployer) {
  deployer.deploy(SecondPriceAuction);
};

Any ideas how to deploy a contract, that does not allow calling the constructor.


texts:
I am trying to compile the following smart contract:
pragma solidity ^0.5.1;
contract Governmental{
   uint constant TWELVE_HOURS = 12;

   function lendGovernmentMoney ( address buddy ) public  returns ( bool ) {
      address owner;
      uint[] memory creditorAddresses;
      uint lastTimeOfNewCredit =0;
      uint amount = msg. value ;
      uint creditorAmounts = 0;
      uint profitFromCrash = 0;
      uint round = 0;
      uint lastCreditorPayedOut = 0;

      // check the condition to end the game
      if ( lastTimeOfNewCredit + TWELVE_HOURS > block . timestamp ) {
         msg.sender.send ( amount );
         // Sends jacpot to the last creditor
         creditorAddresses[creditorAddresses.length - 1].send ( profitFromCrash );
         owner.send (this.balance);
         // Reset contract state
         lastCreditorPayedOut = 0;
         lastTimeOfNewCredit = block . timestamp ;
         profitFromCrash = 0;
         creditorAddresses = new address [](0);
         creditorAmounts = new uint [](0);
         round += 1;
         return false ;
      }
   }
}

I am getting the error:

prg17.sol:20:10: Error: Member "send" not found or not visible after
argument-dependent lookup in uint256.
creditorAddresses[creditorAddresses.length - 1].send ( profitFromCrash );
^--------------------------------------------------^

Somebody please guide me.
Zulfi.


texts: Can you use a generic ABI and grab any Smart Contract by its contract address?

texts:
This might be a basic question, but I was walking through how to interact with the DAI (an ERC20 token) smart contract in Web3.js which led to this:

const daiTokenAddress = "0x6b175474e89094c44da98b954eedeac495271d0f"; // Replace DAI Address Here (can be the actual smart contract)
    const daiTokenMock = new web3.eth.Contract(DaiTokenMock.abi, daiTokenAddress);

But then I switched the daiTokenAddress with the smart contract of the USDC token (a different ERC20 token) and grabbed that contract instead and it works fine.

So my question is, can I switch the contract address in the above function to any smart contract? And then what's the point of passing in an ABI?


texts: why does it matter to sync nodes with time?

texts:
As we know, time gets set on a block's header as the miner's current local time. Each node while accepting a block, checks if the new block's time is more than parent 's time and is not also in the future too far.
Question 1. Why doesn't geth just put the UTC time directly on the header ?  why does the local time set on the computer matter ? I also don't understand how NTP matter in this case since all it does is check's some difference and logs the warning message and that's all


texts: Remix error :-The constructor should be payable if you send value

texts:
Below is the code of the solidity contract :-

pragma solidity ^0.4.24;

contract Auction {
    address public owner;
    uint public startBlock;
    uint public endBlock;
    string public ipfsHash;

    enum State { Started, Running, Ended, Canceled }
    State public auctionState;

    uint public highestBindingBid;
    address public highestBidder;
    uint bidIncrement;

    mapping(address => uint) public bids;

    constructor() payable public {
        owner = msg.sender;
        auctionState = State.Running;
        startBlock = block.number;
        endBlock = block.number + 40320;
        ipfsHash = "";
        bidIncrement = 10;
    }

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

    modifier afterStart() {
        require(block.number >= startBlock);
        _;
    }

    modifier beforeEnd() {
        require(block.number <= endBlock);
        _;
    }

    function min(uint a, uint b) pure internal returns(uint) {
        if(a <= b) {
            return a;
        } else {
            return b;
        }
    }

    function placeBid() payable public notOwner afterStart beforeEnd returns(bool) {
        require(auctionState == State.Running);
        require(msg.value > 0.001 ether);

        uint currentBid = bids[msg.sender] + msg.value;

        require(currentBid > highestBindingBid);

        bids[msg.sender] = currentBid;

        if(currentBid < bids[highestBidder]) {
            highestBindingBid = min(currentBid + bidIncrement, bids[highestBidder]);
        } else {
            highestBindingBid = min(currentBid, bids[highestBidder] + bidIncrement);
            highestBidder = msg.sender;
        }
       return true;
    }
}

I deployed this contract by using Javascript VM but on click of PlaceBid in Remix , I get an error message stating :-.

  Note: The constructor should be payable if you send value. Debug the
  transaction to get more information.

As you can see that both place placeBid and constructor are payable . What is causing this and how can it be resolved?


texts: Will the DAO attacker be able to retrieve his funds on the 14th of july?

texts: It has been a month since the attack on the DAO. The attacker might be able to retrieve his/her stolen ETH in fiat currency tomorrow. Will (s)he be able to do so?


texts: PancakeSwap V2 swapExactTokensForTokens not working, getting stuck

texts:
I am unable to get this working with ethers.js. I know there are many similar questions for this specific topic, but none of the answers seem to work for me. My attempt is mostly based on Noob Troubleshooting failed BSC transaction using ethers.js and Pancakeswap v2 router.
My code is the following:
const ethers = require('ethers');

const addresses = {
    WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
    BUSD: '0xe9e7cea3dedca5984780bafc599bd69add087d56',
    factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
    router: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
    recipient: '0xE00e552a0e18ca773a26f65cE957915D302CBE10'
}

const PRIVATE_KEY = ""

const mygasPrice = ethers.utils.parseUnits('5', 'gwei');

const WSS = "wss://*.bsc.quiknode.pro/*/"
const provider = new ethers.providers.WebSocketProvider(WSS);

const wallet = new ethers.Wallet(PRIVATE_KEY);
const account = wallet.connect(provider);

const router = new ethers.Contract(
    addresses.router,
    [
        'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
    ],
    account
);

const init = async () => {
    console.log("Test TX");

    let tokenIn = addresses.WBNB, tokenOut = addresses.BUSD;

    const amountIn = ethers.utils.parseUnits('0.0005', 'ether');
    const amountOutMin = 0;

    console.log("Starting swap...");

    const tx = await router.swapExactTokensForTokens(
        amountIn,
        amountOutMin,
        [tokenIn, tokenOut],
        addresses.recipient,
        Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
        {
            gasPrice: mygasPrice,
            gasLimit: 500000
        }
    );
    console.log("Swap done!");
    const receipt = await tx.wait();
    console.log("Transaction receipt");
    console.log(receipt);
}

init();

When I run this code, it gets stuck.
Test TX
Starting swap...

The wallet generated from the private key is the same as the recipient address (0xE00e552a0e18ca773a26f65cE957915D302CBE10), and there is enough WBNB balance. I just tried to do a manual swap on pancakeswap V2 (WBNB to BUSD) and it worked flawlessly (https://bscscan.com/tx/0xe3351e82ed4a86e18e164ba47b44bb7fa74faaeda67f8b7e3486f6410e5b50b9).
I am currently out of ideas, and I don't know how to debug this further.
Thanks for your help.


texts: How to do loop all the metamask Accounts loop and display data from that address in React frontend + Dapp App JS

texts:
I want to Display data stored on the Ropsten Network in more then 2 metamask accounts.

I want to display the result on the Home page in the table form.

For that I need to loop through each accounts who store data and display.

Following is my code to getData function and I am showing on load( componentDidMount )

getData = async() => {
 const {accounts, contract} = this.state;
 const response = await
 contract.methods.getData().call({from:accounts[0]});
}

I am using web3 1.0.0-beta.37 and React JS is on frontend.

I have read somewhere that when we do web3.eth.accounts it will silently take accounts[0]. is it correct?


texts: Truffle test: How to test Ether transfer? Balance of specific account?

texts:
How is it possible to test if my contract actually transfers money to a specific account?

function _transfer(address receiver_, uint256 payout) internal{
    receiver_.transfer(payout);
}

Testing in JavaScript Syntax. Expecting something like:

assert.equal(accounts[1].balance, 100 Ether);


texts: Reports of slight network congestion since BAT ICO started funding. What are the various ways to easily handle this capacity? (Batch processing -As we know their funding Address?)


texts: Move ether from mytetherwallet coldstored on computer after one year, after the fork

texts:
I have had ether coldstored on my computer with myetherwallet for a year or so, since the fork I remember there was a need to update before sending the ether but I can't find any instructions or information about it anymore. If it was sent without first updating they'd be lost is what I heard.
So what is it I need to do? Am I missing anything?


texts: How to transfer current wallet to another

texts:
So I started trying to mine ethereum in one of my spare machines at home. I was able to download and install both geth and ethminer and they are running quietly in the background while I work.

From there, how can I transfer the ether that I mine to another wallet? Any help would be greatly appreciated. Thanks!


texts: General question: Reasons to use sha3 (or any hash) in contracts?

texts:
I'm going through the Numerai contracts and noticing a common pattern -
 https://github.com/numerai/contract/blob/master/contracts/NumeraireBackend.sol

and https://gist.github.com/Arachnid/4ca9da48d51e23e5cfe0f0e14dd6318f

function stakeOnBehalf(address _staker, uint256 _value, bytes32 _tag, uint256 _tournamentID, uint256 _roundID, uint256 _confidence) stopInEmergency onlyPayloadSize(6) returns (bool ok) {
    return delegateContract.delegatecall(bytes4(sha3("stakeOnBehalf(address,uint256,bytes32,uint256,uint256,uint256)")), _staker, _value, _tag, _tournamentID, _roundID, _confidence);
}

I see the delegatecall with the bytes4 and get the sha3 hash of a string before the variables of the function. I understand what sha3 does in this context, but my question is why?

Is it for security? What is the purpose of the string before the variables as well?


texts: Is it possible to use both approve and trasferfrom functions in a single function in other contracts?

texts:
I realized that you need to approve the amount of tokens you are gonna send to contract. for this you should first use approve function in token contract and then call the trasferfrom function in other contract (for example buy function)
But is there any way to use approve function in the same buy function?
when I use approve function, I get error. I checked the value of msg.sender... it is the user who is calling the function but i still get error.
i dont want to use approve function from token contract every time before i want to call buy function from Buy contract.
Here is the code: (extra codes are not pasted here)
pragma solidity >=0.6.0 <0.8.0;
contract ERC20{
function approve(address spender, uint256 amount) public returns (bool) {
    require(msg.sender != address(0), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");
    _allowances[msg.sender][spender] = amount;
    emit Approval(msg.sender, spender, amount);
    return true;
}

function approveWithSender(address sender, address spender, uint256 amount) external returns (bool) {
    require(sender != address(0), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");
    require(sender == msg.sender,"You cannot approve other users");
    _allowances[sender][spender] = amount;
    emit Approval(sender, spender, amount);
    return true;
 }
}

contract Buy{

ERC20 tokenAddress;
address contractAddress = address(this);

constructor (address _tokenAddress) public{
    tokenAddress = ERC20(_tokenAddress);
}

function buy(uint amount) public{

    //tokenAddress.approveWithSender(msg.sender, contractAddress, amount);
    //tokenAddress.approve(contractAddress, amount);
    require(amount > 0, "You need to sell at least some tokens");
    uint256 allowance = tokenAddress.allowance(msg.sender, address(this));
    require(allowance >= amount, "Check the token allowance");
    tokenAddress.transferFrom(msg.sender, contractAddress, amount);
 }
}

in case of using approve() function I get revert error, even tho the msg.sender is the user who is calling the function?
in case of using approveWithSender() I get "You cannot approve other users" Error defiend in Token contract.


texts: How to make ECDSA signature of (value_1, value_2) with web3 on Python?

texts:
I want to call function with four parameters. I know how to create two of them, but the last two is the r and s components of ECDSA signature of (param_1, param_2).
I tried this (and a lot of combinations), but the result is wrong:

msg = '%d%d' % (param_1, param_2)
message_hash = defunct_hash_message(text=msg)
signed_message = w3.eth.account.signHash(message_hash, private_key=wallet_private_key)
w3.toHex(signed_message['r'])[2:])
w3.toHex(signed_message['s'])[2:])

Next

From code of contract:

  r, s - components of ECDSA signature of (commitLastBlock, commit). v
  is guaranteed to always equal 27.

Made convertaion this way:

signatureHash = w3.soliditySha3(['uint40', 'uint256'], [commitLastBlock, commit])

I checked it and it's valid. But when I sign the result, the r and s values are wrong anyway. I do it whis way:

signed_message = w3.eth.account.signHash(signatureHash, private_key)


texts: Problem to use an address within a contract. Error: invalid address

texts:
I have a private blockchain.

I am creating a contract and then I am calling a function that returns the main account. I have the error calling this function.

This is the contract creation code:

var browser_untitled1_sol_mytokenContract = web3.eth.contract([{"constant":false,"inputs":[],"name":"GetMain","outputs":[{"name":"resultMain","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"GetBalance","outputs":[{"name":"result","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]);
var browser_untitled1_sol_mytoken = browser_untitled1_sol_mytokenContract.new(
   {
     from: web3.eth.accounts[0],
     data: '0x6060604052341561000f57600080fd5b5b33600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506301406f406000819055505b5b6101238061006d6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063266b1c72146047578063f8f8a912146099575b600080fd5b3415605157600080fd5b605760bf565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341560a357600080fd5b60a960ea565b6040518082815260200191505060405180910390f35b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505b90565b6000805490508090505b905600a165627a7a72305820d65d41c2db3b45a3505ad0645f63c88098090cacaedf6000af2c10ba2dab8c720029',
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

I call the function browser_untitled1_sol_mytoken.GetMain(); to get the main address and get the error:

Error: invalid address
    at web3.js:3879:15
    at web3.js:3705:20
    at web3.js:4948:28
    at map (<native code>)
    at web3.js:4947:12
    at web3.js:4973:18
    at web3.js:4998:23
    at web3.js:4061:16
    at apply (<native code>)
    at web3.js:4147:16