texts: truffle init function is showing an error on my Ubuntu 18.04 system

texts:
When I execute the truffle init command on my command line(Ubuntu 18.04) it's showing me the following error.
ubuntu@ubuntu-vbox:~/block_chain/Ballot1$ truffle init
Downloading...
Error: Truffle Box at URL https://github.com/truffle-box/bare-box.git doesn't exist. If you believe this is an error, please contact Truffle support.
    at Request._callback (/usr/lib/node_modules/truffle/build/cli.bundled.js:313432:23)
    at Request.self.callback (/usr/lib/node_modules/truffle/build/cli.bundled.js:284800:22)
    at Request.emit (events.js:160:13)
    at Request.<anonymous> (/usr/lib/node_modules/truffle/build/cli.bundled.js:285777:10)
    at Request.emit (events.js:160:13)
    at IncomingMessage.<anonymous> (/usr/lib/node_modules/truffle/build/cli.bundled.js:285699:12)
    at Object.onceWrapper (events.js:255:19)
    at IncomingMessage.emit (events.js:165:20)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:152:19)

Ganache is already installed on my OS. How do I tackle this problem?


texts: How to create a transaction with same nonce?

texts:
How do I create a new transaction that has the same nonce as a previous transaction?

I sent a txn with 4Gwei gas price and I want to cancel it by sending a 0 Eth txn with the same nonce.

I am running geth 1.7.1.


texts: Want a large number of Test Ethers. How to get them?

texts: I have made a proof of concept that works on Ropsten Test Network. Now for users to use it I need a large number of Test Ethers in my account. As far as I know, we can get only one ether with one IP in a day. I need thousands of ethers. How can I get those? Please help. Its urgent.


texts:
My understanding is that msg.sender pays the gas fee. Can a smart contract be written in such a way that it's always the contract owner who pay the fees?

As an example, in an ERC20 token when someone transfers the tokens, he pays the gas fee but what if the gas fee for every transfer has to be paid by smart contract owner?


texts:
How does Casper achieve that all validators magically converge to a block without deciding the block deterministacally (stake-grindable)?

How is this implemented in the testnet?


texts: Why is there block gas limit? Should it just be the sum of gas limit used by each transactions inside the block? Why do we need an extra field for it instead of calculate it?


texts: Error: Invalid JSON RPC response: "" infura on contract deploy

texts:
I am trying to deploy contract i am using web3.js version web3@0.20.4 with infura node

following code i am trying

const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/metamask"));
const Tx = require('ethereumjs-tx');

let privateKey = new Buffer('8A0F4E01AC43A014F9F13CF68E', 'hex');

let source = fs.readFileSync('contract.sol', 'utf8');// solc file source decided by yourself
let compiledContract = solc.compile(source, 1);
let abi = compiledContract.contracts[':Adeel'].interface;
let bytecode = compiledContract.contracts[':Adeel'].bytecode;

// Contract object
const MyContract = new web3.eth.contract(JSON.parse(abi));

// Get contract data
const contractData = MyContract.new.getData({
    data: '0x' + bytecode
});

const gasPrice = web3.eth.gasPrice;
const gasPriceHex = web3.toHex(gasPrice);
const gasLimitHex = web3.toHex(300000);

const nonce = web3.eth.getTransactionCount(web3.eth.coinbase);
const nonceHex = web3.toHex(nonce);

const rawTx = {
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: contractData,
    from: '0x5488365e6785e571762ee980400e64c62853c2c0'
};

const tx = new Tx(rawTx);
tx.sign(privateKey);
const serializedTx = tx.serialize();

web3.eth.sendRawTransaction(serializedTx.toString('hex'), (err, hash) => {
    if (err) { console.log(err); return; }

    // Log the tx, you can explore status manually with eth.getTransaction()
    console.log('contract creation tx: ' + hash);

    // Wait for the transaction to be mined
    waitForTransactionReceipt(hash);
});

function waitForTransactionReceipt(hash) {
    console.log('waiting for contract to be mined');
    const receipt = web3.eth.getTransactionReceipt(hash);
    // If no receipt, try again in 1s
    if (receipt == null) {
        setTimeout(() => {
            waitForTransactionReceipt(hash);
        }, 1000);
    } else {
        // The transaction was mined, we can retrieve the contract address
        console.log('contract address: ' + receipt.contractAddress);
        //testContract(receipt.contractAddress);
    }
}

error is here

Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (/var/opt/webserver/adeel/adeelotxeth/node_modules/web3/lib/web3/errors.js:38:16)
    at HttpProvider.send (/var/opt/webserver/adeel/adeelotxeth/node_modules/web3/lib/web3/httpprovider.js:101:18)
    at RequestManager.send (/var/opt/webserver/adeel/adeelotxeth/node_modules/web3/lib/web3/requestmanager.js:58:32)
    at Eth.get [as coinbase] (/var/opt/webserver/adeel/adeelotxeth/node_modules/web3/lib/web3/property.js:107:62)
    at Object.<anonymous> (/var/opt/webserver/adeel/adeelotxeth/test.js:26:53)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)


texts: Metamask Web3js Synchronous Method Error

texts:
Okay guys, I'm a complete newbie to Ethereum and Web3.js and going through the Crypto Zombies tutorial and have done okay so far.

But, when I use this function in my index.html file as they show it I get the

  Uncaught Error: The MetaMask Web3 object does not support synchronous
  methods like eth_call without a callback parameter.

Here's the function:

function getZombiesByOwner(owner) {
        return cryptoZombies.methods.getZombiesByOwner(owner).call()
      }

Contract Function Code:

function getZombiesByOwner(address _owner) external view
returns(uint[]) {
  uint[] memory result = new uint[](ownerZombieCount[_owner]);
  uint counter = 0;
  for (uint i = 0; i < zombies.length; i++) {
   if (zombieToOwner[i] == _owner) {
    result[counter] = i; counter++;
   }
  }
return result;
}

I get that it wants me to use a callback and I've looked at every example/tutorial I could find for the last 2 days. None of the examples that I've tried to replicate have worked.

Is there anyone here who could show me how that function would be written as an asynchronous call instead of the synchronous way I have it here? I'd appreciate it very much because I don't think I've ever felt this stupid in my whole life.

Thanks in advance.


texts: How to check if a user had registered in My DAPP with Metamask?

texts: I want to check if a user had registered in my DAPP with Metamask..Do I need to store User struct in solidity to control that  or just depend on metamask for authentication.??


texts: Is it possible to prove ETH balance without revealing the holding address?

texts: I want to prove that I own an amount of ETH without revealing the address which holds it. I don't know if this is possible at all, whether with zk-snarks technology or any other way. I've found nothing on this and I'm not knowledgeable enough to figure out by myself.  Does anyone can shed some light on this? Thanks!


texts: Is possible for a contract to manage and hold different address and its balance for different erc20 tokens?

texts:
Imagine an exchange contract to store and handle  different accounts for different buyers and sellers, it is possible for a contract to manage and hold different address and its balance for different erc20 tokens?

I know that a common pattern is to use approve, allowance and transferfrom, but this pattern doesnt guarantee a funds availability.

I am wondering if it is possible for a contract to generate different addresses and handle wallets?


texts: How to set truffle-hdwallet-provider as the Web3 currentProvider inside a web page

texts:
https://github.com/trufflesuite/truffle-hdwallet-provider/blob/master/README.md provides sample usage for the deployment configuration inside tuffle.js.

I need a sample that update the Web3 currentProvider inside a web page to be used differently with every user (I will use the code upon a user request after generating the mnemonic seed words)

Update:

Thanks to @jsantos, and I found it here also: https://gnosis-apollo.readthedocs.io/en/latest/pm-js-usage.html.

Actually, it was not mentioned in the documentation that the truffle-hdwallet-provider is compatible with Web3 and could be passed in the constructor. I created a pull request for that: https://github.com/trufflesuite/truffle/pull/1850.
Bellow is the code snippet:

var HDWalletProvider = require("truffle-hdwallet-provider");
var mnemonic = "mountains supernatural bird..."; // 12 word mnemonic
var provider = new HDWalletProvider(mnemonic, "http://localhost:8545");

// Or, alternatively pass in a zero-based address index.
var provider = new HDWalletProvider(mnemonic, "http://localhost:8545", 5);

// Or, use your own hierarchical derivation path
var provider = new HDWalletProvider(mnemonic, "http://localhost:8545", 5, 1, "m/44'/137'/0'/0/");

// HDWalletProvider is compatible with Web3. Use it at Web3 constructor, just like any other Web3 Provider
const web3 = new Web3(provider);

// Or, if web3 is alreay initialized, you can call the 'setProvider' on web3, web3.eth, web3.shh and/or web3.bzz
web3.setProvider(provider)

// ...
// Write your code here.
// ...

// At termination, `provider.engine.stop()' should be called to finish the process elegantly.
provider.engine.stop();


texts: Myetherwallet says not a valid address on Poloniex

texts:
So, I've tried this multiple times.  I put myetherwallet address in at Poloniex to withdraw some of my coins and put them back into myetherwallet and everytime i put my address in, it says "invalid address".  Anybody experience this?  Not sure if the address has to be converted?

Any ideas?


texts: Very basic newcomer question - Do you gain anything back from running Smart Contracts on the blockchain?

texts:
I have just finished reading a book on the Blockchain and Smart contracts (https://www.amazon.com/Decentralized-Computing-Using-Technologies-Contracts/dp/1522521933)

I have a very basic newbie question arising from this, and I can't find the answer by Googling:

If I want to run a Smart Contract on the blockchain, I will need to purchase Ether with fiat money to use as gas.

If I use up all of the Ether I have purchased to to run my smart contract(s). I will have to go ahead and purchase more Ether to continue to run my smart contract(s).

Is there a way that one earns back Ether/gas by running smart contracts on the blockchain, or is it a never-ending process of purchasing Ether to continue running smart contracts on The Blockchain?


texts: fallback-to-build error while installing Truffle in Ubuntu 16.10

texts:
I was installing Truffle in Ubuntu 16.10 using sudo , but I got the following error message:

npm WARN wrtc@0.0.63 license should be a valid SPDX license expression
npm ERR! Linux 4.4.0-59-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! wrtc@0.0.63 install: node-pre-gyp install --fallback-to-build
npm ERR! Exit status 1
npm ERR!  Failed at the wrtc@0.0.63 install script 'node-pre-gyp install --fallback-to-build'.
npm ERR! Make sure you have the latest version of node.js and npm installed. > npm ERR! If you do, this is most likely a problem with the wrtc package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system: node-pre-gyp install --fallback-to-build
npm ERR! You can get information on how to open an issue for this project with:  npm bugs wrtc npm
Or if that isn't available, you can get their info via: npm owner ls wrtc


texts: Is it possible to use address you don't own while running ethereum RPC node (using geth)?

texts:
In other words, you start your own node and then somehow add accounts you don't own (aka - you don't have their private keys)?

