texts:
I'm trying to start geth node to perform queries about blockchain state.
The command that worked for me year ago as follows:
geth --rpc --rpcapi="db,eth,net,web3,personal,web3" --rpcaddr "localhost" --rpcport "8545"

However geth node refuses to init one of namespaces like this:
ERROR[08-15|15:50:04.923] Unavailable modules in HTTP API list     unavailable=[db] available="[admin debug web3 eth txpool personal ethash miner net]"

I'd be ok without it, however this doc clearly says that db namespace is needed to make use of getBalance which is essential part of targeted thing.
My geth version is 1.9.19-stable-3e064192 & windows if that matters.
What should I try further to get this going or maybe db namespace is no longer required for balance queries?


texts: Is there a way to get the hash of a transaction from a contract?

texts:
I've found that tx.hash is not defined in contracts, is there a way to get or calculate the hash of the tx ? And if not, What is the reason for that?

Is there a pattern to store information about a specific tx ?
Thanks


texts: personal_sendTranaction for token tranfer return hash but transaction isn't found in the blockchain

texts:
I am using Geth as a provider to the blockchain. I perform JSON-RPC method send_Transaction to transfer tokens, it returns me hash of the transaction but I can't see this transaction in the Etherscan.
When I call method eth_getTransactionByHash, it return result: "blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000","blockNumber":null. Geth logs don't show any errors.

Transaction with same parameters are succesufully sent before.
When I try to send similar transaction into Ropsten blockchain, all do succesfull.


texts: How to login with web3 without MetaMask?

texts: Is it possible to sign a user in web3 without MetaMask? I am trying to execute a smart contract I created and I'm using Infura to connect to the Kovan test network, but web3.eth.accounts[0] is undefined. How can I sign a user in without having to use MetaMask? Is this even possible? If not, how should I approach this problem? Please and thank you!


texts: What is the best way to test calling a contract's function from another contract?

texts:
I'm playing around w/ Gnosis' MultiSigWallet and noticed in their replaceOwner function it has a modifier that requires msg.sender to be the MultiSigWallet contract itself:

modifier onlyWallet() {
    require(msg.sender == address(this));
    _;
}

In Truffle console, how would I go about testing this and calling the replaceOwner function from the MultiSigWallet's address? I.e., if I try something like this:

wallet.replaceOwner('owner_address','newOwner_address', {from: 'multisigwallet_address'})

I'll get an Error: sender account not recognized

Is there a way within Truffle's console to make calls from contract addresses or is it only possible to make calls from the user addresses?

This post is related and I understand how this works, but I'm more curious to see if we can do this easily w/in Truffle for expedient testing purposes.


texts: How to loop through mapping in solidity?

texts:
I have a mapping in my contract like below:

  mapping (address => uint) public voterCount;

To calculate the total votes, I would like to loop through the mapping and sum the uint values. How do I do this in solidity? One solution is to use another variable say totalVotes that is incremented every time voterCount is updated. I am trying to see if there is a cleaner solution where I don't need an additional variable to keep track of the count.


texts: Deploying a contract from a multisig wallet

texts: I created a multisig wallet using Mist, but don't know how to deploy a contract from the wallet address. Is it even possible? If so, how to do this?


texts: sending transaction from contract to contract in web3

texts:
I have created an ERC223 token contract. now I am testing my contract using web3.
I can transfer tokens from an externally owned account to a contract receiver. also I can check the balance of the receiver using its address.
but when I'm trying to transfer tokens from that receiver contract to another address I get such error:

 Error: Returned error: sender account not recognized

I cannot understan the cause as the receiver contract can call the token contract but cannot send transaction to it.


texts: How do I pass a function pointer to a contract method from a unit test?

texts:
I'm getting this error:

Error: invalid type (arg="type", value="function")

when trying to call this method on the contract IntOption:

function create(
    address target,
    string memory name,
    int initialValue,
    function (address, string memory, int) external view validate
) public {

from my unit test. I'm trying to pass this function defined in Config4AccessControl as argument for validate:

function anyValue(address, string memory, int value) public pure {
    // any value is ok
}

This is the unit test:

it("should not be defined after it's created", async () => {
    const intOptions = await IntOption.new();
    const ac = await Config4AccessControl.new();
    await intOptions.create(addr1, 'foo', 1, ac.anyValue.address);


texts: Access multiple return values (a, b, c) from solidity function in web3js

texts:
I have a function that returns multiple values. I wish to access these from Web3js.

function testReturnBet(uint index) constant returns (address player,
                                                     uint tokensPlaced,
                                                     uint8[4] numbers,
                                                     uint ratioIndex,
                                                     uint timestamp,
                                                     uint rollIndex,
                                                     uint winAmount) {
        bet outBet = bets[index];
        return (outBet.player,
                outBet.tokensPlaced,
                outBet.numbers,
                outBet.ratioIndex,
                outBet.timestamp,
                outBet.rollIndex,
                outBet.winAmount);
    }


texts:
This contract is straight from the solidity docs. But am failing to deploy this:
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract Owned {
    constructor() { owner = payable(msg.sender); }
    address payable owner;
}

// Use `is` to derive from another contract. Derived
// contracts can access all non-private members including
// internal functions and state variables. These cannot be
// accessed externally via `this`, though.
contract Destructible is Owned {
    // The keyword `virtual` means that the function can change
    // its behaviour in derived classes ("overriding").
    function destroy() virtual public {
        if (msg.sender == owner) selfdestruct(owner);
    }
}

// These abstract contracts are only provided to make the
// interface known to the compiler. Note the function
// without body. If a contract does not implement all
// functions it can only be used as an interface.
abstract contract Config {
    function lookup(uint id) public virtual returns (address adr);
}

abstract contract NameReg {
    function register(bytes32 name) public virtual;
    function unregister() public virtual;
}

// Multiple inheritance is possible. Note that `owned` is
// also a base class of `Destructible`, yet there is only a single
// instance of `owned` (as for virtual inheritance in C++).
contract Named is Owned, Destructible {
    constructor(bytes32 name) {
        Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);
        NameReg(config.lookup(1)).register(name);
    }

    // Functions can be overridden by another function with the same name and
    // the same number/types of inputs.  If the overriding function has different
    // types of output parameters, that causes an error.
    // Both local and message-based function calls take these overrides
    // into account.
    // If you want the function to override, you need to use the
    // `override` keyword. You need to specify the `virtual` keyword again
    // if you want this function to be overridden again.
    function destroy() public virtual override {
        if (msg.sender == owner) {
            Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);
            NameReg(config.lookup(1)).unregister();
            // It is still possible to call a specific
            // overridden function.
            Destructible.destroy();
        }
    }
}

// If a constructor takes an argument, it needs to be
// provided in the header or modifier-invocation-style at
// the constructor of the derived contract (see below).
contract PriceFeed is Owned, Destructible, Named("GoldFeed") {
    function updateInfo(uint newInfo) public {
        if (msg.sender == owner) info = newInfo;
    }

    // Here, we only specify `override` and not `virtual`.
    // This means that contracts deriving from `PriceFeed`
    // cannot change the behaviour of `destroy` anymore.
    function destroy() public override(Destructible, Named) { Named.destroy(); }
    function get() public view returns(uint r) { return info; }

    uint info;
}

When deploying the PriceFeed contract, getting the following error:
creation of PriceFeed errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

When deploying the Named Contract with the Argument "GoldFeed" (without quotes obviously):
creation of Named errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="GoldFeed", code=INVALID_ARGUMENT, version=bytes/5.0.5)

There are no compilation errors.  Any assistance over here.


texts:
A struct which contains a dynamic arrays seems to be impossible to initialize, e.g. this doesn't work:

contract Quux {
    struct Foo {   string[] bar;     }
    mapping (address => Foo) foos;
    function Quux() {
        foos[msg.sender] = Foo([]);
    }
}

It looks like it's impossible to say "I just want an empty array here".

This isn't specific to structs, though, the following won't work either:

 mapping (address => uint[]) foos;
 ...
 foos[msg.sender] = [];

A possible workaround is to access "non-existent" structure, e.g.

    function Quux() {
        Foo myFoo = foos[msg.sender];
        myFoo.bar.push("xxx");
    }

Is this how it's supposed to work?


texts: Logical OR operator is not working in IF condition, solidity 0.5.0

texts:
I wanted to ask if is it available to use OR operator in IF conditions, because its giving me awkward results, like this:

contract test {
  if(player1Points > Player2Points || player1Points >= 50){
      result = 1;
  }
}

any help ??


texts: safeTransferFrom is undefined in buidler test

texts:
I have started using buidler for testing/compiling my contracts. In one test i have setup a scenario that a owner attempts to transfer a token to another wallet address.
My contract is inheriting from the Open Zeppelin ERC721.sol one. When trying to call token.safeTransferFrom(args) it says that safeTransferFrom is not a a function and when logging it out it shows as undefined.
Im pretty new to solidity and smart contract coding but looking through the source I can see that the function declaration looks the same as approve which I can call quite happily using token.approve(args).
Is there anything obvious that Im missing?


texts: How to generate consistent hash value with Solidity within Truffle?

texts:
I would like to generate hash value within Truffle using the web3.sha3() function and the hash value is required to be consistent with that one generated in Solidity. The basic example is sha3(uint256(1)). I read the related question here How does Solidity's sha3 / keccak256 hash uints?
However the LEFTPAD method is not supported in Truffle so I did the hashing in the following way:

(within Truffle) web3.sha3("0x000000......000001") which produced "0xcb371be217faa47dab94e0d0ff0840c6cbf41645f0dc1a6ae3f34447155a76f3"

(within solidity) sha3(uint256(1)) whcih produced "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6"

These two values are apparently not the same. I would like to know how can   I generate the same hash in Truffle with respect to this given example.


texts: Will a transaction that depends on another transaction be included in the same block by a miner?

texts:
Consider two transactions, A and B. A is valid given the state of the blockchain as of the last block. B is currently invalid, but becomes valid once A takes effect. A and B are from the same caller and their nonces are sequential - eg A has nonce 4 and B has nonce 5.
For examples of this, consider two smart contract calls where B depends on the effects of A to function.
My understanding is that if both transactions end up on the same block, this block will be valid, because when tx B is processed , tx A will already have happened.
My question is - in practice (ie with current miner implementations) - will both transactions be included on the same block? Assume the gas price is high on both.
I could see it both ways - a miner might not include transactions that are invalid as of the state of the last block. But I could also see them trying to include them all, and the nonces give a hint as to the ordering and validity.