I'm asking because I wanted to make my own node exposed via RPC/internet. Then got curious how secure this is...apparently it isn't since someone used exposed RPC to steal millions a while back. Then I started googling and discovered some 'well known' rpc hosts, while looking into 10-20 of them I found one holding ethers worth nearly $200,000!

Fortunately (maybe fortunately??) this account was locked and "personal" was not available, so unless I am wrong this means no one can send transaction? I didn't try given how illegal this will be but I am 99% sure you can't do this with locked account without "personal".

I am rather curious: are these people too smart, too uncautious or what? And even if I use "personal" to lock the account with strong password - what prevents a hacker to try millions of dictionary combinations to guess the password?

Again: my plan is to start geth without "personal" on account which by default will/should be locked so that no one without root/sh access can start geth as unlocked (yeah not really root since I am on windows anyway but similar...).


texts: External js file not getting load in Truffle test

texts:
I'm writing up test cases for my smart contract. Here is the folder structure:

- bin
- build
- contracts
    - mytestfile.sol
- modules
    - mymodule.js
- test
    - mytestfile.js
truffle.js

I want to use one of the function from module file, hence I'm trying to load mymodule.js file into mytestfile.js in a following way.

var module = require('../modules/mymodule');

However, when I add upper line, truffle test stop working and displaying following output:

If I comment it out, it starts executing other test cases. I have also tried by adding .js extension.

Am I missing anything here?

Edit:
Here is a sample of the module file:

module.exports = {
verify : function(){

    }
}


texts: Indexed event parameter only returns 1st character in address

texts:
pragma solidity ^0.4.13;

contract OwnedI {
    /**
     * Event emitted when a new owner has been set.
     * @param previousOwner The previous owner, who happened to effect the change.
     * @param newOwner The new, and current, owner the contract.
     */
    event LogOwnerSet(address indexed previousOwner, address indexed newOwner);

    /**
     * Sets the new owner for this contract.
     *     It should roll back if the caller is not the current owner.
     *     It should roll back if the argument is the current owner.
     *     It should roll back if the argument is a 0 address.
     * @param newOwner The new owner of the contract
     * @return Whether the action was successful.
     * Emits LogOwnerSet.
     */
    function setOwner(address newOwner) returns(bool success);

    /**
     * @return The owner of this contract.
     */
    function getOwner() constant returns(address owner);

}

pragma solidity ^0.4.13;

import "./OwnedI.sol";

contract Owned is OwnedI {
    address public owner;
    function Owned() {
        owner = msg.sender;
    }

    modifier fromOwner() {
        require(msg.sender == owner);
        _;
    }
    /**
     * Sets the new owner for this contract.
     *     It should roll back if the caller is not the current owner.
     *     It should roll back if the argument is the current owner.
     *     It should roll back if the argument is a 0 address.
     * @param newOwner The new owner of the contract
     * @return Whether the action was successful.
     * Emits LogOwnerSet.
     */
    function setOwner(address newOwner) fromOwner returns(bool success) {
        require(msg.sender != address(0));
        require(newOwner != owner);
        address previousOwner = owner;
        LogOwnerSet(previousOwner, newOwner);
        owner = newOwner;
        return true;
    }

    /**
     * @return The owner of this contract.
     */
    function getOwner() constant returns(address outputOwner) {
        return owner;
    }
}

    pragma solidity ^0.4.13;

import "./Owned.sol";

contract CheckOwner is Owned {

    int public check ;

    function CheckOwner () {
        check = 1;
    }

    function setCheck() fromOwner {
        check++;

    }
}

I call setOwner(). When I remove the indexed keyword from OwnerI for LogOwnerSet, I am able to see the parameters in my transaction. However, if I keep the indexed parameter, in my transaction, my event parameters only show the first letter in the address.

Here is with indexed:

{
        "topic": "a1d2149652d81eb35c360c115fc7ac594124cb1ea8a5a33e9a7f5768c62869fb",
        "event": "LogOwnerSet",
        "args": [
            [
                "0xc"
            ],
            [
                "0x1"
            ]
        ]
    }

Here is without indexed:

[
    {
        "topic": "a1d2149652d81eb35c360c115fc7ac594124cb1ea8a5a33e9a7f5768c62869fb",
        "event": "LogOwnerSet",
        "args": [
            "0xca35b7d915458ef540ade6068dfe2f44e8fa733c",
            "0x14723a09acff6d2a60dcdf7aa4aff308fddc160c"
        ]
    }
]

As you can see, it returns just the 1st character of the address. I need the event log to be indexed.

Am testing in remix

Edit: I tried this with another Event(address out, bool paused) and transaction log parameter has similar problems. The address returns first char and the bool returns "0000000000000000000000000000000000000000000000000000000000000001" which is true. Am I missing some info on how indexed works?


texts: How can I call contract method that suicide and continue execution?

texts:
Can I call another contract that eventually will call selfdestruct, and keep executing my function?

For example, say I have two contracts as follows:

contract Destructor {
    address owner;

    constructor() {
        owner = msg.sender;
    }

    function done() public {
        selfdestruct(owner);
    }
}

contract Test {
    ...
    function test(address dtor) public returns(bool) {
        Destructor(dtor).done();
        // Can I keep execution here after dtor was destructed?
        bla += 42;
        return true;
    }
}

will bla += 42; be executed and test() will return true?


texts: Solidity modifier with function call error

texts:
pragma solidity >=0.4.22 <0.6.0;
contract Person {

    //owner address
    address private owner;

    //identity
    string private firstName;
    string private lastName;
    string private SID;

    constructor(string memory _firstName, string memory _lastName, string memory _SID) public {
        owner = msg.sender;
        firstName = _firstName;
        lastName = _lastName;
        SID = _SID;
    }

    modifier checkAccess(){
        require(this.getAccess() == true);
        _;
    }

    function getAccess() public view returns(bool access){
        //here will be more validation, but for now I just added this one
        return msg.sender == owner;
    }

    function getFirstName() public view checkAccess returns (string memory _firstName){
        _firstName = firstName;
    }
    function getLastName() public view returns (string memory _lastName){
        _lastName = lastName;
    }
    function getSID() public view returns (string memory _SID){
        _SID = SID;
    }
}

So I have this smart contract and I try to use a function inside the modifier and it gives me this error:

  call to Person.getFirstName errored: VM error: revert.
  revert  The transaction has been reverted to the initial state.
  Note: The constructor should be payable if you send value.  Debug the transaction to get more information.

Any idea why and how can it be solved? I wanna to add more checkings into getAccess function, checking a list of addresses or something like that, but for now I only added owner == msg.sender

EDIT: Copy paste the code into https://remix.ethereum.org in order to see more clearly the error


texts: Is there a way to disable a warning in solidity code?

texts:
I'm writing unit tests for some contracts and in some of the tests I'm generating a warning on purpose and solc will display this warning when compiling.

Is there a way to disable warnings in solc for the purpose of a test.

Something equivalent to MSVC++

#pragma warning(push)
#pragma warning(disable : 44444)
// CODE
#pragma warning(pop)


texts: Can contract use its own ethers as a gas when calling other contract?

texts:
Can rich contract (that holds some ethers) use them as a gas when it would like to call other contract?

http://solidity.readthedocs.io/en/latest/control-structures.html gives an example of feed.info.value(10).gas(800)(); and I am not sure if 800 is deducted from originally send gas or from current contract's ethers.


texts: How can I push data to array when using mapping (address => address[]) mappingName?

texts: What is the exact syntax to push data using the above given syntax?


texts: How does browser solidity differentiate calls from transactions with the abi?

texts:
It's all in the question.

I've noticed that there is a color difference for Transact/Transact(Payable)/Call

I would like to know if there is a javascript script to do that ? or i'd need calculate the gas cost for each function ?


texts: when do smart contract wallets need to sign transaction by themselves?

texts: Do smart contract wallets ever store priv/pub keys or something ? Of course, It would be then seen on the blockchain if it did, but I am asking this because somewhere, I've read that sometimes smart contract wallets SIGN the transaction. Not sure what that means but explanation and a little bit example would be great.


texts: Mining with Laptop with only one graphic card

texts: I have HP Elitebook 8460p with Radeon GPU and without additional integrated intel graphics in CPU. Is it possible to run GPU mining on it?


texts: Ether.li transfer problem despite correct password

texts:
AFter entering correct passwort when trying to transfer ETH on ether.li (via browser), I always get an error message "Type error: Object doesn't support property or method 'assign'"...

Does anyone know what to do? Thanks a lot in advance!


texts: Preventing Ethereum Wallet to download binaries

texts:
On Windows 10, I have a separate geth.exe running with custom configuration. But when I run Ethereum Wallet (0.8.10.1708) it downloads new binaries.
Is there a way to prevent it from doing that?
THX.


texts: truffle compile/migrate gives error: "ParserError: Expected pragma, import directive or contract/interface/library definition."

texts:
The tutorial I'm following created a 2_Migrations.sol with the following:

const Token = artifacts.require("Token");

module exports = function(deployer) {
  deployer deploy(Token);
};

"Truffle Migrate" gave this error:

e:\GitHub\NealWalters\DappUniversity\blockchain-developer-bootcamp>truffle migrate

Compiling your contracts...
===========================
> Compiling .\src\contracts\1_Migrations.sol
> Compiling .\src\contracts\2_Migrations.sol
> Compiling .\src\contracts\Token.sol

Error: CompileError: /e/GitHub/NealWalters/DappUniversity/blockchain-developer-bootcamp/src/contracts/2_Migrations.sol:3:1: ParserError: Expected pragma, import directive or contract/interface/library definition.
const Token = artifacts.require("Token");
^---^

Compilation failed. See above.
    at Object.compile (C:\Users\nwalt\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\workflow-compile\legacy\index.js:72:1)
Truffle v5.0.40 (core: 5.0.40)
Node v10.16.2