texts:
I want to interact with a simple contract on the ropsten network this is my Js code :

Web3 = require('web3');

if (typeof web3 != 'undefined')
{
    web3 = new Web3(web3.currentProvider);
    console.log("existing web3: provider " + typeof web3);
    console.log(web3.currentProvider);
}
else{
    //To Do..
    web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/"));
    console.log("new provider " + web3);
}

console.log(web3.isConnected());
console.log(web3.eth.accounts[0]);

abi = JSON.parse('[{"constant": false,"inputs": [{"name": "hash","type": "bytes32"}],"name": "apply","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"},{"constant": true,"inputs": [{"name": "email","type": "string"}],"name": "getApplicationID","outputs": [{"name": "","type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"}]');
var ProfContract = web3.eth.contract(abi);
//Ropsten Deployed Address Contract - See Video on Deploying to Ropsten
contractInstance = ProfContract.at('0xcbbfbafedb0eb83016d2a96a4e80d30b20fa3e30');
console.log (contractInstance);

var email = "83b3e70ad37f69ee6cad0255ad8fcdec8b5c42c69dcf7f8273662f7ea6a8fc3c";

function apply() {
console.log("Done: " );

}

But I get this error message on my console

Access to XMLHttpRequest at 'https://ropsten.infura.io/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Uncaught Error: CONNECTION ERROR: Couldn't connect to node https://ropsten.infura.io/.
    at Object.InvalidConnection (errors.js:28)
    at HttpProvider.send (httpprovider.js:76)
    at RequestManager.send (property.js:143)
    at Eth.get [as accounts] (property.js:46)
    at index.js:17

thanks for any help.


texts: How to get the actual runtime bytecode from creation bytecode and constructor arguments without deploying

texts:
Possible outputs of the Solidity compiler include creation bytecode and deployed (runtime) bytecode. However, this compiled deployed bytecode might not be the same as the one that will actually be deployed on the blockchain. This might be the case if the contract requires constructor arguments to initialize immutable variables. So, how do I use the mentioned artifacts (creation bytecode, deployed bytecode, constructor arguments) and generate the actual deployed bytecode, without actually deploying it. One possible option is to deploy to a (local) testnet and then see the deployed bytecode, but this seems like an overkill.
Ok, to make things clearer, this is the nomenclature (I didn't make it up: What is the difference between bytecode, init code, deployed bytedcode, creation bytecode, and runtime bytecode?):
deployed bytecode = runtime bytecode
actual deployed bytecode = actual runtime bytecode
This question concerns the fact that it is sometimes the case that:
deployed bytecode (as predicted by compilation) =/= actual deployed bytecode (after deployment)
In fact, the last formula generally holds when a contract uses immutable variables.


texts: msg.sender problem for calling ERC20 token contract from another contract

texts:
I am using a ERC20 Token contract as indicated below. (I have deleted the irrelevant portions).

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";

contract TNStoken is Ownable {

using SafeMath for uint256;

mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;

string public name;
string public symbol;
uint8 public decimals;

constructor() public {
    name = "The Neverending Story Token";
    symbol = "TNS";
    decimals = 18;
    totalSupply_ = 100 * 10**6 * 10**18;
    balances[msg.sender] = totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value <= balances[msg.sender] - locked[msg.sender]);

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

function balanceOf(address _owner) public view returns (uint256) {
    return balances[_owner];
}

function totalSupply() public view returns (uint256) {
    return totalSupply_;
}
}

Now, this contract is deployed, and after this deployment, I have another contract that uses this ERC20 contract. The address of the ERC20 token contract is passed to the constructor of this contract, as follows:

contract Adoption {
    TNSToken token;
    address[16] public adopters;
    address owner;

    constructor(address _token) public {
        token = TNSToken(_token);
        ownder = msg.sender;
    }

    function adopt(uint petId) public {
        require(petId >= 0 && petId <= 15);
        token.transfer(address(this), 5 * 10**18);
        adopters[petId] = msg.sender;
    }
}

Now, the point is that this Adoption contract function adopt() is calling the TNSToken contract function transfer(), so inside the transfer() function, msg.sender will be the address of the Adoption contract (and not the account that is paying tokens for pet adoption).

So, how do I indicate to the transfer() function that I want the account address to be used for token transfer ?

One possibility is to pass this function msg.sender while calling it from the Adoption contract.... Is this the right way to deal with this problem ?


texts: Can I truffle migrate with geth --light?

texts: I get invalid address when I try to, I suspect --light doesn't enable deploys -- is that so?


texts: What does instance refer to in solidity/JavaScript

texts:
DToken.deployed().then(function(instance){ token = instance; })

This code I saw in truffle test. Can someone please tell what does this "instance" parameter refer to?


texts: Example Smart Contracts functions not working?

texts:
I'm delving into smart contracts more, and i've copy/pasted the example "Improved Token - Full Coin Node" from https://www.ethereum.org/token.  (I'd post it here it but it breaks the code formatting when i do and i have no clue how to fix it....sorry)

I'm very confused on a few things. Certain functions, such as Buy, Sell, and Freeze Account to name a few, do not work at all and throw the error

"The contract won't allow this transaction to be executed"

and

"If you submit this transaction, it will consume all the gas provided".

From my understanding, the only way to send ETH to this address is via a payable function (the "Buy" function, in my case).

I'm unsure as to what is going wrong. Another thread on here posited that it has to do with this part of the "Buy" function :

_transfer(this, msg.sender, amount);

If anyone could point me in the right direction to understand what I am doing wrong here, I would be very appreciative.


texts: Is it possible for an account to have only a single transaction, and for that transaction to be outgoing?

texts:
This account (https://etherscan.io/address/0xffffad56580f616152cbb8ac362ccf49d4abc886) confuses me. How is it possible for an account to have a single outgoing transaction with no incoming transactions?

My first thought was that this account was given ether by some smart contract and that the incoming transaction would have been an internal transaction, but there doesn't appear to be such a thing. Plus the balance of the transaction is zero. Plus the one transactions seems to have gone through with zero gas cost.

Can someone explain this to me?


texts: Signed Message Verification failing for signed messages with multiple passes

texts:
I'm using web3 to verify signed messages using the code below:

web3.eth.accounts.recover(message, signature);

I'm testing against the list of publicly verified signatures on EtherScan - https://etherscan.io/verifiedSignatures and this actually works for the vast majority of the signatures on there.

For example, by taking this publicly verified signature as an example I can see that the console output is 0x65f4667a96bbfd393f39b35b84145f2521bb359c which is as expected and verified by EtherScan

web3.eth.accounts.recover("test message", "0x290aa619d5e054c3de8b5f48e2a88e0ce410b2aea2ad3deb5c2ea7e270a10f3d27c85801ad48445a37fc27eecc86bbec92748af5fde22159a8bbe923278ec43a1b")

However, trying to do the same with this publicly verified signature returns an output of 0x31e7d77287169f0AF8aE63d276441f905A68b7aD as a result, which does not match the address published on etherscan (0x8F5d3Ad9A330009C751D76cAc7D27F929AC059CE)

web3.eth.accounts.recover("I have the private key for 0x8f5d3ad9a330009c751d76cac7d27f929ac059ce", "0xa45a8a4d35158f3610a7a8263c048b171fbf6ed9fe31a958e56be73323bf585d67a689dc361226512b04be308ccbe4e93b6c49c2253d2299dd243edd563299e701")

The exception seems to be those entries where EtherScan indicates in the results that there are multiple passes.

What does having 2 or even 3 passes to verify a signature mean, and what is the reason for doing so? I wasn't able to find documentation that goes into this

Thanks!


texts: Can I run both Ethereum and Bitcoin blockchain on the same PC?

texts:
I just completed the installation of both Bitcoin-Core on one PC and Ethereum on another PC. Both computer now have a complete blockchain and running wallet.

My question is: Could I run both Ethereum and Bitcoin-Core on one PC ?
Are there any reason for not running both Ethereum and Bitcoin-Core on one single PC ?
 Could there be interference as far as the internet access and ports, etc. ?
 Speed is not an issue since that PC will be dedicated strictly to cryptos. Thanks


texts: Understand an EVM call instruction with gas as 0x00

texts:
I am trying to understand the following EVM call instruction generated from here: https://ethervm.io/decompile

 memory[temp3:temp3 + 0x00] = address(msg.sender).call.gas(0x00).value(var1)(memory[temp3:temp3 + memory[0x40:0x60] - temp3]);

So basically the gas is specified as how much gas the sender willing to pay to send the money to the "msg.sender", right? But I am quite confused about the gas(0x00). Wouldn't the contract be able to send anything, right?


texts: Why is the CryptoKitties contract balance not the same as their revenue?

texts:
I am doing research about the CryptoKitties game. I see that its revenue is about 12M USD. But when I visit the CryptoKitties Smart Contract I see that the revenue is about 220k USD only.

I think I have missed some points here but can you please explain to me why the contract balance is not the same as the revenue?

Thanks


texts: Add data to an array in assembly for solidity

texts:
Hi I'm trying to make a function in assembly inline with following purpose:

Given: An array in the blockchain with names (= bytes32[] _documentHashes).

Asked: Find which indexes are equal to the name that I search (= bytes32 _searchHash) and return them in an array (= uint[] result)

I have the following code, with some comment to clarify my logic. Following Topic has helped me to produce this code:

function arrMke() public{ // Some test data
    bytes32[] arrMke;
    arrMke.push(0X10);
    arrMke.push(0X20);
    arrMke.push(0x10);
    arrMke.push(0X40);
    uint[] arrResult = search(arrMke,0X10);
}

function search(bytes32[] _documentHashes, bytes32 _searchHash) public returns (uint[] result){
    assembly {
        let len := mload(_documentHashes) // Load the length (first 32 bytes)
        let counter := 0 //count each time data in the _documentHashes == _searchHash
        result := mload(0x40) // 0x40 is the address where next free memory slot is stored in Solidity.
        let i := 0 // uint i for the loop
        loop: //start loop
        let docHash := mload(add(_documentHashes, add(0x20, mul(i, 0x20)))) // docHash = _documentHashes[i], data offset = 0x20 (1st 32 is reserved for size) & i*32 to pickup the right index
        if eq(docHash, _searchHash) { // condition if(docHash == _searchHash)
            counter := add(counter,1) // increment counter by 1
            mstore(add(result, 0x20), counter) // (re)Set size of the result array each time the condtion is true
            mstore(add(result, add(0x20, mul(counter, 0x20))), i) // add data to the array, data offset = 0x20 (1st 32 is reserved for size) & i*32 to pickup the right index
        }
        i := add(i,1) // increment for loop
        jumpi(loop, lt(i,len)) // stop loop when the lenght of _documenthashes is reached
        mstore(0x40, add(result, add(0x20, mul(counter, 0x20)))) // Update/return the result array ofsset + length of the data (=i*32)
    }
}

Problem:

I don't get the debugger in remix running. The "Solidity locals" screen is empty:

uint[] arrResult = search(0x0,arrMke,0X10); does'nt want to compile:

Question:

1) How can I watch (see the data in) my variabeles, especially uint[] result? Because I'm not sure if my assemblercode is correct at all.
2) Why do I get this compile error & how can I fix it?