If I add the same Pragma that is in 1_migrations.sol (the file generated by truffle init" and renamed):

pragma solidity >=0.4.21 <0.6.0;

const Token = artifacts.require("Token");

module exports = function(deployer) {
  deployer deploy(Token);
};

I get the same error.

If I try the same pragma as my Token contract:

pragma solidity ^0.5.0;

const Token = artifacts.require("Token");

module exports = function(deployer) {
  deployer deploy(Token);
};

Also gives same error.

truffle-config.js contains this for the compiler settings:

  compilers: {
    solc: {
      optimizer: {
        enabled: true,
        runs: 200
      }
   }


texts: Issue calling one contract from another using Quorum

texts:
I'm using truffle and running locally with 4 quorum nodes, trying to call another contract's function, but keep getting 0 in return instead of the expected value the I get once calling the contract directly.

Truffle v4.1.15

Solidity v0.4.25

Here are the contracts:

contract Token {
   using SafeMath for uint;
   uint _totalSupply;
   address owner;
   mapping(address => uint) balances;

   event Transfer(address indexed from, address indexed to, uint tokens);

   constructor() public {
       _totalSupply = 1000000 * 10**uint(18);
       owner = msg.sender;
       balances[owner] = _totalSupply;
       emit Transfer(address(0), owner, _totalSupply);
   }

   function totalSupply() public view returns (uint) {
       return _totalSupply.sub(balances[address(0)]);
   }
}

contract Marketplace {

   Token public cashToken;

   constructor(address cashTokenAddress) public {
       cashToken = Token(cashTokenAddress);
   }

   function getTotalSupply() public view returns (uint) {
       return cashToken.totalSupply();
   }
}

and here's truffle's 2_deploy_contracts.js:

var SafeMath = artifacts.require("SafeMath");
var Token = artifacts.require("Token");
var Marketplace = artifacts.require("Marketplace");

var account1key = ...
var account2key = ...
var account3key = ...

var publicKeys = [account1key, account2key, account3key];
var tokenAddress;

module.exports = function(deployer) {

 deployer.then(async () => {

   deployer.deploy(SafeMath, {privateFor: publicKeys});
   deployer.link(SafeMath, Token);

   await deployer.deploy(Token, {privateFor: publicKeys}).then(() => {
     console.log("tokenAddress: ", Token.address)
     tokenAddress = Token.address;
   });

   await deployer.deploy(Marketplace, tokenAddress, {privateFor: publicKeys});
 })

};

The response I get while connected to the same node the contracts were deployed from:

truffle(development)> Token.deployed().then(function(contract) { return contract.totalSupply() });
BigNumber { s: 1, e: 24, c: [ 10000000000 ] }

truffle(development)> Marketplace.deployed().then(function(contract) { return contract.getTotalSupply() });
BigNumber { s: 1, e: 0, c: [ 0 ] }

What am I doing wrong?

Many thanks


texts: How can I check which network I'm working on?

texts:
When I start eth I get the following header:

$ eth
(++)Ethereum
Beware. You're entering the Frontier!
[...]

I think i followed the instructions for working on a private network (because i just want to check out the technology) but how can i check if I'm working on the real network?


texts: Is it possible to deploy a contract using create2 in Solidity?

texts: Can I deploy a contract in Solidity (not in-line assembly) using create2?


texts: So, I'm running my rig on the ethermine pool and I used the geth program to setup a wallet which acts as my "miner" name on ethermine.  When I click on my miner address I am taken to etherchain.org and it's shows my balance etc.  Now how the hell do I transfer that ether to a coinbase to poloniex?  I can't seem to do anything with it.


texts:
I am studying about DApps and Ethereum. I did get the Solidity part but I am confused about the front-end apps.

Is it possible that I use web framework like PHP Laravel/Rails for Frontend/Db operations and interact with backend Blockchain via web3.js or anything?


texts: Ethereum's block times are under 10 seconds compared to most other coins which are in minutes. Why and How?

texts: Ethereum's blocktimes is under 10 seconds but other coins like BTC, LTC, and others are usually in minutes. How does ethereum solve the problems to why those other blocktimes are in minutes? Basically looking for a comparison and the pros/cons of having such short blocktimes and how it compares to other coins.


texts:
Having trouble integrating web3 from Metamask in React.
Metamask version: web3@1.0.0-beta.34

import Web3 from 'web3'

let web3;

window.addEventListener('load', function () {
    if (typeof window.web3 !== 'undefined') {
        web3 = new Web3(window.web3.currentProvider);
    } else {
        // No web 3 provider
        console.log("Please install Metamask");
    }
});

export default web3;

Getting the following error:

window is not defined
ReferenceError: window is not defined
    at Object../lib/getWeb3.js (lib/getWeb3.js:5:0)


texts:
I want to use a factory so that people can create a standardized contract.  People should be able to transfer money directly by this creation which led me to the problem of the msg.sender during the exceution. I read that tx.origin has some security flaws but I wonder if this is also true just for the creation of contracts by a factory. Following example contract:

 pragma solidity ^0.4.0;

    contract Factory {

     address[] public contracts;

       function createContract ()
          payable
          public
       {
          Con newCon = (new Con).value(msg.value)();
          contracts.push(newCon);
       }

    }

    contract Con {

     address owner;
     uint256 valueOwner
;

     function Con()
        payable
        public
     {
        owner = tx.origin;
        valueOwner = msg.value;
     }

       function withdraw ()
          public
       {
          if(msg.sender == owner)
             msg.sender.transfer(valueOwner);
       }

    }

I do not see why tx.origin should do any harm here or am I missing some point?


texts: ganache forked mainnet always revert even on success transaction in mainnet

texts:
I am trying to impersonate an account using forked mainnet what I did was unluck the unknown account, approve the erc-20 token and copy then send the transaction of that address. Everytime the address send a transaction I run the tx first on forked mainnet to estimate if there will be a revert will happen in advance. The issue was every transaction returns a revert error UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT then I check on the etherscan the same transaction is a success. I don't understand why this happen and how to resolve this issue?
Snippet of my code:
const localWeb3 = new Web3(
   new Web3.providers.WebsocketProvider('ws://localhost:8546') // forked mainnet
)

localWeb3.extend({
   methods: [{
       name: 'unlockAccount',
       call: 'evm_unlockUnknownAccount',
       params: 1
   }]
})

await localWeb3.unlockAccount(tx.from)

let abi = [ //long abi ]

const localContract = new localWeb3.eth.Contract(abi, tokenAddress)
let allowance = await localContract.methods.allowance(tx.from, UNISWAP_ROUTER_ADDRESS).call()
console.log("allowance: ", allowance)

localWeb3.eth.sendTransaction({
    from: tx.from,
    to: tx.to,
    gasPrice: tx.gasPrice,
    gasLimit: tx.gas,
    input: tx.input
})
.on('error', async (err) => {
    console.log(count, err)
})
.then(async (receipt) => {
    console.log(receipt)
})


texts: Geth RPC eth_getTransactionReceipt method

texts:
Geth RPC docs:

eth_getTransactionReceipt

Returns the receipt of a transaction by transaction hash.

Note That the receipt is not available for pending transactions.

What is the reason why Receipt not available for pending transactions?


texts: How to send signed transactions concurrently via Infura?

texts:
I'm using web3js and web3js-raw as follows to change state of my smart contract on ethereum,

let initiateAddLoyaltyTransaction = function (fromWallet, toWallet, companyName, amount, callback) {
let functionName = 'transferWithAddLoyalty';
amount = web3.utils.toWei(amount.toString(), 'ether');
let params = [fromWallet, toWallet, amount, companyName];
W3JSR.prepareSignSend(config.ethereum[ethereumNetwork].ABI_DEFINITION, config.ethereum[ethereumNetwork].CONTRACT_ADDRESS, functionName,
    config.ethereum[ethereumNetwork].WALLET_ADDRESS, privateKey, params, 10000000000).then((result, error) => {
    callback(result, error);
});

};

It works fine when I call this function and wait for the transaction to mined by miners. But the problem is when I send another transaction before first one completes( because my use case needs to do several transactions in a short period of time) it gives an error saying

message: Error: Returned error: known transaction: 5abe27f97e23fb660b514c87c4d7db150dbd23bcf54632eef09fad6ec64427fe

I can see that the nonce is same for both transactions. Could someone please explain me how to deal with nonce while using Infura. Do I need to maintain nonce localy? And how to retry if one transaction fails


texts: Solidity + web3 js Why amount stay 0 with this simple deposit function

texts:
I publsh and initialize this sm

pragma solidity ^0.4.17;
contract CommunityChest {
    function withdraw() public {
        msg.sender.transfer(address(this).balance);
    }

    function deposit(uint256 amount) payable public {
        require(msg.value == amount);
        // nothing else to do!
    }

    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }
}

with web3 js i intialize my contract and try to deposit 1 ether to contract adresse with the "desposit" function

var value = 1;
var params = {
gas: 40000,
from: userAccount
};
myContract.deposit(value, params, function(error, result){
    if(!error){
        console.log(result);
    }else{
        console.error(error);
    }
  });

Why my amount stay at 0 on Metamask ?


texts: Transaction happen but ethers were not send in private network

texts:
I wanted to transfer 5 etheres from my coinbase address to my another account.
My coinbase balance is:

    > eth.getBalance(eth.coinbase)
     9.999999999999999999999999999999999e+33

So I transferred it and sendTransaction gave txhash also

     > personal.unlockAccount(eth.coinbase, "jevel")
    true
 > eth.sendTransaction({from:eth.coinbase,
to:"0xe773d39957869a5edf76285fadb78e49875f273e", value:web3.toWei(5,
"ether"), gas:21000})
INFO [09-24|10:38:50.553] Submitted transaction
fullhash=0x153e720efb94bfd97b3995766407407a0e95b31c92cf5665eec9338f5ce86236
recipient=0xe773D39957869A5EDF76285fAdB78E49875F273e
"0x153e720efb94bfd97b3995766407407a0e95b31c92cf5665eec9338f5ce86236"

but when I checked it, it was showing null:

    >eth.getTransactionReceipt("0x153e720efb94bfd97b3995766407407a0e95b31c92cf5665eec9338f5ce86236")
null

After that I mined my transaction :

  INFO [09-24|11:09:13.298] Generating DAG in progress
 epoch=0 percentage=98 elapsed=3m48.012s
INFO [09-24|11:09:15.562] Generating DAG in progress               epoch=0
percentage=99 elapsed=3m50.277s
INFO [09-24|11:09:15.564] Generated ethash verification cache      epoch=0
elapsed=3m50.278s
INFO [09-24|11:09:28.690] Generating DAG in progress               epoch=1
percentage=0  elapsed=10.568s
INFO [09-24|11:09:39.675] Generating DAG in progress               epoch=1
percentage=1  elapsed=21.553s
INFO [09-24|11:09:50.649] Generating DAG in progress               epoch=1
percentage=2  elapsed=32.527s
INFO [09-24|11:10:01.199] Generating DAG in progress               epoch=1
percentage=3  elapsed=43.077s
INFO [09-24|11:10:13.226] Generating DAG in progress               epoch=1
percentage=4  elapsed=55.104s
> miner.stop()
 true

Then I checked the number of blocks mined:

    > eth.blockNumber
     0

It is showing 0.

My private network have zero peers. Is that the problem???


texts: Difference between execution costs on remix an Ganache?

texts:
I created a contract on remix and then deployed it. when I call any function there is an execution cost in gas.  I also deployed the same contract on Ganache for testing. I find the execution cost in remix is 525424 gas but in Ganache, i found the gas used 1214584 gas.
Is the execution costs in remix is accurate, Is it simulate the actual execution costs on etherum network?
How can I know the execution cost in ganache?


texts: Error : invalid asm.js : Invalid member of stdlib when executing node deploy.js

texts:
Unable to deploy contract on Rinkeby network using infura and mnemonic of metamask account.

I am using Atom as IDE for writing smart contract using solidity.

As soon as I execute node deploy.js, I get error as invalid member of stdlib
I tried reinstalling npm, solc, truffle-hdwallet-provider but to no luck.
Even the console.log does not print anything on console.

Below is the dependency in my package.json:

"dependencies": {
    "ethereumjs-testrpc": "^6.0.3",
    "ganache-cli": "^6.4.3",
    "mocha": "^6.1.4",
    "python": "0.0.4",
    "solc": "^0.4.25",
    "truffle-hdwallet-provider": "^1.0.8",
    "web3": "^1.0.0-beta.37"
  }

deploy.js

   const HDWalletProvider = require('truffle-hdwallet-provider');
   const Web3 = require('web3');
   const {interface,bytecode} = require('./compile');

   const provider = new HDWalletProvider(
     'my mnenonic',
     'infure URL'
   );

   const web3 = new Web3(provider);

   const deploy = async()=>{

   const accounts = await web3.eth.getAccounts();

   console.log('Attempting to deploy from account',accounts[0]);

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

   console.log('Contract deployed to', result.options.address);

  };
  deploy();


texts: How execute a contract method with private key / sign send method?

texts:
I'd like to execute an erc20 contract method without unlocking a wallet, signing the transaction inside my code.
Here is how the code should look like:

  public async send(sender: string, receiver: string, value: number, key: string)
    : PromiEvent<object> {
    return this.contract.methods.transfer(receiver, value)
      .send({ from: sender });
  }

the current code doesn't allow me to sign manually, it assumes the sender address is unlocked. How can I sign send manually?


texts:
I am trying to write an application using web3.js and I want to integrate some ERC20 functionality. But rather than muddy up the mainnet, I'd like to try things on the Testnet first. I see that https://ropsten.etherscan.io/address/0x722dd3f80bac40c951b51bdd28dd19d435762180#tokentxns is a standard Testnet token. Is there anyway for me to get my hands on some?

Or perhaps another ERC20 compliant testnet token?


texts: Which is the safest way to generate a random number?

texts:
I need a function that generates a random number from 0 to n for the lottery.
I found 2 ways to do that:
1. https://gist.github.com/alexvandesande/259b4ffb581493ec0a1c
But miners can influence the number by not publishing a block with an unwanted outcome
2. Use JSON-RPC random.org with oraclize.it
But oraclize is centralized service.
So, which is the safest way to generate a random number?


texts:
pragma solidity 0.6.6;

import "./SafeMath.sol";
// import "./FreezeFunction.sol";
// import "./XYZToken.sol";

contract Vault is FreezeFunction{
    // Using SafeMath to prevent underflow and overflow
    using SafeMath for uint;

    mapping(address => uint256) public vaultBalance;
    mapping(address => bool) public hasDepositedEther;
    mapping(address => bool) public isStaking;

    event Withdrawal(address indexed src, uint _ethAmount);
    // event Staking(address src, bool locked);

    // User deposits eth -> vaultBalance -> vaultBalance bal updates
    function depositEther(uint _ethAmount) public payable returns(bool success) {
        require(_ethAmount > 0 ether, "Cannot be 0");

        address(this).transfer(_ethAmount);
        vaultBalance[msg.sender] = vaultBalance[msg.sender].add(_ethAmount);

        hasDepositedEther[msg.sender] = true;
        isStaking[msg.sender] = false;
        return true;
    }

        // Allows user to withdraw a desired amount of eth from their vault address.
    function withdrawEther(uint _ethAmount) public returns(bool success) {
        require(vaultBalance[msg.sender] != 0, "No funds to withdraw");
        require(isStaking[msg.sender] != true, "Cannot withdraw eth while staking");
        require(vaultBalance[msg.sender] >= _ethAmount, "Not enough funds to withdraw");

        vaultBalance[msg.sender] = vaultBalance[msg.sender].sub(_ethAmount);
        msg.sender.transfer(_ethAmount);

        emit Withdrawal(msg.sender, _ethAmount);
        return true;
    }

    function contractBal() public view returns(uint bal) {
        bal = address(this).balance;
        return bal;
    }

    // Fallback function that receives ether
    receive() external payable {}
}

When I withdraw in remix, it doesn't add the transfer amount to the address's wallet.
Not sure how to fix this.


texts: how miners within a mining pool execute transactions and verify blocks?

texts:
I know that solo miners have to select & execute transactions in a block and also verify the recipint block and its transactions, all by themself.
However, I am not sure how this works in a mining pool. Who execute transactions in a block? and how verify the recipint block and its transactions? Do miners within a pool collabarate with each other in executing transactions in a block and verifying transactions in the recipint block? (e.g., every miner is responsible for a set of transactions) or these tasks are only done by the manager of the mining pool, and miners only participate in the PoW consensus?
I would appreciate if there is a research paper that clearly say and answer those questions.


texts: Mocha timeout, not resolving promise of large array from method.mymethod.call()

texts:
I'm trying to test a contract getter method that returns a large array. I am testing using the web3 library in Mocha with ganache-cli provider. My contract deploys alright, but trying to call the getArray() test doesn't pass.

Contract:

    pragma solidity ^0.4.24;
    contract myContract{
            bytes32[7500] public array;
            function getArray() public view returns(bytes32[7500]){
                return array;
            }
    }

Test:

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

const compiledContract = require('../ethereum/build/myContract.json');

let accounts;
let mycontract;

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

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

});

describe('ourPlace', () => {
    it('allows manager to retrieve array', async (done) =>{

            const array = await mycontract.methods.getArray().call({from: accounts[0], gas:'6000000'});
            const length = array.length;
            console.log(length);
            assert.equal(7500, length);

        }).timeout(15000);
});

I first tested with 'done' and '.timeout'. The log reports a proper length of 7500 despite the Promise not resolving. The error reads:

  Error: Timeout of 15000ms exceeded. For async tests and hooks, ensure
  "done()" is called; if returning a Promise, ensure it resolves.

I have had a somewhat similar issue with Remix's Javascript VM. But, when I deploy on Remix using Injected Web3 to Rinkeby, Remix returns the large array just fine. This makes sense because it's just a call.  How do I resolve this promise? I would like to be able to run the tests properly. Thanks.

Edit: Full test code. Dependencies: "fs-extra": "^6.0.1","ganache-cli":"^6.1.3","mocha": "^5.2.0","solc": "^0.4.24","web3": "^1.0.0-beta.34"


texts:
I am very new to solidity programming, I have issue while running one solidity smart contract.

 pragma solidity >= 0.4 .22 < 0.6 .0;

 contract DocumentManager {

 mapping(uint => Document) documents;
 uint public nbDocuments;
 address public owner;

 enum Status {
    UNKNOWN,
    OPEN,
    DONE,
    DENIED
 }

struct Document {
    address owner;
    string document;
    string name;
    uint nbRequests;
    string privateKey;
    mapping(uint => Request) requests;
}

struct Request {
    address owner;
    Status status;
    string key;
}

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

function newDocument(string memory hash, string memory name) public {
    nbDocuments++;
    documents[nbDocuments].owner = msg.sender;
    documents[nbDocuments].document = hash;
    documents[nbDocuments].name = name;
    documents[nbDocuments].nbRequests = 0;
}

  function grantAccess(uint documentId, uint requestId, string memory
   encryptedKey) public {
    uint256 document = documents[documentId];
    if (document.owner == msg.sender) {
        document.requests[requestId].status = Status.DONE;
        document.requests[requestId].key = encryptedKey;
     }
  }

 function denyAccess(uint documentId, uint requestId) public {
    uint256 document = documents[documentId];
    if (document.owner == msg.sender) {
        document.requests[requestId].status = Status.DENIED;
    }
 }

   function requestDocument(uint documentId, string memory publicKey)
    public {
    uint256 document = documents[documentId];
    document.nbRequests++;
    uint256 request = document.requests[document.nbRequests];
    request.status = Status.OPEN;
    request.owner = msg.sender;
    request.key = publicKey;
  }

  function getLastRequestId(uint documentId) public returns(uint) {
    return documents[documentId].nbRequests;
   }

  function getOpenRequestPublicKey(uint documentId, uint requestId)
   public returns(string memory) {
    uint256 request = documents[documentId].requests[requestId];
    if (request.status == Status.OPEN) {
        return request.key;
    }
    return "";
  }

function getRequestOwner(uint documentId, uint requestId) public
  returns(address) {
    uint256 document = documents[documentId];
    if (document.owner == msg.sender) {
        return document.requests[requestId].owner;
    }
 }

function getDocument(uint documentId) public returns(string memory
  hash) {
    return documents[documentId].document;
}

function getDocumentName(uint documentId) public returns(string memory
 name) {
    return documents[documentId].name;
}

function getEncryptedKeyFromRequest(uint documentId, uint requestId)
 public returns(string memory) {
    uint256 request = documents[documentId].requests[requestId];
    if (request.status == Status.DONE) {
        return request.key;
    }
    return "";
}

function getDocumentHash(uint documentId) public returns(string
 memory) {
    return documents[documentId].document;
}

function getRequestStatus(uint documentId, uint requestId) public
 returns(Status) {
    return documents[documentId].requests[requestId].status;
 }

}