Thanks for your help!

Tshy


texts: Distribute token to multiple address not working


texts: inject web3 in electron-ethereum-react desktop application

texts:
I am trying to make ethereum-electron-react application.

when I try to inject web3 it does not get detected.

import Web3 from 'web3';

console.log (Web3);

this shows an empty object

 even though I have already installed Web3.

node version -v8.9.4

any ideas to fix it?


texts:
I created a contract that insert one number (uint) in blockchain with set function but how can i retrieve all numbers inserted?

This is my html, i put 1 number in a blockchain and i will see just the last inserted:

<!DOCTYPE html>

<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

Inserimento dati nella Blockchain Ethereum

                    Inserisci token:

                    1
                    <input id="xvalue" type="text" class="form-control" />

                  <input id="Button1" type="button" class="btn btn-primary" onclick="setvalue()" value="Add to Blockchain"  />

And my contract is:

pragma solidity ^0.4.24;

contract M {
    uint256 storeddata;

    function set(uint256 x) public {
        storeddata = x;
    }

    function get() public view returns(uint256) {
        return storeddata;
    }
}


texts: Masking Ethereum Address in a transaction

texts:
I want to hide the ethereum addresses of dApp users so that your transactions will not be traced by one who you have interaction earlier. The use case is actually similar to the application:

Alice goes to BerBurry and gets some clothes by paying with ethereum.
Alice goes to Suegg and gets some clothes by paying with ethereum.
Alice requests some money from Bob, by sharing her wallet address.

In the scenario above, Bob can trace that Alice has some shopping from BerBurry and Suegg. The manager of Guess knows Alice has already bought something from Burberry, vice versa.

I know that it can be handled on Quorum but what are workaround solutions of the problem? I am open to off-chain solutions that can be verifiable on the chain or the solution may require multiple transactions?

Probably, the question I have asked may require some brainstorming or it may be already resolved by some genius guys :)

@Ismael I just simplified the problem to make it clear for everyone. Actually, Alice does not pay directly to BerBurry. Instead, Eve pays for Alice and there is an agreement that states Alice will pay to Eve for borrowing money to pay BerBurry. The off-chain identity of Alice is exposed to Eve and BerBurry. Initially, Alice does not have to share her wallet address but on payback, the address will be exposed.


texts: Transaction pending in queue for 100mins +

texts:
Using Parity I submitted at Transfer of ETH using 'send after block'
The transaction has now been pending for 100mins+ (see attached).
Now I can't send any ETH as all transactions go into 'Pending' state.

How to I either get these transactions to execute or remove them ?

Many thanks in advance

[UPDATE] at 20170621-1901 =

Rebooted my Mac restarted Parity via Chrome browser result = the 2 existing transactions have been posted again 20mins ago, propagated to 50+ peers and still they are pending. There is something else at play here ...

Can someone PLEASE tell me how I can remove these transactions ?
Looks to me as if they are just being ignored by the Miners ?


texts:
I'm using geth to connect to the rinkeby network with fast sync. However, every time I restart geth I receive the following output:

Maximum peer count                       ETH=25 LES=0 total=25
Starting peer-to-peer node               instance=Geth/v1.8.2-stable-b8b9f7f4/windows-amd64/go1.9.2
Allocated cache and file handles         database=C:\\Users\\<name>\\AppData\\Roaming\\Ethereum\\rinkeby\\geth\\chaindata cache=768 handles=1024
Persisted trie from memory database      nodes=355 size=65.27kB time=971.4µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
Initialised chain configuration          config="{ChainID: 4 Homestead: 1 DAO: <nil     DAOSupport: true EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 1035301 Constantinople: <nil     Engine: clique}"
Initialising Ethereum protocol           versions="[63 62]" network=4
Head state missing, repairing chain      number=1926960 hash=1246ad…3bfcb0
Rewound blockchain to past state         number=1925246 hash=119ab4…1e5f81
Loaded most recent local header          number=1926960 hash=1246ad…3bfcb0 td=3569384
Loaded most recent local full block      number=1925246 hash=119ab4…1e5f81 td=3566020
Loaded most recent local fast block      number=1926960 hash=1246ad…3bfcb0 td=3569384
Loaded local transaction journal         transactions=0 dropped=0
Regenerated local transaction journal    transactions=0 accounts=0
Blockchain not empty, fast sync disabled
Starting P2P networking
UDP listener up                          self=enode://<address>
RLPx listener up                         self=enode://<address>
IPC endpoint opened                      url=\\\\.\\pipe\\geth.ipc

It then starts to sync after some peers were discovered, but it always throws me back 500-3000 blocks. This is quite annoying, because my PC is pretty slow and when I close geth by accident or because I don't need it for a while, I always have to wait a few extra minutes until I'm in sync again.

Does anyone have a clue what is causing this? This happened to me with geth 1.8.0, 1.8.1 and 1.8.2.


texts: web3.eth.getBlockNumber returns { [Function: get] request: [Function: bound ] }

texts:
0
down vote
favorite
I am using express and web3 while i get the blockNumber it returns  { [Function: get] request: [Function: bound ] }

my code is

var express = require('express');
 var app = express();

const Web3 = require('web3');
var web3 = new Web3();

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))

app.get('/', function(req, res) {

let Block =  web3.eth.getBlockNumber

console.log(Block);
res.send("It is me");
});

But i need the block number


texts: How to charge percentage of transaction cost?

texts:
Example:

uint public createPostCost = 0.0003 ether;

function createPost(bytes32 _post)
    public payable {
        require(msg.value >= createPostCost);
        Post memory newPost;
        newPost.post = _post;
    }

Within a discussion forum dapp, the current implementation charges users a set fee per post created. I would like the charge to be dynamic, say 10% of the gas cost of the transaction. Is this possible to implement in the contract? Or is this something for front-end web3 to handle?


texts: New web3 method to request account access from dapp browser, no request

texts:
Since metamask communicated that they will no longer inject web3 by default (https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8) I tried to use their new suggested method to access accounts.

Here is the code:

window.addEventListener('load', async () => {
    // Modern dapp browsers...
    if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
            // Request account access if needed
            await ethereum.enable();
            // Acccounts now exposed
            web3.eth.sendTransaction({/* ... */});
        } catch (error) {
            // User denied account access...
        }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({/* ... */});
    }
    // Non-dapp browsers...
    else {
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
    }
});

This works and I get access to the account, however, there is no request the user has to accept in metamask. Why is that? And how can I simulate the request to prepare my UI for this?


texts:
Can a user send a transaction using my website frontend with an account which is not in my node?

The solution to this problem could be create an account for every user in my platform, but I think that there should be some better solution.


texts: does solidity round decimals to ceil or floor them?

texts: so lets say result of a calculation in solidity is 0.2 or 0.8, when I save that result in a variable does that convert to 0 or 1 ?


texts: Error while installing truffle-hdwallet-provider

texts:
I am on windows OS and my current python version is 3.6 and node version is v10.12.0

I am trying to install truffle-hdwallet-provider by running following command:

npm install --save truffle-hdwallet-provider

Here is the error I am facing:

E:\BlockChain\truffle\firsttoken_deployment>npm install --save truffle-hdwallet-provider

> sha3@1.2.3 install E:\BlockChain\truffle\firsttoken_deployment\node_modules\sha3
> node-gyp rebuild

E:\BlockChain\truffle\firsttoken_deployment\node_modules\sha3>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Users\Fariha.Abbasi\AppData\Local\Programs\Python\Python36\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:289:12)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:962:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
gyp ERR! System Windows_NT 10.0.17763
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd E:\BlockChain\truffle\firsttoken_deployment\node_modules\sha3
gyp ERR! node -v v10.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN firsttoken_deployment@1.0.0 No description
npm WARN firsttoken_deployment@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

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

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Fariha.Abbasi\AppData\Roaming\npm-cache\_logs\2019-08-23T12_38_15_766Z-debug.log

Can someone guide me what is happening wrong?


texts: Help on transferFrom and Approve functions

texts: We have a token contract A and an Escrow contract B. While transferring token from an address to contract B we are using transferFrom function which overridden from contract A. But in need to do the transfer , we have to call approve function on contract A. This works if we call the approve function directly from contract A. But if we are overriding the approve function just like transferFrom on contract B, it is failing. Could someone please explain how we can call approve from contract B itself.


texts:
Using Remix, I can't pass a set of bytes ["0xee", "0xff", "0xgg", "0xhh", "0xii"] to my function

function foo(bytes5 input) {
    // Do something
}

I've already tried all these formats:

["0xee", "0xff", "0xgg", "0xhh", "0xii"]
["0xeeffgghhii"]
["0xee0xff0xgg0xhh0xii"]
"0xeeffgghhii"
"0xee0xff0xgg0xhh0xii"
[["0xee"], ["0xff"], ["0xgg"], ["0xhh"], ["0xii"]]
"0xee", "0xff", "0xgg", "0xhh", "0xii"

The IDE always raises the same error or says (legitimately) that the number of arguments doesn't match with my function:

  Error encoding arguments: Error: invalid bytes5 value (arg="", type="object", value=undefined)

As you can see I already tried the solutions suggested here and here, how should I do it?
Thanks in advance!


texts:
Getting this in Solidity:

browser/ballot.sol:121:16: Parser Error: Expected Primary Expression.

Here is my code, says that it is the name line with the parser error

function ERC20Token(
    ) {
    balances[msg.sender] = 888888;
    totalSupply = 88888888;
    name = “DoubleHappiness";
    decimals = 8;
    symbol = “DBL";
}


texts: What are the under-the-hood mechanics for locking an ERC-20 token?

texts: I have some idea of what "locking ether" means, but I need to understand for sure.  AFAIK, tokens exist at some address, but according to many sources, the token is locked in a smart contract for some period of time.  What is the reality?  Do tokens get locked at the source address for the time-limit, or at some temporary neutral storage location (address) before it is sent to the destination?  I am wondering in the case where someone wants to prevent themselves from using some amount of tokens using this locking mechanism.  In that case, there is no destination.  How does the code work?  The source and destination are the same, or do the funds get locked in a neutral storage location to be returned to the initial address after the vesting period is over.


texts: Is it possible to chain mulitiple individual transactions into a single "all or nothing" transaction?

texts:
Lets say I have a contract with a bunch of individual properties. For example, a person with a firstName and lastName field.

A user of a dapp wants to change both fields, which would take two individual transactions.

This is problematic from a UX perspective, since its possible that one of the transactions succeeds while the other fails, and the user must be made aware of it.

This becomes more problematic when changes are codependent. Consider a user who wants to change the firstName of a person CONDITIONAL on the lastName changing.

Is it possible to chain these independent transactions into a single all or nothing transaction?


texts: miner.Start() Returns "null" - Its frustrating

texts:
I set a private blockchain on Ethereum. Two nodes up and sync'ed as peers. Issue is it does not start mining.

miner.Start() Returns "null" - What can I do?

Have set eth.coinbase() return the a new account etc. So am not sure whats happening.


texts:
Web3.py version 3.15.0
Python: Python 3.5.2
OS: linux

I have followed @carver 's answer related to Rinkeby failure with web3.py — Could not format value '0x…' as field 'extraData' related to web3.exceptions.ValidationError: The field extraData is 97 bytes, but should be 32. It is quite likely that you are connected to a POA chain. Refer http://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority for more details.:

Code:

from web3 import Web3, IPCProvider
# connect to the default geth --dev IPC location
w3 = Web3(IPCProvider('/home/user/POA/private/geth.ipc'))
from web3.middleware import geth_poa_middleware #<===Error occurs

# inject the poa compatibility middleware to the innermost layer
w3.middleware_stack.inject(geth_poa_middleware, layer=0)

# confirm that the connection succeeded
w3.version.node

Error I am having:

Traceback (most recent call last):
  File "coder.py", line 4, in <module>
    from web3.middleware import geth_poa_middleware
ImportError: cannot import name geth_poa_middleware

[Q] How could I fix this error (cannot import name geth_poa_middleware)?


texts: How to identify ether payments from an exchange?

texts:
I am building an application that accepts payments from its users. Nowadays, only users with a wallet can make withdraws to a smart contract address(mine). This is because each user has a single and unique wallet address, so the backend is able to identify its transactions.
Nevertheless, exchanges uses the same withdraw address for most of its users so it is impossible to identify unique users transactions to my smart contract.

Why exchanges use the same address for all the withdraws?

My solution to that would be creating a temporal wallet in my backend for each user transaction and then send the received ethers to the main wallet/smart contract.

This solutions requires two transactions, so double fees. Is there any good alternative to that?


texts: Call function from a dynamically created Contract

texts:
I'm creating a Main contract which will be used to create dynamic contracts with msg.sender as Owner. Anyone can send ETH externally to the dynamic contract and anyone can withdraw ETH from the dynamic contract but it will only goto Owner.

main.sol

contract Main{
   // this contract will just create contracts
   mapping(address => address[]) public dynamic_contracts;
   function createContract(){
      address newContract = new Dynamic(msg.sender);
      dynamic_contracts[msg.sender].push(newContract);
   }
}

dynamic.sol

Contract Dynamic{
 // this contract will hold funds and transfer em
    address Owner;
    function Dynamic (address owner) {
        Owner = owner;
    }
    function transferFunds(){
      //transfer it to Owner
      Owner.transfer(this.balance())
    }
}

The problem is Dynamic contract is created dynamically therefore i only have its address stored in mapping dynamic_contracts of Main. I don have its abi so how do i call transferFunds function ?


texts:
I'ved tried my luck on ethereum mining with this https://github.com/angelomilan/ethereum-guides/blob/master/GPU-cloud_mining.md
And I think I have some ethereum.

> eth.getBalance(eth.coinbase).toNumber();
5000000000000000000
> web3.fromWei(eth.getBalance(eth.coinbase), "ether")
5

UPDATE:
I tried to send using this but has this error:

eth.sendTransaction({from:eth.accounts[0], to:"0x21389ab987979ae987", value: web3.toWei(0.0005, "ether"), gas:5000})

Error: intrinsic gas too low

> eth.getBlock("latest").gasLimit
5003

> net.peerCount
0

What is intrinsic gas too low and how to solve this, my gasLimit is 5003. What is all this and how to I would say pump more gas ?

My question is now how do I convert it to cash ? I cant figure that out. I believe on the .ethereum hidden folder contains the coinbase wallet. How do I then cash it out ?


texts:
Want to get tokens amount sent to my contract address on chain, but don't know address of token.

Can I get through any function ?

Any possible way to so ?


texts: Can I download the wallet and blockchain to an external disk?

texts:
I am running on a macbook air and suffering from incredibly small storage space. Is it possible for me to download the wallet + sync the blockchain and securely store my tokens on the external disk?

Other answeres I have found have suggested transferring the files from local to external, but I am unable to save it locally to begin with

What are my options?

Looking forward to getting stuck into solidity and writing some smart contracts :-)


texts: I brought DAO tokens via Kryptokit ..I now find out the best way is to use mist - please help

texts:
I have ethereum installed. Opened terminal and mist28 running in the background.
Kryptokit wallet is open in the browser and I have it backed up.
I have looked and this seems to be possible.
Can anyone help me out.
Thanks


texts: Is Ethereum a common blockchain for all type of smart contracts (several thousands)

texts:
I have read that full nodes run all the contracts(several thousands) to verify them so aren't they using too much energy (and also thus spending money) to verify each and every contract that is requested on the network.
Since there are too many contracts and also requests coming for them can it be the case that request for a contract take minutes or hours to be performed by the mining nodes?

Sorry for asking such basic questions actually I am new to this stuff.


texts: I don't understand the "share" concept in miner and pool

texts: If I launch a miner, after a few minutes it displays "shares: 65", 65 acepted. But pool statistics shows me "valid shares 23, stale shares 0, invalid shares 2". Last seen 12 minutes ago, but the miner can't found 40 shares in 12 minutes.... Where gone the shares?.


texts: Index and query blockchain data and levelDB

texts: Would it be more performant to query the blockchain data directly through the underlying database levelDB instead of using the provided geth api? How would it be possible? Can I just index the transactions by sender / receiver in mysql or elasticsearch? I saw vulcanizeDB doing this


texts: how to send ether on the testnet thru command line, specify gas cost & transaction cost

texts:
as you can see in the above screen capture, I'm trying to send some ethers through the command line.

something slightly confusing is that from this documentation (I'm using geth), it doesn't seem to indicate a place to specify the gas price, transaction fee, etc. why not?

why did this transaction fail?


texts: How do Ethereum's transaction fees compare to Bitcoin?

texts:
Ethereum has faster transactions than the 10 minutes of standard bitcoin protocol.
How do the transaction fees compare at the moment if you translate the price into a comparable currency like dollars or euros?
Long-term how are they likely to compare?


texts:
How do I receive a revert message using go-ethereum?
receipt, err := bind.WaitMined(context.Background(), client, tx)
if err != nil {
    fmt.Errorf(err)
}
fmt.Println(receipt.Status)

Now I can only get status. I use abigen to call smart contract methods


texts: error.message.indexOf is not a function truffle ganache

texts:
for truffle developers
var Election = artifacts.require('./Election.sol');

contract("Election",function(accounts){
var electionInstance;

it("throws an exception for double voting",function(){
    return Election.deployed().then(function(instance){
        electionInstance = instance;
        candidateId = 2;
        electionInstance.vote(candidateId , { from:accounts[4] });
        return electionInstance.candidates(candidateId);
    }).then(function(candidate){
        var voteCount = candidate[2];
        assert.equal(voteCount,1 ,"accepts first vote");
        return electionInstance.vote(candidateId,{from : accounts[1] });
    }).then(assert.fail).catch(function(error){
          //error at this line
        assert(error.message.indexOf('revert')>=0,'error message must constain revert');
        return electionInstance.candidates(1);
    })
});

});

return the error as

Contract: Election
throws an exception for double voting:
TypeError: error.message.indexOf is not a function


texts: How can an account with a direct ICAP address be created?

texts:
In order for an Ethereum account to be able to have an IBAN-compatible "direct" ICAP address, its raw address must have zeroes in the most-significant 6 bits. In other words it must fit in 154 bits.

The only way I know in which to do that is by brute-force: pick a private key, derive the public key from it, and then the address from that - and repeat until you find one that meets the criterion. There's a 1-in-64 chance each try.

Is that the only way to do it?


texts: Truffle Deployment Error: Invalid number of parameters for "undefined". Got 1 expected 0!

texts:
I am trying to deploy my smart contract. When I run truffle compile everything works however when I run truffle migrate, I get this occurring error message:

Error: * Deployment Failed *
"KJToken" -- Invalid number of parameters for "undefined". Got 1 expected 0!.

I have tried to delete my build folder and reset my compilations but nothing is working. Even when I try to reset my truffle migration the same error shows up.
Here is my deploy contracts.js code:
var KJToken = artifacts.require('./KJToken.sol')
module.exports = function (deployer) {
  deployer.deploy(KJToken).then(function () {
    return deployer.deploy(KJToken, KJToken.address)
  })
}

Here is my kjtoken.sol
pragma solidity >=0.4.21 <0.7.0;

contract KJToken {
    string public name;
    string public symbol;
    uint8 public decimals;
    uint256 public totalSupply;

    //balances for each account
    mapping(address => uint256) balances;
    address devAddress;

    //Events;
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
    event Transfer(address indexed from, address indexed, uint256 value);

    // owner of account approves the transfer of an amount to another account
    mapping(address => mapping (address => uint256)) allowed;
    // contructor is automattically going to run when the smart contract is uploaded
    constructor() public {
        name = "KJtoken";
        symbol = "KJ";
        decimals = 18;
        devAddress = 0x22391dc3a3cD8e9774F426e5405C3440559D0a1e;
        uint initialBalance = 1000000000000000000*1000000; // 1M tokens
        balances[devAddress] = initialBalance;
        totalSupply += initialBalance; //set the total supply

    }

    function balanceOf(address _owner) public view returns (uint256 balance) {
        return balances[_owner];
    }

    //Transfer the balance from owner's account to another account
    function transfer(address _to, uint256 _amount) public returns (bool success) {
        if (balances[msg.sender] >= _amount
            && _amount > 0
            && balances[_to] + _amount > balances[_to]) {
            balances[msg.sender] = _amount;
            balances[_to] += _amount;
            emit Transfer(msg.sender, _to, _amount);
            return true;
        } else {
            return false;
        }
    }

    function transferFrom(
    address _from,
    address _to,
    uint256 _amount
) public returns (bool success) {
    if (balances[_from] >= _amount
        && allowed[_from][msg.sender] >= _amount
        && _amount > 0
        && balances[_to] + _amount > balances[_to]) {
        balances[_from] -= _amount;
        allowed[_from][msg.sender] -= _amount;
        balances[_to] += _amount;
        return true;
    } else {
        return false;
    }
}

// allow _spender to to withdraw from your account, multiple times, up to the _value amount.
// if this functin is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) public returns (bool success) {
    allowed[msg.sender][_spender] = _amount;
    emit Approval(msg.sender, _spender, _amount);
    return true;
}

}