When I am getting issue like below issue

   on line number 39-40
     browser/ballot.sol:39:9: TypeError: Type struct
  DocumentManager.Document storage ref is not implicitly convertible
   to expected type uint256.
    uint256 document = documents[documentId];
    ^--------------------------------------^

  browser/ballot.sol:40:12: TypeError: Member "owner" not found or not
  visible after argument-dependent lookup in uint256.
    if(document.owner == msg.sender) {
       ^------------^

When I tried old version of solidity it is running fine(pragma 4.22 version).

Thanks in advance


texts: HelloWorld contract using truffle v3.2.1

texts:
I made my first very simple HelloWorld smart contract :

pragma solidity ^0.4.4;

contract HelloWorld {
    uint public balance;

    function sayHi() returns (bool success) {
        balance = 1000;
        return true;
    }
}

Trying to deploy all using truffle in a testrpc local network
My deploy contracts looks like this :

var HelloWorld = artifacts.require("./HelloWorld.sol");
module.exports = function(deployer) {

  deployer.deploy(HelloWorld);
};

I truffle build && truffle migrate and then try to use my contract, I can see that my contract is correctly deployed, I can access my testrpc network (accounts available etc ...)  but I try to get my balance :

truffle(development)> var aHelloWorld = HelloWorld.deployed()
undefined
truffle(development)> aHelloWorld.balance.call().then(console.log)
TypeError: Cannot read property 'call' of undefined

It doesn't find my balance property ... however if I console.log my aHelloWorld object, I can see that it has a balance property.

and then I called :

truffle(development)> aHelloWorld.toString()
'[object Promise]'

So it seems that my contract stays as a promise, I tried  :

truffle(development)> aHelloWorld.then(function (myContract) {
  myContract.sayHi().then();
  console.log(myContract.balance.call().then(console.log))
})
Promise { <pending> }
undefined
truffle(development)> { [String: '1000'] s: 1, e: 3, c: [ 1000 ] }

It correctly changed my balance, I am happy but reaally confused... I've watched few tutorials and also read some answers here about basic steps like Truffle error: Cannot read property 'call' of undefined
It works for them all by doing HelloWorld.deployed().balance.call()...

I mean accessing the contract directly through HelloWorld.deployed() without waiting for the promise ...
Is it because the version of truffle I use or am I doing something wrong ?

UPDATE :
Even truffle tutorial shows direct access to the deployed() object :
http://truffle.readthedocs.io/en/latest/getting_started/testing/


texts:
What is the default lockout time for Ethereum accounts?
I know that we can mention the time until which we need the account in unlocked state:

personal.unlockAccount(addr, pswd, duration)

This command will keep the account unlocked for the specified duration (seconds).

But, if I don't mention the time and unlock an account like this:

personal.UnlockAccount(addr, pswd)

After how much time will it be locked?


texts: I am running a private ethereum network using geth. I started the bootnode first following the documentation and ran 5 different nodes on the same machine with same genesis file on same network with the bootnode specified. Three of them managed to peer themself but two of them doesn't have any peer at all. After 1 hour the 4th node got a peer but the 5th one still has no peer. I assume given enough time all the peers will sync up. Why does the bootnode take so much time to sync peers in the nodes? Is there certain configurations to speed up the process. ps. i don't want to add the peers manually using admin.addPeer('enodeAddr').


texts: What is the best way of token redemption by user?

texts:
Background

RETN Deals offers discount coupons from global brands and in addition, offers generous cashback in Cryptocurrency (RETN). The web application automatically tracks consumer purchases at these stores and rewards them in crypto. Once the user reaches the min withdraw-able limit that is set within the web-app, they become eligible to redeem RETN.

Looking for the best approach to handle the redemption process.

Ways of approach

  Approach 1.

Whenever the user clicks Redeem, the web app calls token.transfer method and transfers the token from RETN Deal’s address to the user’s ERC20 address.

Benefits

Validation happens on the server side, the user cannot manipulate
more value than what they eligible for.

Problems

Gas Price: The web app owner has to bear the gas price for every
single redeem. Cost consumed in transferring the tokens to the end
users are very high
Queue: Every user’s transactions get clogged
until the previous transactions get cleared. This is because of the
NONCE will get incremented for every transaction as they originate from the same address.

  Approach 2

Create a smart contract that can be called (via metamask) by the user

Benefits

Cost-effective : The consumer is the bearer for the gas price
Queue : Transaction origination will be different for each customer’s
and thus the transaction will be fast
Customer’s choice: The customer can choose how much to withdraw, and
when to withdraw it. He/she can control the gas price too.

Problems

The withdraw-able limit has to be set every time in the contract so
that the user cannot withdraw more than they deserve. This consumes
gas. Even if an array of items is set, the number of items in an
array cannot be more than 180(approx.) due to the block/transaction
gas limit, thus more number of transactions will need to set the
limit itself which will again consume the gas from the sender and the
transactions keep pending in the queue until its ancestor
transactions get mined.
If the user’s withdraw-able limit is not set, they will not able to redeem
If we are to allow the users to redeem without setting the limit, the user can withdraw more value than what he/she is eligible for.

What is a better approach to allowing consumers to redeem RETN, which can create value for the consumer, maintain the security of the contract, reduce gas consumption by RETN, and not clog the blockchain?

Should oraclize be of any help to this kind of problems? Guess that will still consume gas.


texts: How msg.sender changes through relaying function calls between contracts?

texts:
Here is the example for question.

contract example1 {
  function A() {
    print msg.sender; // just fake code to imagine it prints out the result
    example3.C();
  }
}

contract example2 {
  function B() internal {
    print msg.sender;
  }
}

contract example3 is example2 {
  function C() {
    print msg.sender;
    B();
  }
}

If I call function A(), then A() will print my address, and C() will print contract example1's address. Then is B() will print contract example1's address or contract example2's address?


texts: Anyone knows what does this contract code mean?

texts:
Refer to the link below:

https://github.com/bokkypoobah/Tokens/blob/master/contracts/MyToken.sol

Line 62:

contract ApproveAndCallFallBack {
    function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}

And line 209:

ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);

If I understand correctly, line 209 is calling the default constructor of ApproveAndCallFallBack contract (which obviously does not exist), and call the receiveApproval() interface which is obviously not implemented here.

Anyone know how is this contract suppose to be used?


texts:
Is there a standard or a convention for URLs of Ethereum address?

That is I want clicking xxx://0x... to initiate transfer to this account.


texts: What is the numerical value of true and false? Presumably one is 0x0000000000000000 and one is 0x0000000000000001


texts: How does Ethereum verify an account exists if that account does not carried any transaction?

texts:
https://blog.ethereum.org/2015/11/15/merkling-in-ethereum/ :

  This allows for a highly advanced light client protocol that allows
  light clients to easily make and get verifiable answers to many kinds
  of queries: ...
  Does this account exist?

  The is handled by the state tree, but the way that it is
  computed is more complex. Here, we need to construct what can be
  called a Merkle state transition proof. Essentially, it is a proof
  which make the claim “if you run transaction T on the state with root
  S, the result will be a state with root S', with log L and output O”

When we start using geth or parity we can create unlimited number of accounts each having an unique address ex:'0xe427c111f968fe4ff6593a37454fdd9abf07c490'. As I understand if there is no transaction to this address, it will not show up on the state-tree.

[Q] If an account did not carried any transaction, hence it will now show up in the state tree. So how Ethereum could know that account actually exist which does now have any foot print on the state-tree?

[Q] In addition to that: hence each user can create unlimited number of accounts. If an user creates billions of accounts, and each will carry a non-stop transaction between each other. Does all account's information will be stored in the World-State? If yes, this may consume a lot of memory on the long run.

Thank you for your valuable time and help.


texts: How to calculate difficulty of genesis block?

texts: To calculate difficulty of a block we need the parent block timestamp and difficulty? As there doesn't exist a parent block so what values should we take for those?


texts:
I am currently reading an interesting book about solidity, and I'm reading about block creation. This gives a good overview:

The book mentions that the maximum size of a block is determined by the upper gas limit and block size.

I am a bit confused as for when a new block needs to be created.
In another example, they give an example in which the gas value does not even reach the gasUsed property of a block doesn't even come close to the gasLimit.

So in the example added, Sam wants to add $$ to Mark. But it isn't clear to me how it is decided that a new block needs to be created.
I mean, a block consists of multiple transactions, so why wouldn't this transaction just be appended to an already existing block?

Related, everywhere I read that a new block gets created by the miner who 'solves the puzzle' based on a changing nonce. So who creates this puzzle?
Also related, they mention the 'genesis' block, which is the first block in a blockchain, but there is no puzzle for this, so who creates the first block? And in a blockchain, how is it decided that we need a new genesis block? Is the ' Ethereum blockchain' therefore a combination of blockchains (each having their own genesis block)?

I know, quite a few questions...
If you prefer me to split up these questions, I will. But as they're closely related, I would have hoped that a single answer could clarify these questions at once.


texts:
I am trying to buy Ethereum and I live outside the US, Coinbase does not support my place!
Also, I'd like it to be simple, buying with PayPal or credit card, and not with Bank transfer such as Kraken


texts: Export Token Holders list of a token to csv

texts: I'm trying to do some distribution calculations on a couple of tokens and could use an export of the token holders list that I can find in Etherscan when I search for a specific token. Since Etherscan is showing the list I was hoping the API would have a function for this, but it looks to me like it doesn't. Please bear with me as I am totally new to this and am not able to really build anything. I know how to fiddle with some APIs and that's about it.


texts: ERC20 token transfer without private Key

texts:
On my node there is an account, which I know the address and password, but do not know privateKey.
This account has tokens ERC20 and ETH for gas.
How can I transfer tokens to another wallet?

The usual translation I do so:

var privateKey = new EthJS.Buffer.Buffer(senderPrivateKey, 'hex')
var txParams = {
    nonce:    web3.toHex(count),
      gasPrice: gasPriceHex,
    gasLimit: gasLimit,
      to: contractAddress,
    value:    '0x00',
    data:     contract.transferFrom.getData(senderAccount, recipientAccount, numberTokens),
      chainId: web3.toHex(1),
}
var tx=new EthJS.Tx(txParams);
tx.sign(privateKey),serializedTx=tx.serialize().toString('hex');
web3.eth.sendRawTransaction('0x'+serializedTx, function(err, hash) {
    if (!err)
        console.log(hash);
    else
        console.log(err);
});

I can do web3.personal.unlockAccount, but how do I sign a transaction without private Key?


texts: "Invalid JSON RPC response: undefined" when using web3.personal remotely

texts:
When executing my script files from a machine that needs to connect to a remote geth node, I get an "Invalid JSON RPC response: undefined" when using web3.personal.* functions.

In particular I have started geth in one workstation with the following parameters:

> geth --datadir /home/user/eth/ --networkid 123 --rpc --rpcapi "personal,web3,eth,net,db" --rpccorsdomain "*" console 2>>geth.log

Initially I tested the scripts by executing them locally, using the following HttpProvider:

  Web3.providers.HttpProvider("http://localhost:8545")

The scripts are executed as expected and all the web3.personal.* functions such as web3.personal.listAccounts and web3.personal.unlockAccount() work well.

However when I execute the exact same script from a remote workstation and thus replace localhost with the IP of the machine running geth I get the following error:

  Error: Invalid JSON RPC response: undefined

To be noted that I can execute other functions remotely, such as web3.version.api and web3.eth.contract(abiHEC), etc.
So the problem seems to be the web3.personal.*.

I am using web3 version 0.20.6 and geth 1.8.2.

Do you have any suggestions on how to solve this?

Could it be that this is a security feature not allowing the use of personal functions remotely?

If so, do you have any recommendation on how I can invoke a smart contract function remotely?
Thank you.


texts: Could my private key could be reconstructed from just the ciphertext, salt and my password

texts: Lets assume hypothetically that I have these all written down on paper somewhere.  In comparison to the keystore, which I consider a JSON file that's too long, can I theoretically disregard all other information with the exception of my salt, passphrase and ciphertext, in order to decrypt my private key...or is there another variable that I would need?


texts: How to get a message from web3.shh using Python

texts:
Good afternoon. I'm trying to implement the "Status" at the moment. I use the library Web3.shh. I sent the message and gives the answer "True", but I can not receive all the messages on the other address. In the documentation of the Ethereum and in the documentation "Status" I did not find any answers. Tell me how to correctly pull messages from the Geth at? Here's the code:

from web3 import shh
from web3 import HTTPProvider, Web3

status_host = 'https://host:port''
privatekey = '0x....7f2afa922ffdbeac65867f544a....'

connect = Web3(HTTPProvider(status_host))
print('connect status ===> ', connect.isConnected())

ms = shh.Shh(connect)
print('info ===>>>> ', ms.info)

id = ms.addPrivateKey(key=privatekey)
print('id ===>>>> ', id)

user_address = ms.getPublicKey(id)
print('user_address ===>>> ', user_address)

privkey = ms.getPrivateKey(id)
print("privkey => ", privkey)

topic = Web3.toHex(b'AS')
print("topic => ", topic)
text = 'test message'
address_to = '0x0487be55c072702a0e4da72158a7432281e8c26aca9501cd0bfeea726dc85f2611e96884e8fc4807c95c04c04af3387b83350a27cc18b96c37543e0f9a41ae47b5'

mes_send = ms.post(
    {
        'ttl': 20,
        'payload': Web3.toHex(text=text),
        'pubKey': address_to,
        'topic': topic,
        'powTarget': 2.5,
        'powTime': 2,
    }
)

if mes_send == True:
    print('Status message => Send')
else:
    print('Message not send')


texts: Unable to transfer token from one personal account to another

texts:
I have created two personal account on private blockchain with geth.
This is the balance of one account

web3.fromWei(eth.getBalance(eth.accounts[0]), "ether");

100000000000

And this is of the second one

 web3.fromWei(eth.getBalance(eth.accounts[1]), "ether");
0

I unlocked first account

personal.unlockAccount(eth.accounts[0])
Unlock account 0x942282c0793fb08dea160c74ac45b5d4f2d03192
Passphrase:
true

When i try to send transaction or transfer from one to another, it executes successfully

eth.sendTransaction({from: '0x942282c0793Fb08dEA160C74AC45B5D4F2D03192',to: '0x7258CB67ccBCF4AC755e5D7F0891e9415B683129',value: '1000000000'})
INFO [02-19|10:45:22.065] Submitted transaction                    fullhash=0xf6e573bcd1eb92d70b06cfa80e04604f0a83a49d0c75786afc04062ebb975af1 recipient=0x7258CB67ccBCF4AC755e5D7F0891e9415B683129
"0xf6e573bcd1eb92d70b06cfa80e04604f0a83a49d0c75786afc04062ebb975af1"
> INFO [02-19|10:45:24.616] Commit new mining work                   number=1 sealhash=24efa9…31b496 uncles=0 txs=9 gas=189000 fees=0.000189 elapsed=179.547ms

But changes are not reflected when i again check balance accounts.

This is the genesis.json that i have used for blockchain setup.

{
 "config": {
   "chainID": 1234,
   "homesteadBlock": 0,
   "eip155Block": 0,
   "eip158Block": 0
 },
 "alloc": {
    "0x942282c0793fb08dea160c74ac45b5d4f2d03192": {
      "balance": "100000000000000000000000000000"
    }
 },
 "difficulty": "0x4000",
 "gasLimit": "0xffffffff",
 "nonce": "0x0000000000000000",
 "coinbase": "0x0000000000000000000000000000000000000000",
 "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
 "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
 "extraData": "0x123458db4e347b1234537c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
 "timestamp": "0x00"
}


texts: How can I efficiently get a large amount of data from a contract?