texts: NEthereum, Number of indexes don't match the number of topics

texts:
I would like to get all Transfer events for a specific interval of blocks.

When I call GetAllChanges with the following parameters, I get this error message:

  'Number of indexes don't match the number of topics. Indexed
  Properties 2, Topics : 0'

Event<TransferEventDTO> transferEvent = new Event<TransferEventDTO>(_web3.Client);
filterTransferEvents = transferEvent.CreateFilterInput(new BlockParameter(6_500_000), new BlockParameter(6_500_001));
var ethNodeResp = transferEvent.GetAllChanges(filterTransferEvents).GetAwaiter().GetResult();

If I however instead call this function on another range, then it works.

filterTransferEvents = transferEvent.CreateFilterInput(new BlockParameter(509_000), new BlockParameter(510_000));

I use Netehereum.Web3 version 3.2.0 and it talks with a Parity wallet version 2.4.1 in full archive mode

Does this have something to do with indexes not being set consitently on the Transfer events? What can I do to fix this?


texts:
Im getting about 43.4 Mh/s on my Radeon Pro Duo using ubuntu and latest fire pro drivers.

Any suggestion on how to increase the hash rate?
Thanks!


texts: Fund my Ropsten account to deploy my contract

texts:
I have a full geth node on my machine and I want to deploy my contract on Ropsten using truffle.
How I can fund my coinable account with some ether to deploy my smart contract?
I have tried fuusent.ropsten but it says " invalid address"
I have account in metamask and it has some ether but I did not know how to use it.
how can I add some ether to any account I created in Ropsten to use it to deploy the smart contract and to interact with it later after deploy it
I want many account to interact with my smart contract. I used the command geth --ropsten account creat but I don't know how to fund all theses accounts
In truffle.js I have this:
ropsten: {

 host: "Localhost",     // Localhost (default: none)
 port: 8545 ,           // Standard Ethereum port (default: none)
 network_id: "*",       // Any network (default: none)

},

In a terminal I connect to the node as the following:
geth --syncmode "fast" --cache=1048 --ropsten --rpc --rpcapi "eth,net,web3" --rpccorsdomain '*' --rpcaddr localhost --rpcport 8545 console

Then in another terminal I deploy the smart contract using truffle as the following:
Truffle migrate --network ropsten

and it does not work as this error appear:
1_initial_migration.js
======================

 Deploying 'Migrations'
  ----------------------

 Error:  *** Deployment Failed ***

 "Migrations" could not deploy due to insufficient funds
    * Account:  0xd48616a728b4D05A5b0e6457EBda383A92f40A54
    * Balance:  0 wei
    * Message:  sender doesn't have enough funds to send tx. The upfront cost is: 372936000000000 and the sender's account only has: 0
    * Try:
      + Using an adequately funded account
      + If you are using a local Geth node, verify that your node is synced.

When I check the address balance, it returns 0:
> eth.getBalance("0xd48616a728b4d05a5b0e6457ebda383a92f40a54")
0


texts: When running a smart contract, what exactly happens on the blockchain?

texts:
When somebody runs a smart contract, what part goes into the blockchain?

The whole contract (in Solidity), only the transaction or the complete execution (contract and input data)?


texts: How to get owner recovery phrase programmatically during keystore file generation?

texts:
I've generated keystore file by means of keythereum

function generateAddress(cb) {
  var params = { keyBytes: 32, ivBytes: 16 };

  var dk = keythereum.create(params);

  keythereum.create(params, function (dk) {
    var options = {};
    var password = generatePassword();
    keythereum.dump(password, dk.privateKey, dk.salt, dk.iv, options,
      function (keyObject) {
        cb(keyObject, password);
      }
    );
  });
}

function generatePassword() {
    var length = 8,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

How to programmatically extract recovery phrase from generated keystore file or get it during the process of generation?


texts: How do you handle the hex prefix without the value (only "0x")?

texts:
First, I'm caling function foo() (from another contract) that returns me a uint in the form of bytes.
Then, I'm using BytesLib.toUint(foo(), 0) to retrieve the uint.
When the value is supposed to be 1, foo returns 0x0000000000000000000000000000000000000000000000000000000000000001, and BytesLib.toUint(foo(), 0) works fine.
When the value is supposed to be 2, foo returns 0x0000000000000000000000000000000000000000000000000000000000000002, and BytesLib.toUint(foo(), 0) works fine.
However, when the value is supposed to be 0, foo does not return 0x0000000000000000000000000000000000000000000000000000000000000000.
It returns 0x. And BytesLib.toUint(foo()), 0) does not work.
I would like to implement some logic to check if the value of foo() equals 0x. I've tried multiple things:

if (foo() == 0x) { //do something else }
if (foo() == "0x") { //do something else }
if (foo() == address(0)) { //do something else }
if (foo() == keccak256(0x)) { //do something else }

But all of these result in compilation errors.
How should I handle 0x?


texts: fallback function is accepting more than 2300 gas

texts:
Quoting from solidity doc:

  In such a context, there is usually very little gas available to the
  function call (to be precise, 2300 gas), so it is important to make
  fallback functions as cheap as possible. In particular, the following
  operations will consume more gas than the stipend provided to a
  fallback function (updating state variable a to 100):

  Writing to storage
  Creating a contract
  Calling an external function which consumes a large amount of gas
  Sending Ether

So ideally I should not use complex logic in fallback function. And fallback function can not use more than 2300 gas.

I gave this a try.

pragma solidity ^0.4.18;

contract TestFallback{
    uint public a = 0;
    uint public loopsize = 100;

    function updateLoopSize(uint _size) public {
        loopsize = _size;
    }

    function() public payable{
        uint i = 0;
        for (i=0; i<loopsize; i=i+1){
            a +=1;
        }
    }
}

I called the fallback function with loopsize = 100. The function executed successfully with following gas consumption:

  gas   : 3000000; transaction cost : 585049; execution cost: 563777

Now, this confused me with the paragraph I just read. I even tried making calculations as well as token transfers in fallback function. They consumed more than 100,000 gas but executed successfully. So what am I missing?

Can I use complex logic inside fallback function?
If I need to execute some function (like send tokens) as soon as the user's pay ethers to smart contract, what are possible approaches apart from writing the logic in fallback function.

PS: For second query, I don't think making a payable function will help. As in that case users have to call a specific method of smart contract. But I want that user's just send Ethers from any wallet and recieve assets. (User's don't need any abi to send eth to contract)


texts: Mappings inside functions to filter query

texts:
I have a struct and several boolean mappings that are used to keep track of struct's properties

struct Animal {
    string species;
    bytes32 ID;
}

mapping (bytes32 => Animal) public Animals;

mapping (bytes32 => bool) public Mammals;
mapping (bytes32 => bool) public Birds;
mapping (bytes32 => bool) public Fish;

mapping (bytes32 => bool) public Carnivore;
mapping (bytes32 => bool) public Herbavore;
mapping (bytes32 => bool) public Omnivore;

After setting some of these booleans to "true" I want the user to call a functions to check on an animal's properties.

function CarnivoreFish(bytes32 _ID) public returns (bool){

    //used to check if animal is a carnivorous fish

    if( Fish[_ID] == true &&  Carnivore[_ID] ==true ){
       return true;
    }
    else{
        return false;
    }
}

I want to be able to generalize the previous function to work for any combination of animal class and diet.  I have tried  defining new mappings and setting them equal to the mappings above based on keywords.

function filterAnimals(bytes32 _ID, string memory _animalClass, string memory _diet) public returns (bool){

    mapping (bytes32 => bool) memory AnimalClass;
    mapping (bytes32 => bool) memory Diet;

    //set first mapping "AnimalClass"
    if (_animalClass == "mammals") {
      AnimalClass = Mammals;
    }
    else if (_animalClass == "birds"){
       AnimalClass = Birds;
    }
    else{
        AnimalClass = Fish;
    }

    //set second mapping "Diet"
    if (_animalClass == "mammals") {
      Diet = Carnivore;
    }
    else if (_animalClass == "birds"){
       Diet = Herbavore;
    }
    else{
        Diet = Omnivore;
    }

    //check if animal has both propeties

    if( AnimalClass[_ID] == true &&  Diet[_ID] ==true ){
       return true;
    }
    else{
        return false;
    }
}

I receive errors based on the way I am trying to define my mappings. Is there a way to set one mapping equal to another like I am trying to do? Is there a more obvious way to generalize the CarnivoreFish function?


texts: Is Egretia (EGT) is still Ethereum Token? Or It has been moved as a Coin to its own Blockchain?

texts: Currently Egretia (EGT) is represented as a Token of Ethereum Network, but is there any changes regarding shifting from Token to Coin on its own Chain?


texts: Deployment Failed : "Migrations" -- only replay-protected (EIP-155) transactions allowed over RPC

texts:
I am trying to migrate the code which is already tested in mainnet to ropsten network. I wonder why it is throwing the below strange error. We as a team unable to find a solution for this for past 2 days.
Any assistance in this regard will be very helpful
Error message from truffle
Error:  *** Deployment Failed ***

"Migrations" -- only replay-protected (EIP-155) transactions allowed over RPC.

at C:\Users\****\AppData\Roaming\nvm\v8.11.4\node_modules\truffle\build\webpack:\packages\deployer\src\deployment.js:364:1
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Truffle v5.1.12 (core: 5.1.12)
Node v8.11.4

2_deploy_crowdsale.js
await deployer.deploy(
  KiiACrowdSale,
  _rate,
  _ownerAddress,
  this.token.address
);

error after adding the
await deployer.deploy(
KiiACrowdSale,
_rate,
_ownerAddress,
this.token.address,{chainId: 3}
);


texts:
Based on EIP 150 change the call depth attach.

EIP and EIP-discussion:

  Note that with the given parameters, the de-facto maximum call stack
  depth is limited to ~340 (down from ~1024), mitigating the harm caused
  by any further potential quadratic-complexity DoS attacks that rely on
  calls.

On this accepted answer:

  With the new rules, the call cannot consume more than 63/64 of the gas
  of the parent. So if your gas is X, then N CALLs in, it will be max X
  * (63/64)^n.

[Q] Is this statement correct with the new rules?

Based on my calculations following statement is wrong:

  if your gas is X, then N CALLs in, it will be max X * (63/64)^n

because we also need to add cumulative gas-sum till the nth call on the stack.

Hence Till we reach (n-1)th call the parent's gas will be decrease as new gas value: X_n' at each stack level.

For example:

1    => X_1   = X        * (63/64)^n
2    => X_2   = X_1      * (63/64)^n //X_1 is used instead of X
3    => X_3   = X_2      * (63/64)^n //X_2 is used instead of X
...
N    => X_(N)  = X_(N-1) * (63/64)^n
1022 => X_1022 = X_1021  * (63/64)^n //X_1021 is used instead of X
1023 => X_1023 = X_1022  * (63/64)^n //X_1022 is used instead of X

So Nth call should be something like: X_n * (63/64)^n, where X_n should be much smaller than original X. So gas consumption limit gets much smaller.

Overall, the main question I have is:

[Q] How EIP 150 gas cost algorithm works on each stack level? and how gas consumption limit is affected at each stack level?

Please note that I am not questioning the answer, I just want to understand what should be correct.

Thank you for your valuable time and help.


texts: how to send one transaction from multiples seed wallets?

texts:
I would like to know if there is posible to group 3 wallet balances derived from a seed phrase and send one tx.

Example :

The user received 1 ETH to address A, 1 ETH on address B, ETH on address C.

Now the user wants to send 3 ETH to another wallet. How would he do it? What about miner fee, will be multiples transactions, one transaction?

there is an code example of that?


texts:
I want to create customized ethereum wallet in my web site. is there are any way to develop customized wallet ?

thanks.


texts:
Update2: Ismael highlighted that upgrading drizzle and Web3 were crucial. I was using drizzle 1.3 and Web3 1.0. So, using the same Solidity code, I can now read a string array into a webpage, using drizzle 1.5.3 and Web3 1.3.
Update: I found a note on this forum by goodvibration that noted

And so there is no way for you to return an array of strings. Perhaps
on solc 0.6, but I doubt it. –

Therefore, instead of pulling an array, I created a function in my Solidity contract that returned only elements from a string array. This worked. If anyone knows how to pull string arrays, that would be great, but it appears impossible.
...
I can call getter functions on an Ethereum smart contract that reads an array of uints, but when I just change my target to a string, my javascript file fails to read it.
My Solidity getters look like this; they are identical except one array is uint the other a string. They both work in Remix on Rinkeby (the strings have items with about 10 characters, all English letters).
function showUint() external view returns (uint[16] memory) {return teamScheduleU;}

 function showString() external view returns (string[16] memory) {return teamScheduleS;}

My javascript code looks like this
  this.scheduleKey = this.contracts[this.contractDict].methods.showUint.cacheCall()}
...
 myArray = this.props.contracts[this.contractDict].
showUint[this.scheduleKey].value;

When I pull in the uint array in javascript with showUint as above, it works. When I replace with showString it does not. The error reads:
   Error: Invalid UTF-8 detected
    at decodeSymbol (utf8.js:194)
    at Object.utf8decode [as decode] (utf8.js:206)
    at Object.hexToUtf8 (utils.js:218)

I get this same error when trying to read an event log that contains a string array (I can read event logs from the same contract that do not contain strings). Interestingly, I get this same error even if I do not process the string variable from the event log, just that the event log contains a string (it has the same "Invalid UTF-8" descriptor).


texts: Honest lottery winner generation - pseudo random number obtaining

texts:
Suppose I would like to organize a honest lottery and prevent cheating when we need to find a winner. I known problem of random number in the known network arises.

I would like to try the following algorithm to prevent cheating.

The idea is to use hash of a block but the block number is not known for miners/participants and organizers to prevent cheating.

On start organizer defines a random uint64 - key number to be used in the winner random number calculation. The uint number is big enough and known to organizer only on start.
Organizer fixes the key number by providing hash of sum - the number plus current block hash (as a salt).
The key hash is stored in the Lottery contract and available for all the participants. Then key hash is used to prevent organizers cheating and fixes the key number.
Participants buy tickets and the Lottery contract stores all the participant addresses. The addresses are used on winner calculation as well.
When conditions are fulfilled (e.g. all the tickets are sold or necessary amount of blocks are generated or just after some time) organizer starts winner calculations.
Organizer provides the stored key number and confirms the number is exactly the same by calculating the key hash (entered on init).
The key number is added to the sum of addresses and we got mod 255 of the sum to detect number of block which hash is used to detect winner.
Key number + address1 + address2 ... + addressN % 255 = number of winner block (the block hash is used to get winner number)

To person who want to guess winning number it is not possible to get the number - in the contract we have just hash of the number. The number is rather big uint64 (or could be even bigger) to prevent "unhashing" the number.
For organizers the number is fixed and is futile because all the tickets owners addresses must be known to calculate the winner.

Opinions? Any holes in the logic?

UPDATE:
After discussing the suggested algorithm there is an improvement.

When a participant buys a ticket it is allowed to pass additional has for participant key number which is also used in the winner calculation.
Suppose ticket price is 100%.
When participant want to provide own participant key number he pays more e.g. 300%.
When the participant key number is provided during the winner detection round 210% of ticket price is returned.
If the participant key number is not provided the sum is added to the lottery prize.

Thus everybody who has doubts about organizer honesty can add own random part. Not providing the key means such a person lost the deposit.
Such honesty providers can have cheaper (in fact) tickets.


texts: Truffle configuration, server.js instead of lite-server

texts: As it seems lite-server is only good for development. I decided to use server.js for production but I have no idea how to configure it for truffle?


texts: Infinite gas estimation from solc for simple function

texts:
Here is a simple Solidity contract:

pragma solidity ^0.4.16;

contract Test {
    uint[] array;

    function testGasEstimation() public {
        array.length = 1;
    }
}

Here is the output of solc --gas Test.sol

======= Test.sol:Test =======
Gas estimation:
construction:
   88 + 44200 = 44288
external:
   testGasEstimation(): infinite

Similarly array.push(1); estimates to infinite gas.


texts:
I write a simple contract to test my Parity jsonRPC.
Here is my contract:

pragma solidity ^0.4.4;

contract test01 {
  string key;
  string name;
  function test01() {
    // constructor
  }
  function readKey(string p) constant returns(string) {
    key = p;
    return key;
  }
  function readName(string p) constant returns(string) {
    name = p;
    return name;
  }
}

I read some document and know that I should use the first 4 bytes of function name to call a function.

I write it on Remix so that I can get the function bytes directly.
Just as this picture show:

So I use the jsonRPC eth_call to call the functoin readKey. And put the parameter behind the four bytes.

Just like this command:

curl --data '{"method":"eth_call","params":[{"data":"0x19efb2b30000000000000000000000000000000000000000000000000000000000000005"}],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST 10.4.20.69:8540

But it just return {"jsonrpc":"2.0","result":"0x","id":1}

And I change some other parameters. But it still return 0x. I don't understand why. Maybe because I don't call jsonRPC in a correct way? Thanks!


texts: How can I send an Anonymous event (In ABI, anonymous==true) in Solidity?

texts:
Here's my contract code, now in the ABI I have an anonymous entry and I'm not sure what is that and how can I emit anonymous event.

pragma solidity ^0.4.24;

contract TestContract {
    event Start(uint start, uint middle, uint end);
    event End(uint start, uint middle, uint end);

    uint one;
    uint public two;
    uint public three;

    function setInitialParams(uint _one, uint _two, uint _three) public {
        emit Start(one, two, three);
        one = _one;
        two = _two;
        three = _three;
        emit End(one, two, three);
    }

    function () public {
        revert();
    }
}

Thought maybe it's the anonymous function like fallback but no, here's the ABI of the start event:

{
    "anonymous": false,
    "inputs": [
        {
            "indexed": false,
            "name": "start",
            "type": "uint256"
        },
        {
            "indexed": false,
            "name": "middle",
            "type": "uint256"
        },
        {
            "indexed": false,
            "name": "end",
            "type": "uint256"
        }
    ],
    "name": "Start",
    "type": "event"
}


texts: Dapp design to handle delay in callback response from Oraclize

texts:
In my dapp design I am receiving few user inputs via a form and passing them to a smart contract. Inside the smart contract I am using Oraclize service to timestamp the user inputs. Its a known fact that callback from Oraclize (I am using Wolframalpha) takes a few seconds to send back results which in my cases at times have went up to 30 seconds on few occasions.

Inside my dapp (created using Javascript) how can make the control stay on the form page till response from callback is received and then release notification on the page that transaction is successful.
Right now my Javascript logic goes ahead and display the success message whereas in the backend the smart contract is still awaiting callback response from Oraclize.

function saveToBlockchain(params) {
    contract.deployed().then(function(i) {
    i.savedetails(
       params["title"],params["remarks"]
        {
        from: web3.eth.accounts[0]
        }
      ).then(function(f) {
        $("#msg").show();
        $("#msg").html("Transaction completed successfully!");
     });
   });
 }

Please suggest how to implement this type of logic in the dapps.


texts: How to pass arguments of contract constructor in EVM?

texts:
In geth console, I know I can pass arguments via new.

However if I just wanna use evm, how should it be done?

For example,

contract SetNumber {
    int public number;
    function SetNumber(int _number) {
        number = _number;
    }
}

How should I pass _number in evm?

I thought it might be by using --input

But I've checked the bytecode, there's no keccak256 of SetNumber(int256) in it.


texts:
I have been reading about RSK lately and was wondering about the compatibility and possibilities, so I wanted to ask for some basic info in case there's someone more knowleadgable.
I have a smart contract running on the Ethereum network. The contract is based on the ERC20 standard. So, this smart contract, with its setup today, would it be possible to make it use the RSK network instead of Ethereum?
If yes, what could be the pros and cons? Eg. cheaper/faster transactions.


texts:
const DManage = new web3.eth.Contract(myABI, '0x9420D0904B2F696f8612239e5a507A86B5dA1b6a');
DManage.events.allEvents()
.on('data', (response) => {
    console.log(event);
})
.on('changed', (response) => {
    // remove event from local database
})
.on('error', console.error);

When I run this, the code executes without any errors. Why doesn't it go "daemon" mode? Shouldn't it listen to future events?

How can I get the web3 event listner (code above) run as a daemon? So that each time a event is emitted it will execute some code.


texts: Efficient way to use selfdestruct() as safe ether transfer option?

texts:
I have been getting into mitigating reentrancy issues and safe ether transfer recently and have come up with the following 'safe transfer' code.
Workflow:

deploy contract Foo
send ether to Foo
execute function safeTransfer specifying the destination address and value in wei

pragma solidity ^0.4.11;

contract Interface {
    function pay();
}

contract Foo {

    function safeTransfer (address _to, uint256 _amount)
    {
        Bar a = new Bar(_to);
        a.transfer(_amount);
        Interface b = Interface(a);
        b.pay();
    }

    function () payable {}
}

contract Bar {

    address payee;

    function Bar (address _payee)
        {
            payee = _payee;
        }

    function () payable {}

    function pay ()
        {
            selfdestruct(payee);
        }
}

At ~150k gas this is rather expensive but it works. I am aware of the pull payment best practise but would much prefer a convenient automated payments method. Any thoughts on how to potentially optimise this idea for use as payment option in a contract?


texts: Difference between byte and uint8 datatypes in solidity

texts:
I want to understand if there is a difference between byte data-type and uint8 in solidity ?
Thanks


texts: If I am using Infura Node interact with smart contracts. And I want to build/setup web3 apis on a ubuntu machine on AWS. Do i need to install truffle on that machine or just node.js and web3 is enough?


texts:
> web3.eth.getCompilers(function(err,req){if(!err)console.log(req);else console.log(err);});

undefined

  Error: METHOD_NOT_FOUND: The method being requested is not available on this server
      at Object.InvalidResponse (/usr/local/lib/node_modules/ethereum-console/node_modules/web3/lib/web3/errors.js:35:16)
      at Object. (/usr/local/lib/node_modules/ethereum-console/node_modules/web3/lib/web3/requestmanager.js:86:36)
      at /usr/local/lib/node_modules/ethereum-console/node_modules/web3/lib/web3/ipcprovider.js:66:44
      at Array.forEach (native)
      at Socket. (/usr/local/lib/node_modules/ethereum-console/node_modules/web3/lib/web3/ipcprovider.js:50:47)
      at emitOne (events.js:96:13)
      at Socket.emit (events.js:188:7)
      at readableAddChunk (_stream_readable.js:176:18)
      at Socket.Readable.push (_stream_readable.js:134:10)
      at Pipe.onread (net.js:551:20)


texts: Problems subscribing to infura via websockets

texts:
So I have a dapp that includes a node server, which I have got to work successfully using ganache, using this line:

web3 = new Web3(new Web3.providers.WebsocketProvider('http://127.0.0.1:8545'))

I have deployed my project to ropsten and would like to use infura for that, so I changed the code to:

web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/v3/PROJECTID'))

Obviously I did use my actual projectID. But I get this error: " UnhandledPromiseRejectionWarning: Error: connection not open". This is the same error I get when I use my localhost URL but forget to start ganache.

I know that my infura is set up properly because I am able to successfully migrate my project using truffle using the "https://ropsten.infura.io/v3/PROJECTID" endpoint.

As a test I tried to connect via http instead of wss, ie using this line:

web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/PROJECTID'))

and this gives me a DIFFERENT error: "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'returnValues' of null"

Wat do? I'm using my node server to listen for events, so I'm not sure if I can use http even if it did work- I believe that I need to use websockets for events.


texts: What are those multiple transactions in the transaction pool?

texts:
I am running geth. Via txpool.content.pending I am looking at the transactions that my node currently sees. It gives me a bunch of transactions by their transaction hash (I think), in the below example I think the transaction has is 0xea674fdde714fd979de3edf0f56aa9716b898ec8. This transaction has two child objects and I would like to know what those are. I am talking about 214823 and 214824. What are those indices and why are there two transaction objects under the same hash? nonce, to and value are different, hence I am wondering why those would show up under the same transaction hash.

0xea674fdde714fd979de3edf0f56aa9716b898ec8: {
    214823: [{
        blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
        blockNumber: null,
        from: "0xea674fdde714fd979de3edf0f56aa9716b898ec8",
        gas: "0x15f90",
        gasPrice: "0x4a817c800",
        hash: "0xf600f6000087513137182f9aee222618bb813e17cd1c550e710bfe532fc6c353",
        input: "0x",
        nonce: "0x34727",
        to: "0xd3642cbc286df002d4bba68f4dcdc00d19ccd553",
        transactionIndex: null,
        value: "0xde1a377aa686c6c"
    }],
    214824: [{
        blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
        blockNumber: null,
        from: "0xea674fdde714fd979de3edf0f56aa9716b898ec8",
        gas: "0x15f90",
        gasPrice: "0x4a817c800",
        hash: "0x588bdf42eaf5e049c3a098be2104a7c5c65495154a5cacdb0161db158716ef0d",
        input: "0x",
        nonce: "0x34728",
        to: "0x4fed6e010dcdc0bf50c0cbc98ed33f1991b172da",
        transactionIndex: null,
        value: "0xde79cc181013590"
    }]
  }


texts: Error: Documented parameter "{uint" not found in the parameter list of the function on Solidity 0.4.11

texts:
I am trying to compile the Gav Wood's wallet on the latest Solidity compiler. Looks like the latest Solidity compiler has some issue with the code I do not totally understand. I'd like to know how to fix code or the compiling process.

I am getting error:

        Error: Documented parameter "{uint" not found in the parameter list of the function.
contracts/Wallet.sol:358:13: Warning: Return value of low-level calls not used.
            _to.call.value(_value)(_data);
            ^---------------------------^

The related code is:

    // first, take the opportunity to check that we're under the daily limit.
    if (underLimit(_value)) {
        SingleTransact(msg.sender, _value, _to, _data);
        // yes - just execute the call.
        _to.call.value(_value)(_data);
        return 0;
    }


texts: How to derive the private key from UTC file?

texts:
I want to implement a client-side wallet where the transaction is generated and signed on the browser, and sent to the server which is running a geth node. Apparently ethereumjs-tx does what I want for the client side, but it needs the private key for signing.

Therefore, I want to ask the user to supply their UTC key file and their password on the browser, and then, -I guess- I need to derive their private key with these two pieces of information. But I have no idea how to do that.

I found helpeth that extracts the private key from a UTC file, but can I use this in browser JavaScript? Or are there other solutions for this?

Thanks,


texts: Ganache VM Exception while processing transaction: out of gas

texts:
I am deploying my contract using web3 by taking values (just copy paste) from Etherscan (i.e. abi, contract creation code, etc.) and then deploy my contract on Ganache (gui). When i run the my code through node deploy.js following error displayed (However, on Ganache GUI, that command shows that my contract has been deployed and also shows its address).

Here is my code:

 async function deployWithCreationCode(){

     var contract = new web3.eth.Contract(abi);
    var dc = await contract.deploy({data: crCode})
          .send({
              from: account1,
              gas: 6721975, // i cannot assign more gas above gas limit of ganache... is it possible to increase this limit.... ?
              gasPrice: '30000000'
          });
return dc._address;

}

Here is my error:

UnhandledPromiseRejectionWarning: Error: Returned error: VM Exception while processing transaction: out of gas

Note: If size of my contract creation code is less, then  no error at all.


texts: As I understand,  .eth domain zone is a smart-contract. Does the owners of this smart contract delete record about .eth domain?


texts: Replaying Ethereum transactions, how could I extract the "from" account key from an existing transaction

texts:
I'm trying to replay transactions that exist in one chain on another.
I can replicate all transaction arguments that are available through eth_getTransactionByHash, but now need to sign the transaction. How do I extract the signing information from the committed transaction so that I'm able to resubmit with eth_sendRawTransaction.
Also welcome responses in web3.py, web3.js, ethers.js or any other preferred json-rpc SDK.
Existing code using web3.py that doesn't work:
tx = fallback_web3.eth.getTransaction(individual_tx_hash)
transaction = {
  "from": tx["from"],
  "to": tx["to"],
  "gas": tx["gas"],
  "gasPrice": tx["gasPrice"],
  "value": tx["value"],
  "nonce": tx["nonce"],
}
if "data" in tx:
  transaction["data"] = tx["data"]
w3.eth.sendTransaction(transaction)


texts: How do I import my coinbase wallet to metamask

texts: I just installed metamask and when I click import it asks for a private key. I have no idea what that is from my coinbase wallet. All I see in my coinbase wallet is my 12 word phrase, where do I find the private key of my coinbase wallet?


texts: Invalid implicit conversion from contract to address

texts:
pragma solidity 0.5.10;

contract ERC20 {
    function totalSupply() public view returns (uint supply);
    function balanceOf(address _owner) public view returns (uint balance);
    function transfer(address _to, uint _value) public returns (bool success);
    function transferFrom(address _from, address _to, uint _value) public returns (bool success);
    function approve(address _spender, uint _value) public returns (bool success);
    function allowance(address _owner, address _spender) public view returns (uint remaining);
    function decimals() public view returns(uint digits);
    event Approval(address indexed _owner, address indexed _spender, uint _value);
}

contract TestContract{

    address payable public owner;

    constructor() public {
        owner = msg.sender;

    }

    function depositToken(address _addr) external
    {
        ERC20 tokenContract = ERC20(0x722dd3F80BAC40c951b51BdD28Dd19d435762180);

        require(tokenContract.allowance(msg.sender,this)>0);

        uint tokenAmount = tokenContract.allowance(msg.sender, this);
        require(tokenContract.transferFrom(msg.sender, this, tokenAmount));

    }
}

When i Compile this contract return
TypeError: Invalid type for argument in function call. Invalid implicit conversion from contract TestContract to address requested. require(tokenContract.allowance(msg.sender,this)>0); ^--^


texts: Can an Ethereum contract autonomously and securely manage a bitcoin wallet

texts:
I'm wondering if it's possible to have an Ethereum token that is backed by pooled bitcoin (and therefore has 1:1 value parity with Bitcoin) in a trustless way.  With tokens issued and destroyed as bitcoin is deposited and removed.

I'm assuming the answer will be no, because the contract would need to be able to issue the private key(s) whenever bitcoin is withdrawn, and that would seem to require a trusted party to provide a key to 'unlock' the contract to do its thing.

But I'm unclear on Ethereum capabilities - maybe the black-box of the contract can 'know' the (hardcoded?) encrypted private key(s), in such a way that it can output a valid, signed bitcoin transaction, only upon contract conditions relating to the contract token being met?

(What I'm really wondering here - is is there a way to subvert the bitcoin scaling issues, by having a trustable, trustless ethereum token, that is almost like a bitcoin sidechain, guaranteed to have 1:1 pegging to bitcoin value, by being provably backed by bitcoin holdings equal to the tokens in circulation.)


texts: others accessing setApprovalForAll ERC721

texts:
While I was skimming through open zeppelin's ERC721BasicToken.sol I came across a problem.

When setting the approval of a given operator

  function setApprovalForAll(address _to, bool _approved) public {
    require(_to != msg.sender);
    operatorApprovals[msg.sender][_to] = _approved;
    emit ApprovalForAll(msg.sender, _to, _approved);
  }

I've noticed that the visibility of the function is public. Doesn't it mean that anyone can modify an operator which was previously set before?

For example, I would create a contract that can control over a deployed ERC721Token contract.

contract TokenAccessor {
  ERC721Token public nft;

  constructor(address _tokenAddress) public {
    nft= ERC721Token(_tokenAddress);
  }
}

And from the migrations script, I would pass in the address of someone's deployed ERC721 token contract.

module.exports = function (deployer) {
  deployer.deploy(TokenAccessor, "0x......")
    .then(() => {

This way, I think anyone can access setApprovalForAll to change the operator?

contract TokenAccessor {
  ERC721Token public nft;

  constructor(address _tokenAddress) public {
    nft= ERC721Token(_tokenAddress);
  }

   function changeOperator() public {
    nft.setApprovalForAll(msg.sender, true);
   }
}


texts:
What is topics[0] in Event logs?
Here's a snapshot from etherscan.io


texts: How to extract private keys from Ethereum Wallet?

texts:
How to extract private key of an account from Ethereum Wallet on Linux? Please specify the exact filesystem locations.

I need private keys both for the main network and for the Ropsten test network.


texts: Is there a way to test (if you still know) your Mist wallet password without making a transaction?


texts: Deploy gas issue for require reason string

texts:
I found a strange case and didn't find out why.
...
modifier onlyMaster() {
        require(msg.sender == master || msg.sender == developer, "caller is not the master");
        _;
    }
...

Deploy Gas amount: 1183967
I tried to delete some words for saving deployment gas as follows.
...
modifier onlyMaster() {
        require(msg.sender == master || msg.sender == developer, "caller is not master");
        _;
    }
...

Deploy Gas amount: 1186943
But the gas amount was increased against my prediction like this.
Other omissions decreased the gas amount but only this omission increased the gas amount.
So I created a very simple smart contract and tested it.
contract Demo {
    address public master;
    uint256 public callTimer;
    function setMaster(address master_) external {
        master = master_;
    }

    function demoFunction() external{
        require(msg.sender == master, "caller is not the master");
        callTimer++;
    }
}

I removed "the" and the deploy gas amount was decreased just I thought.
I am sorry that I can't provide the whole code, but has anyone ever had a similar experience?
What's the reason?
FYI, the "caller is not the" string is not repeated in the smart contract.


texts: Can a miner compromise an EVM that runs a smart contract?

texts:
For example, there is a private storage variable which cannot be seen by any user during the execution of the smart contract.

When a miner runs the smart contract in a local EVM, can it infer the value of the private variable by, for example, monitoring the memory?

(Suppose the miner machine is completely malicious, including the kernel and the user space.)

Thanks a lot.


texts: One contract for all transactions or an instance of a contract for each transaction?

texts: Let's say we have a contract with functions for an online store built on top of the Ethereum blockchain. Whenever a transaction between buyer and seller happens, are new instances of that contract created for each transaction or are all transactions using the same contract?


texts: Sending ethers with mocha.js and truffle might result in larger sums than intended

texts:
Good day,

I have a contract General and a library GenLib.

library GenLib{
    event MoneyIn (address _from, uint256 _amount);
    function moneyIn() {
       MoneyIn(msg.sender, msg.value); <- Only call the event MoneyIn()
   }
}

contract General{
    function getMoney () payable{
        GenLib.moneyIn();
   }
}

Now the weird part, when I'm trying to send money to the General contract using the getMoney function, the amount that is actually transferred is TWICE the amount that is specified.

That's the JS file I'm using to check my contract:

var Gen   = artifacts.require("General");

contract('Gen', function(accounts) {

  var user = accounts[0];

  var valueP2C      = web3.toWei(2, "ether");

  it("Deploy Gen contract", function(){
    return Gen.deployed().then(function(instance){
      gen = instance;
    });
  });

  it("Gen account is empty", function(done){
    web3.eth.getBalance(gen.address, function(err, res){
      done(assert.equal(res.valueOf(), 0, ""));
    });
  });

  it("Use account is full", function(done){
    web3.eth.getBalance(user, function(err, res){
      userAmount = res.valueOf();
      done(assert.equal(res.valueOf(), 0, ""));
    });
  });

  it ("Send money from user to gen", function(done){
    gen.getMoney({from: user, value: valueP2C}).then(function(res){
        done(assert.notEqual(res, null, ""));
      });
  });

  it("Gen recieved money", function(done){
    web3.eth.getBalance(gen.address, function(err, res){
      done(assert.equal(res.valueOf(), valueP2C, ""));
    });
  });

  it("User account is P2C lower", function(done){
    web3.eth.getBalance(user, function(err, res){
      done(assert.equal(res.valueOf(), userAmount - valueP2C, ""));
    });
  });
});

And the final results:

✓ Deploy Gen contract
✓ Gen account is empty
✓ User account is full
✓ Send money from user to gen
1) Gen received money
> No events were emitted
2) User account is P2C lower
> No events were emitted

expected '4000000000000000000' to equal '2000000000000000000' <-TWICE THE AMOUNT
expected '87641250800000000000' to equal 89643554700000000000

Another piece of information that might be useful is that whenever I remove the call to the external library, everything works just fine.

I'm baffled by this weird behavior and would appreciate any help or insight you might have.


texts: Is there any reliable source for hourly data for Ethereum dating back to 2017? The poloniex API only provides me with daily data - https://poloniex.com/public?command=returnChartData&currencyPair=USDT_ETH&start=1480360203&end=9999999999&period=14400


texts: Is there a maximum number of entries for a mapping?

texts:
In many contracts, notably voting, there is a mapping of the kind mapping(address => bool) voted;

How many voters can be registered in that way? is there a size limit? will the contract need more and more gas for each query until it reaches the maximum gas limit?

what would happen if there are 100 million voters for example?


texts: The method eth_sendTransaction does not exist/is not available - web3.py

texts:
I am trying to send data to the contract, but I am getting the following error:
The method eth_sendTransaction does not exist/is not available

This is the code:

from web3 import Web3

web3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/9fe6f0a016494dfeb4cecd7d1c98431a"))

from web3.middleware import geth_poa_middleware

web3.middleware_onion.inject(geth_poa_middleware, layer=0)

print(web3.eth.blockNumber)

x = web3.isAddress('0xacb0ceacb13e786644f0ab21aa044032ae925874')
print(x)

abi = '''
   ...
      '''

address = Web3.toChecksumAddress('0xacb0ceacb13e786644f0ab21aa044032ae925874')

lucas = '0x690809206b73994282910F1740a729a89aF4beCa'

myContract = web3.eth.contract(address=address, abi=abi)
key = myContract.functions.storeData([1,4]).transact({'from' : lucas})

print(key)

addedData = myContract.functions.getData(key).call()
print(addedData)

The above code can connect to the network rinkeby normally, but cannot perform the transaction. The storeData method takes an array and returns an uint which is key and is working normally in Remix.

I'm using Metamask.


texts: Why does it cost 21000 gas to send a transaction

texts: What is the forumla used to calculate how much gas needs to be used? are the values just determined arbitrarily or was there some kind of benchmarking?


texts: Can't get geth to connect to own fullnode via --bootnodes param

texts:
I'm running a full node with LES protocol enabled which I want my light clients to connect to and sync from.

I tried to do this by starting the light client with geth --light --bootnodes <my_enode>. Doesn't connect. With --verbosity 4 set, it gives me
DEBUG[08-23|16:05:24] Bad packet from <my_ip>:<my_port>: rlp: too few elements for discv5.pong

I also tried with geth --light --bootnodesv4 <my_enode>. Still doesn't connect. In this case there's no debug entry.

When attaching to the light client node and issuing `admin.addPeer(), it successfully connects.

Am I misunderstanding what the --bootnodes param is for?
If not this way, how can I tell geth to connect to my full node on startup?

Update:
I just noticed that adding manually with admin.addPeer doesn't always work, probably because the full node has already maxPeers connected. Is it possible to configure the full node such that a given list of nodes is always allowed to connect (e.g. via reserved slots or higher priority)?