texts:
I have a contract that will store a lot of data.  Offline solutions really don't apply to the problem I'm trying to solve, short of caching (but then I have a cache invalidation problem I'd have to solve too).

I only need to update small amounts of data at a time, so that fits easily under maxGas because of the "gas charge only on changing to non-zero value" feature of the EVM, but I need to be able to read a large amount of data at a time, and I'm having problems with that.

When I try to read a large amount via a solidity ABI, I get an out of gas error in the geth logfile (but nothing programmatically from web3.js call() which doesn't even take a gas argument), and I just get all zeros from web3.js despite the fact that I've modified a memory location.

Will web3.eth.getStorageAt work more efficiently or will it also run out of gas?  If this method works better than invoking the EVM, and I'm using fixed arrays, how do I find the address of the data?  Is there an alternative solution that minimizes overhead on the Ethereum node I'm talking to?

example code:

uint8 [10][10][100][100] public blocks;
// this quietly runs out of gas even in a call()
function getBlocks() returns (uint8[10][10][100][100]) {
        return blocks;
    }
}


texts: Event emits multiple times on a solidity function call

texts:
I need have a problem, when I execute a solidity function, event emits multiple times, but when I refresh page then it works normally and only past events get called.

Here is my code:

  addEventListenerOrderSent(component) {

if (typeof this.state.contractInstance !== 'undefined') {
  try{
    this.state.contractInstance.events.OrderSent({
      filter: {buyerAddr: [this.state.account]},
      fromBlock: 0,
      toBlock: 'latest'
      }/* , function(error, event){ console.log(event);} */)
    .on('data', function(event){
        var epochValue = event.returnValues.dateOfOrder;
        var d = moment.unix(epochValue).utc(); // The 0 there is the key, which sets the date to the epoch
        event.returnValues.dateOfOrder = d.local().format('DD-MM-YYYY h:mm:ss');

        var web3 = new Web3();
        event.returnValues.itemName = web3.utils.hexToAscii(event.returnValues.itemName);

        var newArray = component.state.orders.slice();
        newArray.push(event.returnValues);
        component.setState({ orders: newArray });

    })
    .on('error', console.error);

  } catch (e) {
  // Send error to Error reporting service in
  // production/staging stage or log to console in dev.
  console.error(e);
  }
}

}

When I call solidity function Order, event emits and for some reason event emits multiple times in my table:

And after I call refresh, only one event stays in the table as it should.

What am I doing wrong?


texts: delete an element from mapping of address to struct array

texts:
I have the following struct and mapping.

struct consumeID{
    address consumerGatewayID;
    string serviceConsumerID;
}
mapping(address=>consumeID[]) public pendingAccessRequests;

I want to add and delete elements from the mapping.

For adding elements i tried something like this:

pendingAccessRequests[_producerGatewayID].push(consumeID(_consumerGatewayID, _serviceConsumerID));

Can anyone help me with logic to delete elementsfrom that mapping?


texts: How can I get contract public values with nethereum as the wallet does?

texts:
I'm fiddling around with this tutorial.

After deploying and setting up the contract within the page, I created a proposal from the ethereum wallet which I could see after a few blocks. The read from contracts part shows all proposals, available by their number. This implies that the proposals are available readily somewhere but I want to know how to geth them via nethereum.

I have the contract ready as below.

contract = web3.Eth.GetContract(abi, contractAddress);

How can I get the data?


texts:
I am running a testnet on Ganache UI. But when I deploy a contract and close and reopen ganache, there are no blocks and the contract deployment is gone. Is it possible to save/load a blockchain through ganache UI?

I know how to save a blockchain in ganache-cli. But ganache-cli and ganache UI seem to be different and I can't connect them to each other.

I would like to save my blockchain within ganache UI.


texts: How much effort would it be to migrate a Dapp written in embark to truffle or vice-versa? Which parts of the code can be preseved (would work in both frameworks)?


texts: How exactly does Oraclize works under the hood?

texts:
The following is what the  Ethereum documentation of Oraclize says:

  Firstly, in the most common case, a transaction executing a function
  of a smart contract is broadcasted by an user. The function contains a
  special instruction which manifest to Oraclize, who is constantly
  monitoring the Ethereum blockchain for such instruction, a request for
  data.

  Secondly, according to the parameters of such request, Oraclize will
  fetch or compute a result, build, sign and broadcast the transaction
  carrying the result. In the default configuration, such transaction
  will execute the __callback function which should be placed in the
  smart contract by its developer: for this reason, this transaction is
  referred in the documentation as the Oraclize callback transaction.

What kind of instruction is executed? What messages are passed around when calling the oraclize_query function?

Is the "special" instruction and oraclize_query the same thing? As far as I understand, oraclize_query is the request for data, right?

The other answers, don't address what the "special" instruction is, etc.


texts:
When I'm going through best practices of smart contract I came across https://consensys.github.io/smart-contract-best-practices/general_philosophy/ this site. They have mentioned

    Understand that your public functions are public, and may be called maliciously.
Your private data is also viewable by anyone.

My doubt is without knowing abi or the contract address how come one know my function name?


texts: Signing message: Provided address is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can't be converted

texts:
Provided address is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can't be converted is not a dupe, this is about signing messages

My code:

const msgParams = [{
        type: 'string', name: 'Message', value: 'Hi, Alice!'
     },{   type: 'uint32', name: 'A number', value: '1337'
      }];
      let from = Merchant.accounts[0];
      console.log(window.provider);
      let p = window.provider;
      console.log(Object.keys(window.web3));

      window.web3.eth.sign(from, msgParams, function(err, res) {
        console.log(err);
        console.log(res);
      });

(window.provider is the current provider.. window.web3 loses its current provider, see my other question window.web3.currentProvider is null for details)

Running this I get the error in the title

Metamask prompted to sign.. once. Now the prompt won't show. The signing prompt did have the Alice, 1337 data in it.

How do I sign a message with Metamask to get the encrypted string of that signed message?

EDIT: Merchant is my utility class for Metamask. The logged output of Merchant.accounts[0] is

0x2e290a50d3193753f156e5b0b12e4231bd568526

EDIT 2: I have tried this:

web3.eth.getAccounts(function(a,b) {
      Merchant.accounts = b;
      // alert("Saving accounts" + Merchant.accounts);
      console.log("Merchant accounts: " + Merchant.accounts);
      let x = web3.eth.getBalance;
      console.log(x);
    });

 toChecksumAddress (address) {
    address = address.toLowerCase().replace('0x', '')
    var hash = createKeccakHash('keccak256').update(address).digest('hex')
    var ret = '0x'

    for (var i = 0; i < address.length; i++) {
      if (parseInt(hash[i], 16) >= 8) {
        ret += address[i].toUpperCase()
      } else {
        ret += address[i]
      }
    }

    return ret
  }

reloadKeys() {
        const msgParams = [{
        type: 'string', name: 'Message', value: 'Hi, Alice!'
     },{   type: 'uint32', name: 'A number', value: '1337'
      }];
      // Merchant.accounts[0]
      // let addr = 0x2E290A50d3193753F156e5b0b12e4231Bd568526;
      let from = this.toChecksumAddress(Merchant.accounts[0]);

      // window.web3.utils.toChecksumAddress();
      console.log(typeof(from));
      console.log(from);

      console.log(Object.keys(window.web3));

      window.web3.eth.sign(from, msgParams, function(err, res) {
        console.log(err);
        console.log(res);
      });

I still get this error.


texts:
I still can't transfer my Eth's from Ether.li to another account.

  “Please fund your user account with sufficient ether (~0.01 ETH / tx) for gas (transaction fees)“

That's what the site tells me to do and after i tried to transfer it like that, but then it tells me "must specify a amount).

I would be very happy if someone can help me, and i'm ready to pay the one out.


texts: convert type address into address payable

texts:
Trying to convert the type address to address payable. My solidity compiler version is 0.8.4
    function toPayable(address account)
        internal
        pure
        returns (address payable)
    {
        address payable acc = address(uint160(account)); // <= error here
        return acc;
    }


texts: Contract reading a string returned by another contract

texts:
I have 2 contracts, Parents and Child which has a  public string variable - name.

contract Child {
    string public name;
    function child (string _name){
       name = _name;
    }
}

Parents needs to get that name:

contract Parents {
    string public childName;
    Child child;
    function Parents(address _childAddress){
        child = Child(_childAddress);
        childName = child.name();  // I also tried child.name
    }
}

But I'm getting the following error:

Error: Type tuple() is not implicitly convertible to expected type string storage ref.
        childName = child.name();

So I've tried to create another function in Child that will return a string:

function getName() returns (string name) {
    return name;
}

And in Parents I've changed

childName = child.name();  into--->  childName = child.getName();

But I keep getting the same error. Any ideas?
As always, your help is appreciated.


texts: Not able to connect Tessera with Quorum node

texts:
I am following up with the Quorum set up as mentioned @ https://docs.goquorum.com/en/latest/Getting%20Started/Creating-A-Network-From-Scratch/#tessera
I have created 3 Quorum nodes with RAFT consensus. Now I am trying to install the Privacy manager Tessera with them. I am able to generate the pub and private keys and run them successfully. However attaching the Tessera with quorum node is failing with the below error.

panic: MustNew: Failed to connect to Constellation (./new-node-1t/tm.ipc): Constellation Node API did not respond to upcheck request

goroutine 1 [running]:
github.com/ethereum/go-ethereum/private/constellation.MustNew(0xc00003600f, 0x14, 0xc00003600f)
    /home/srikant/Desktop/quorum-master/build/_workspace/src/github.com/ethereum/go-ethereum/private/constellation/constellation.go:108 +0x190
github.com/ethereum/go-ethereum/private.FromEnvironmentOrNil(0x118e95e, 0xe, 0xc000225f48, 0x9ed863)
    /home/srikant/Desktop/quorum-master/build/_workspace/src/github.com/ethereum/go-ethereum/private/private.go:20 +0x64
github.com/ethereum/go-ethereum/private.init.ializers()
    /home/srikant/Desktop/quorum-master/build/_workspace/src/github.com/ethereum/go-ethereum/private/private.go:23 +0x36

Here is a snippet form my config,json file from Tessera.

{  "useWhiteList": true,
   "jdbc": {
       "username": "sa",
       "password": "",
       "url": "jdbc:h2:/home/srikant/Desktop/fromscratch/new-node-1t/db1;MODE=Oracle;TRACE_LEVEL_SYSTEM_OUT=0",
       "autoCreateTables": true
   },
   "serverConfigs":[
       {
           "app":"ThirdParty",
           "enabled": true,
           "serverAddress": "http://localhost:9081",
           "communicationType" : "REST"
       },
       {
           "app":"Q2T",
           "enabled": true,
            "serverAddress":"unix:/home/srikant/Desktop/fromscratch/new-node-1t/tm.ipc",
           "communicationType" : "REST"
       },
       {
           "app":"P2P",
           "enabled": true,
           "serverAddress":"http://localhost:9001",
           "sslConfig": {
               "tls": "OFF"
           },
           "communicationType" : "REST"
       }
   ],
   "peer": [
       {
           "url": "http://localhost:9001"
       },
       {
           "url": "http://localhost:9003"
       },
       {
           "url": "http://localhost:9005"
       }
   ],
   "keys": {
       "passwords": [],
       "keyData": [
           {
               "privateKeyPath": "/home/srikant/Desktop/fromscratch/new-node-1t/new-node-1.key",
               "publicKeyPath": "/home/srikant/Desktop/fromscratch/new-node-1t/new-node-1.pub"
           }
       ]
   },
   "alwaysSendTo": []
}

The Path of tm.ipc file in the reference is correct. However its failing with the following command.

PRIVATE_CONFIG=./new-node-1t/tm.ipc nohup geth --datadir new-node-1 --nodiscover --verbosity 5 --networkid 31337 --raft --raftport 50000 --rpc --rpcaddr 0.0.0.0 --rpcport 22000 --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3,quorum,raft --emitcheckpoints --port 21000

Can anyone please help me out.


texts: Is there any way to create contract by binary data?

texts:
In solidity, if we have defined contracts already, its simple to create an contract in contract by using the keyword: new, like this:

contract FatherContract {
    function createChild() public {
        new ChildContract();
    }
}

contract ChildContract {
    constructor() public {
        //...
    }
}

but what if I want to create an contract from binary data, like this:

contract FatherContract {
    function createChild(bytes contractDataInfo) public {
        // any way to create a new contract in this method
        // using contractDataInfo?
    }
}

If the contractDataInfo is contract creation info, any way to create a new contract in method createChild?


texts: Why was Frontier's "default" gasLimit = 3141592?

texts:
I've noticed this number at least in two places:

On the Ethereum Network Status web page.

In the sources of pyethereum.

The number looks suspiciously familiar, and I keep asking myself:
"Where have I seen it before?" and "What exactly is this number?"


texts: Do gas refunds apply in a fallback function? What is the limit for non matching function identifiers?

texts:
I know that a fallback function called with a .transfer only has gas limit of 2300. What happens if the fallback function deletes some storage variables in the fallback function? Would the fallback function be able to use more than the 2300 gas limit because some gas is being refunded? Let's say it sets one variable to 0, which the gas refund is 10000. Then would the fallback function have gas limit of 12300? I.e. be able to set 2 variables each action having a cost of 5000 gas?
Also, I've read that .transfer, .send will have a limit of 2300 gas and call.value will transfer gas from the transaction. But what about a non matching function? According to the docs a non matching function identifier will trigger the fallback function. So what happens if someone calls my contract with "thisMethodDoesntExist()", would the fallback have a limit of 2300?


texts: How do I add to a mapping that maps (address => bool)?

texts:
This is just part of my contract, but shows where I create the mapping, the modifier onlyMember, and the function addMember.  Basically, I want to be able to add new members who can execute onlyMember functions, as I - the owner - can.
 I was able to add a new member, as the owner, but when I switched to the member address and tried to execute other functions that appear later in the contract (which have the modifier onlyMember attached to them), I get an error.  I am wondering if I set up the addMember function incorrectly, but remix isn't giving me any errors about it.

// <------------------------- MEMBERS ------------------------->

address owner = msg.sender;
bool ifmember;
mapping(address => bool) members;

modifier onlyMember {
    require(msg.sender == owner || members[msg.sender] == true);
    _;
    }

function addMember(address _address) public onlyMember {
    ifmember = members[_address];
    }

// <----------------------- END MEMBERS ----------------------->


texts:
There is so much information out there that turns around this point that I decided to make a post, can someone please help out?

Does that sound correct as a work-flow for medium/large size projects ?:

Use Mix IDE (can I use it with geth?) or ethercamp Ethereum Studios to write and test the contracts.
Use Meteor and Webstorm(or some other javascript IDE) to Build the platform, eventually using place-holder javascript variables until the contracts are ready.
Move the contracts over to the meteor file structure and add the tested functions to the relevant javascript files.
Does truffle fit in somewhere in that picture or will it just create noise since there will already be the Meteor framework?

Thanks!


texts:
Can we use web3.py with Truffle framework ?
If yes, please share such integration examples


texts:
Why is it necessary to manually add a token you will transact in (before the actual transaction) in Metamask? What happens if someone doesn't do that before a transaction, to display that balance in Metamask?
Thanks.


texts: How are transactions with the same gas price ordered in a block?

texts:
If A has gas_price == 1gwei and B has gas_price == 1gwei, how does the miner decide which tx gets executed first when ordering them into a produced block?
Does it depend what mining client is  used? How do the popular clients differ?


texts: How can I create a different address and publickey for same private key in ethereumj?

texts:
If i follow the steps mentioned in How to create an account in ethereumj.

It creates new account every time with different private key/address/public key. I would like to create different address/public key for same password every time.


texts: Until when can I safely broadcast transactions before homestead?

texts: I would like to broadcast a transaction. When should I "hold" and let the homestead release happen? Until when can I send transactions?


texts: Can Anyone guide me on how to get the tether(usdt) test token on ethereum in ropsten test network


texts:
Etherscan shows an ERC-20 contract and this many tokens:
000000000000000000000000000000000000000000000000000000070c96a0ea

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

How do I convert that to a number I can understand?  I can use easily C#, Python, Javascript or is there some type of web converter?


texts: Error parsing openzeppelin. Expected pragma, import directive or contract/interface/library definition

texts:
None of the solutions that I saw solved this issue. When I do truffle compile I get this error

Error parsing @openzeppelin/contracts/GSN/Context.sol:
ParsedContract.sol:15:1: ParserError: Expected pragma, import
directive or contract/interface/library definition. abstract contract
Context { ^------^

Should I be looking somewhere else? or do I have to install something?
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";


texts: How to do private transactions in POA network with geth client like in besu?

texts:
In Hyperledger Besu you can create a private transactions between nodes maintaing privacy.
How can I do similar transaction between my geth client in POA network


texts: How to show token balance from a ETH address in my Android App?

texts:
I have an Android App and I want to show the balance of an especific token of the user wallet Address

IE: show how many CHAINLINK are holding the user on his wallet

Thanks in advance


texts: web3 - Can I call a library function without a contract?

texts: I have a library which contains a function concat - it can merge two bytes. I have deployed a contract which uses that library and it works. I would like to make a simple bytes builder on my website. Do I need to deploy a special contract BytesBuilder or can I simply call the already deployed library and call lib.concat somehow?


texts: How to delete or bug fix smart contracts

texts: If I plan to have a develop on DApp, how can I retain control over it. Either for doing further enhancements or bug fixes. Can I able to delete any abandoned contracts?


texts:
--- HEAVILY EDITED ---

Solidity contract:

pragma solidity ^0.4.24;

contract PatientRecords {

struct Patient {
    string ID;
    string weight;
    string height;
    string diseasehistory;
    string vaccinecard;
    string name;
    address registrantAddress;
}

uint ID;

constructor() public {
    ID = 0;

}

Patient[] public patients;
mapping(string => uint) names;

function register(string _id, string _weight, string _height, string _diseasehistory, string _vaccinecard, string _name) public returns (bool, uint){
    for (uint i = 0; i < patients.length; i++) {
         require (stringsEqual(patients[i].ID, _id) == false);
    }
  names[_name] = ID;
  ID++;
   patients.push(Patient(_id, _weight, _height, _diseasehistory, _vaccinecard, _name,  msg.sender));
   return (true, ID);
}

function verifyByName(string _name) public view returns(string, string, string, string, string, string) {
   uint n;
   n = names[_name];
   return (
        patients[n].name,
        patients[n].ID,
        patients[n].weight,
        patients[n].height,
        patients[n].diseasehistory,
        patients[n].vaccinecard);
}

function stringsEqual(string storage _a, string memory _b) internal pure returns(bool) {
    bytes storage a = bytes(_a);
    bytes memory b = bytes(_b);
    if (keccak256(a) != keccak256(b)) {
        return false;
    }
    return true;
}

}

HTML input bar & button code:

<input id="name" type="text">
<button id="button2">Search</button>

What I need:

The user inputs a value on the HTML
User clicks a button
Value is passed as a parameter onto a "view" function on the contract
HTML displays whatever the contract returns

So, with the code above, how can I achieve those 4 points?

Thank you.


texts:
I am trying to send Ethers to a contract deployed on Ganache but I am getting  VM Exception while processing transaction: revert, the same logic is able to transfer Ethers to other account.

Following are error log and the code for sending Ether

Code:
Fallback method:

function() public payable {
    transfer(msg.sender, msg.value);
}

Transfer logic:

/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
    require(_value <= balances[msg.sender]);
    require(_to != address(0));

    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    emit Transfer(msg.sender, _to, _value);
    return true;
}

Error:

Error: Returned error: VM Exception while processing transaction: revert
    at Object.ErrorResponse (errors.js:29)
    at index.js:140
    at XMLHttpRequest.request.onreadystatechange (index.js:79)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request-event-target.js.XMLHttpRequestEventTarget.dispatchEvent (xml-http-request-event-target.js:34)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request.js.XMLHttpRequest._setReadyState (xml-http-request.js:208)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request.js.XMLHttpRequest._onHttpResponseEnd (xml-http-request.js:318)
    at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.<anonymous> (xml-http-request.js:289)
    at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.push../node_modules/events/events.js.EventEmitter.emit (events.js:96)
    at endReadableNT (_stream_readable.js:1010)
    at afterTickTwo (index.js:27)
    at Object.ErrorResponse (errors.js:29)
    at index.js:140
    at XMLHttpRequest.request.onreadystatechange (index.js:79)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request-event-target.js.XMLHttpRequestEventTarget.dispatchEvent (xml-http-request-event-target.js:34)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request.js.XMLHttpRequest._setReadyState (xml-http-request.js:208)
    at XMLHttpRequest.push../node_modules/xhr2-cookies/dist/xml-http-request.js.XMLHttpRequest._onHttpResponseEnd (xml-http-request.js:318)
    at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.<anonymous> (xml-http-request.js:289)
    at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.push../node_modules/events/events.js.EventEmitter.emit (events.js:96)
    at endReadableNT (_stream_readable.js:1010)
    at afterTickTwo (index.js:27)
    at resolvePromise (zone.js:814)
    at zone.js:724
    at index.js:72
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3815)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:496)
    at ZoneTask.invoke (zone.js:485)
    at timer (zone.js:2054)


texts: Why blocks are not including queued transactions in this private chain

texts:
I have started two nodes with same genesis.json on same machine in a same directory. I followed the following steps:

./geth --datadir ./chaindata/ --port 30303 --networkid 15525 --rpc --rpcport 8545--rpcaddr 0.0.0.0 --rpccorsdomain "*" --rpcapi "web3,eth,personal,net" console

and then the second node (ran this command on same machine in same directory):

 ./geth --datadir ./chaindata2/ --port 30304 --networkid 15525 --rpc --rpcport 8546 --rpcaddr 0.0.0.0 --rpccorsdomain "*" --rpcapi "web3,eth,personal,net" console

PLESE NOTE THAT THE PORT, RPC PORT , AND DATA DIRECTORY ARE DIFFERENT IN THE TWO

Then, found the node id of the second one by admin.nodeInfo and added it as a peer in the other console with admin.addpeer

admin.addPeer("enode://f583bdf4e0e56818b920041a0588ba415352fa155935f04fbe287f2e2d111047a2f7e7b15c156d160b2afbbdde46081cf6aa6a73dbdbefddb99a8ebb01e03de3@127.0.0.1:30303")

Now Unlocked an account (with pre-allocated balance) and sent transaction:

eth.sendTransaction({from:"39408873c54f3d8efe67c43532ac3b3b5db7fb7f", to: "11f53eb1649af91da0af06d84700a33919febe9e",value: "250",gasPrice:20 , gas: 21000, nonce: 150 )});

But txpool.status shows the following:

{
  pending: 0,
  queued: 5
}

And when I call the eth.getTransaction("0x5aded5..."), The block number field is null.

Also txpool.status on the second node shows

{
      pending: 0,
      queued: 0
    }

However the blocks are succesfully synchronized, and the mining is successfully done.
For Information :
Here is my genesis.json

{
   "config": {
      "chainId": 1994,
      "homesteadBlock": 0,
      "eip155Block": 0,
      "eip158Block": 0,
      "byzantiumBlock": 0
   },
   "difficulty": "4",   // PLEASE NOTE !!!
   "gasLimit": "2000000",
   "alloc": {
      "39408873c54f5b8efe67c4353d4c3b3b5db7fb7f": {
          "balance": "100000000000000000000000"
      },
      "ae13d41d66af2d380c7af6d825ab557eb271ffff": {
          "balance": "120000000000000000000000"
      }
   }
}


texts: Why would push in solidity only push once?

texts:
I have the code which follows. It adds the hashes into contracts fine but the my myHashes array gets just one value at 0. Is there any reason why this push would fail?

pragma solidity ^0.4.18;

contract RegisterContract {

    uint public contractWeight;

    mapping(bytes32=>string) public contracts;
    bytes32[] public myHashes;

    function addContract ( string jsonInput, bytes32 hashKey) public {
        contracts[hashKey] = jsonInput;
        myHashes.push(hashKey);
     }

    function addWeight (uint weight) public {
        contractWeight = weight;
    }

    function () payable public {
    }
}


texts:
I am using Infura with the mainnet and web3py to interact with smart contracts and send transactions. Last week this same code worked fine, but today, trying to send the transaction for the deployment of the contract, I get this error message, on the waitForTransactionReceipt method:

File "pruebaPagos.py", line 303, in <module>
tempsensorContract, w3, nonce = construirContrato()
File "pruebaPagos.py", line 139, in construirContrato
tx_receipt = w3.eth.waitForTransactionReceipt(tx)
File "/root/Proyectos/bchain/rafa-py3/local/lib/python3.5/site-packages/web3/eth.py", line 223, in waitForTransactionReceipt
return wait_for_transaction_receipt(self.web3, transaction_hash, timeout)
File "/root/Proyectos/bchain/rafa-py3/local/lib/python3.5/site-packages/web3/utils/transactions.py", line 70, in wait_for_transaction_receipt
_timeout.sleep(poll_latency)
File "/root/Proyectos/bchain/rafa-py3/local/lib/python3.5/site-packages/web3/utils/threads.py", line 68, in sleep
self.check()
File "/root/Proyectos/bchain/rafa-py3/local/lib/python3.5/site-packages/web3/utils/threads.py", line 61, in check
raise self
web3.utils.threads.Timeout: 120 seconds

Below is my Python code that uses web3 for the deployment of the contract. I've tried to put different gas prices, but it doesn't work either. Anyone knows what is going on here? Is this an Infura problem?

contract_source_code = '''
   #my solidity source code
'''

compiled_sol = compile_source(contract_source_code)
contract_interface = compiled_sol['<stdin>:tempSensor']

#connection to infura
w3 = Web3(HTTPProvider('https://mainnet.infura.io/MY-API-KEY'))

from web3.middleware import geth_poa_middleware

w3.middleware_stack.inject(geth_poa_middleware, layer=0)

count =  w3.eth.getTransactionCount(account,"pending")

gasPrice = w3.toWei('3.5','gwei')

#creating the contract and its transaction for the deployment
TempSensor = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
transaction = TempSensor.constructor().buildTransaction({
        'gas': w3.toHex(850000),
        'gasPrice': w3.toHex(gasPrice),
        'nonce': w3.toHex(count),
    })

#sign the transaction and send
key = 'PRIVATE-KEY'
signed = w3.eth.account.signTransaction(transaction, key)
tx = w3.eth.sendRawTransaction(Web3.toHex(signed.rawTransaction))
print('Transaction for the deployment:')
print(Web3.toHex(tx))

tx_receipt = w3.eth.waitForTransactionReceipt(tx)

tempsensorContract = w3.eth.contract(
    address = tx_receipt.contractAddress,
    abi = contract_interface['abi'],
)

In etherscan.io it can't even find my transaction hash. It says:

Sorry, we are unable to locate this Transaction Hash


texts: Problem in contract verification through EtherScan API

texts:
Contract source verification through these APIs is putting it 'pending in queue' and not getting confirmed.

This interface is also behaving same.

I tried it with rinkeby and kovan.

Here it works fine.


texts: Error: invalid arrayify value when deploying in remix

texts:
I got this strange error when deploying a contract in remix. Here is the constructor
uint256 private value;
bytes32 private itemName;  //<<==cause error
uint256 private itemId;

constructor (uint256 _value, bytes32 _itemName, uint256 _itemId, address _dudes, address _erc20)

Here is the error:
creation of EscrowTrade1000 errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="1234", code=INVALID_ARGUMENT, version=bytes/5.0.5

Here is the deploying value for the constructor:

Tried to enter different values for _ITEMNAME and the error is the same. What's wrong with the data here?


texts:
I have a function in a contract to retrieve ETH balance for a given address, which is:

function getEthBalance(address _addr) constant public returns(uint) {
      return _addr.balance;
}

Is there a way to retrieve token balance of the contract for a given address, just like the function above?

EDIT:
Let's suppose the contract issues a token named TKN, and I have 10 TKN in my ETH address, is there a way to retrieve the balance of those 10 TKN in my address with a function? Something like:

function getTKNBalance(address _addr) constant public returns(uint) {
      return _addr.TKN.balance;
}


texts:
When sending funds (Ether) from my main wallet, I entered my own address and sent them to myself. This created a contract with my funds. Is there any way to recover the funds?
Thanks.


texts: mist or wallet for macos can't connect to private-net

texts:
mist or wallet for macos(version 0.11.1) can't connect to private-net.

using command: ./Ethereum\ Wallet --rpc http://localhost:8545

but mist or wallet (version 0.9.3) works.  why？ tks！


texts: Bloom Filters - is the blockchain filtered block by block?

texts:
I understand that bloom filters are used to quickly scan for log topics and corresponding contract addresses. I also understand that an 2048-bit bloom filter is stored in the block header.

Question: If I have a filter looking for a specific log topic value from block 0 to the latest block: how does the node search for this? Will it iterate over the bloom filters block by block starting by block 0? Or, is there a hierarchy of bloom filters (mipmaps?) so that multiple blocks can be filtered at once? Bonus for pointing to geth code location where this is implemented.


texts: Price feed of multiple coins in a single GET request

texts:
I have used Chainlink oracle to get the price feed of a single coin. But I want to fetch the latest price of 100s of coins from the smart contract using oracle. Is it possible to get the price of multiple coins in a single GET request? If not, what is the best way to deal with it?
(Surely one request/coin costs a lot of gas and transaction time)


texts:
I am trying to implement the contract below in REMIX.

If I try to pass parameters to appendTags as "tag1", I get an error as Error:

  invalid bytes32 value (arg="", type="string", value="tag1")

How can I pass parameters to the function appendTags in REMIX ?

contract Post{

struct tags{
bytes32[] tagged;
}

mapping(address => tags) adminTags;

function appendTags(address addrs, bytes32 tag) public {
 adminTags[addrs].tagged.push(tag);
}

function getTagsofAdmin(address addrs) public view returns(bytes32[]){
return adminTags[addrs].tagged;
}

}