texts: initialise array of struct inside a new struct

texts:
Following up on the question of 2d array of different types: 2d array of different types?

How would one go about initializing a new array of structs (Vote) when creating a new struct (Project)

pragma solidity ^0.4.25;

contract Votinggame{

       struct Vote {
          address voter;
          string comment;
      }

        struct Project{
            int id;
            string name;
             int votes;
            Vote[] vote;
        }

        Project[] public projects;
        int idcounter=-1;

     function addNewProject(string name) public {

             Project memory newProject = Project({
                 id:idcounter+1,
                 name:name,
                 votes:0

                 // How to initialise new vote array of struct Vote inside Project struct ??
                 // vote: new Vote[](0) -> this is not working "UnimplementedFeatureError: Copying of type struct HotOrNotCrypto.Vote memory[] memory to storage not yet supported."

             });
           idcounter=newProject.id;
           projects.push(newProject);
        }

      function vote(uint index , string comment) public {
        Project storage project = projects[index];
        project.votes++;
        Vote memory v;
        v.voter = msg.sender;
        v.comment = comment;
        project.voters.push(v);
      }
    }
 function getProjects() public view returns (uint){
         return (projects.length);
       }
}

Also to extend on this how would one go about displaying vote Array of Vote struct in React. At the moment I'm displaying projects Array of a projects struct using .fill().map()

  static async getInitialProps(){

    const getProjects = await Contract.methods.getProjects().call();
    const projectsList = await Promise.all(
    Array(parseInt(getProjects))
    .fill()
    .map((element, index)=> {
      return Contract.methods.projects(index).call()
    }));
  const sorted_projects = _.orderBy(projectsList, ['votes'], ['desc']);

   return { sorted_projects};

  }

and then render new table row for each struct element like so:

  renderRow(){
    return (

      this.props.sorted_projects.map((sorted_projects,key)=>{
      return <RequestRow
        id= {key+1}
        key ={key}
        sorted_projects ={sorted_projects}
      />;

  }));

I guess this will be sort of similar with the difference that I would have to provide which project index I want votes array to display


texts: How connect library to smart contract from external resources?

texts:
Now I connect library SafeMath.sol in local project.

pragma solidity ^0.4.15;
   import './ERC20.sol';
   import './SafeMath.sol';

How can I connect SafeMath.sol from external(non-local) resources or other contracts?


texts:
I'm trying to deploy a smart contract (7 nodes sample from Quorum) using web3j.
It fails at get() to get the contract wrapper object. If I check the logs, a new transaction will show up, but if I call any contract function, it will give me a null pointer exception. My code looks like this:

    String deployeraccount = "0xed9d02e382b34818e88b88a309c7fe71e65f419d";
    String privfor = "QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc=";

    try {

        Quorum quorum = Quorum.build(new HttpService("http://localhost:22000"));

        ClientTransactionManager transactionManager = new ClientTransactionManager(
                quorum, deployeraccount, Arrays.asList(privfor));

        BigInteger gasPrice = BigInteger.valueOf(30000);
        BigInteger gasLimit = BigInteger.valueOf(100000);
        BigInteger initialWeiValue = BigInteger.valueOf(0);
        Uint256 initVal = new Uint256(BigInteger.valueOf(0));

        System.out.println(">> Before deploy");

        Future<Simplestorage> ft = Simplestorage.deploy(    quorum,
                                                            transactionManager,
                                                            gasPrice,
                                                            gasLimit,
                                                            initialWeiValue,
                                                            initVal     );
        System.out.println(">> deploy");

        while (!ft.isDone()) {
                Thread.sleep(500);
        }

        System.out.println(">> after wait");

        Simplestorage ss = ft.get();

I already tried changing the gas value, but still got the same issue. Thanks.


texts:
After following the instructions on rinkeby for joining the network, I cannot seem to get more than a single peer that also wont get me up to date. Eventually my node kicks that peer off, and then I am isolated.

What is the issue, and how can I troubleshoot/diagnose it?

P.S: no issues syncing to main-net

Edit:
After a while it randomly seems to have have managed to finish syncing, and I now have 3 peers. But my transactions dont reach the network. Geth states that it was submitted, but etherscan doesnt show anything. The stats show my pending transactions seem to reach the network, but nada ;-;

INFO [04-26|01:19:58] Submitted transaction                    fullhash=0x7ffefbc0a02732ea31e9fdbf57f4ad7248113dda2d591d713ecdcd1fc8831e25 recipient=0x55a717fe6247a81b9c1c051364564713f48eefb9


texts: Truffle re-deploy unchanged contracts on every migrate

texts:
On every truffle migrate truffle deploy contracts even if they are not changed.
although it doesn't re-compile
Truffle v5.0.5


texts:
Can anyone help me fix this problem?
I get 'txHash: undefined' error in terminal
var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/.....')

const account1 = '0x4e8143b70aC257BC26......................'
const account2 = '0x7184a5934B9B36E210......................'

const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1, 'hex')
const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2, 'hex')

web3.eth.getTransactionCount(account2, (err, txCount) => {

// Build a transaction
const txObject = {
    nonce: web3.utils.toHex(txCount),
    to: account1,
    value: web3.utils.toHex(web3.utils.toWei('1', 'ether')),
    gasLimit: web3.utils.toHex(21000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}

// sign a transaction
const tx = new Tx(txObject)
tx.sign(privateKey2)

const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')

// Broadcast the transacation

web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    console.log('txHash:' , txHash)
})
})


texts: how to get the status of a transaction which is not mined and pending

texts:
I used the following code to send a transaction and get transaction status.However, sometimes the transaction is not minded at all. But the transactionReceipt get the same value "NULL" for both of the "not mined" and pending status.

Is there a way to get different values for these 2 status so we can resubmit the transaction when the status is not mined??

EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get()
EthGetTransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(transactionHash).sendAsync().get();


texts: Resources of a miner's reward in Ethereum?

texts:
To compensate the miner who could solve the PoW as the first one, they will receive some coins as a reward for keeping  them motivated due to the costs related to mining process (electricity and hardware).

Does this reward include both following parts?

Newly minted coins.
Transactions fees included in winner's block.

If yes, the second part seems logical and the coins can be provided simply through the account of the participants who submitted the transactions.

However, concerning the first part i.e. "newly minted coins",

(a) What is the reason to add this complementary reward?

(b) How are those new coins minted? And how to calculate the amount of those new coins?


texts: Does anybody knows how to write an API inside a Truffle application?


texts: How to deploy contract into local running node using solidity browser?

texts:
I am running a local ethereum node and I did unlock an account.
Now I want to use the solidity browser to deploy that contract, but when I switch to the web3 provider deploy option and I press the Create button at the address 'http://localhost:8000' all I see is an error that says 'Error: account is locked'. I don't know why and how is this working?

Also what is the easiest way to deploy an smart contract into a local running node?


texts: What's the default value for the second parameter of eth_getBalance() if not supplied

texts: It's not clear in the documentation, but this function works if the 2nd parameter is not passed. What's the default if not passed?


texts:
I want to convert string data to address type.I know that we can directly use address type in the parameters, but for some reason I want to convert it from string to address.
 sample code

function check(string _address,string _name,string _password) public returns (string)
{

    address add=address(_address);
   if(!checkUser(add))
    {
        Useraccnts.push(add)-1;
          Users  storage myuser=users[add];
          myuser.name=_name;
          myuser.password=_password;

        return "true";
    }
    else
    {
        return "false";
    }

}

I got JSON-RPC: internal error while executing this function. so I want to check whether it would be resolved if I change the address to a string. If you know how to resolve the JSON-RPC error please help me out.

registerUser: function() {
    var self = this;
    var acc=account;
    var name=document.getElementById("name").value;
    var password=document.getElementById("password").value;
    var meta;
    CoinFlipper.deployed().then(function(instance) {
        meta = instance;
        return meta.check.call(acc,name,password).then(function (value) { },

I'm using the above function in app.js.

  Error: Invalid JSON RPC response: {"id":6,"jsonrpc":"2.0","error":{"code":-32603}} at Object.InvalidResponse (app.js:10374)


texts: ERC20 who manages all tokens? EOA or contract?

texts:
Let's say I have a platform that gives incentives to users as ERC20 tokens when the users wrote some good articles.

At this point, from which account ERC20 tokens should be transferred to users?

Is it from the EOA owner address that owns all ERC20 tokens? or should it be from the ERC20 contract address?

In the former case, I think it'd be very tedious since EOA owner address needs to go through approve() & allowance()steps for each case and this is not realistic (ex: 1,000 cases per day). Also, EOA has to pay for gas fees.

In the latter case, beneficiary users can just call a method to receive tokens and they can pay for gas fees which is more realistic to me. For example,

contract IncentiveContract {

    function claimIncentives(uint256 tokens) public {
        if (condition) {
            MyToken instance = MyToken('address of MyToken');
            instance.transfer('beneficiary address', tokens);
        }
    }
}

If my approach for the latter case is correct, should the ERC20 token owner address send all of his tokens to contract address so the contract can manage all these?


texts:
I have the following contract code:

contract ShippingOrder{
    address public oOrigin;
    address public oShipper;
    address public oCarrier;
    address public oReceiver;
    mapping (address => uint) public obalances;
    event Bal (uint balance);
    function ShippingOrder() {
        obalances[tx.origin] = 200;
    }
    function getBalance(address sender) returns(uint) {
        Bal(obalances[sender]);
        return obalances[sender];
    }

the getBalance function runs and returns a balance, but the Bal event never emits...


texts: Smart contract copying code beyong code length

texts:
I've seen a couple smart contracts (eg the contract decompiled in this answer) use this pattern:
Code[Code.Length:Code.Length+x]
This surprised me because I would expect Code.Length to mark the end of Code. What would the result of this expression be and what could the purpose be for using this pattern?


texts: Was the initMultiowned adversary breaking the law

texts:
In recent events an adversary obtained 31M in ether by exploiting a bug in Ethereum contracts. Taking over ownership of the wallet.

Since the contracts are entirely defined in code, this exploit was within the definitions of the contract. The question is therefore:
Is the adversary punishable by law?


texts: How to delete or remove a key from mapping?

texts:
I have the following map:

mapping (string => Category) categoryMap;

Let's say the key was mistyped, so I want to remove the key and add a correct one, how would I do that?

Function would be

  function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_oldCategoryLabel].label = _newCategoryLabel;
    Category tmpCategory = categoryMap[_oldCategoryLabel];
    // Delete Key
    // create new key from _newCategoryLabel
      }

Thanks

Edit:

Here is what I was doing:

  function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_oldCategoryLabel].label = _newCategoryLabel;
    Category tmpCategory = categoryMap[_oldCategoryLabel];
    delete categoryMap[_oldCategoryLabel];
    categoryMap[_newCategoryLabel] = tmpCategory;
  }

Category struct

  struct Category {
    string label;
    uint percent;
    address[] userList;
  }


texts: What does it mean when a function is called in the head of constructor() function?

texts:
I'm reading through some smart contracts and I noticed functions being called in the head of the constructor function, like MarginAdmin() in the following example.

constructor(address vault, address proxy)
    public
    MarginAdmin()
{
    state = MarginState.State({
        VAULT: vault,
        PROXY: proxy
    });
}

In this case, MarginAdmin is another solidity contract that is being imported into this file. What does this mean when a function gets called like this in the head of constructor function?


texts: Is there any way I can check my .json key works without importing the wallet?

texts:
Could I do this on an offline machine perhaps? I'd like to double check my key works without exposing myself to technical mess ups that would lead me to losing all my ether.

Thanks!


texts: How to configure Azure STRATO Blockchain LTS with Visual Studio?

texts:
I'm learning all about Blockchain but I wanted to make an example of smart contract, i followed this tutorial, but I can't find much about how to integrate Azure Strato Blockchain with my application in Visual Studio, I read that I need to change the configuration file "Config.yaml" and put my public IP with the /strato-api/, but it does not work, I'm asking for tutorials that works with Azure STRATO Blockchain because I can't find any.

This is the error im getting by deploying the contract.


texts: Call derived function from base contract

texts:
I have the following smart contracts:

pragma solidity ^0.4.11;

contract base {
    uint public v;
    separate public mySep;

    function base() {
        mySep = new separate();
    }

    function f() {
        v = 1;
    }

    function sepCall() {
        mySep.doStuff();
    }
}

contract derived is base{
    function f() {
        v = 2;
        super.f();
    }
}

contract separate {
    derived myBase;

    function separate() {
        // constructor expects to be called by base or derived
        myBase = derived(msg.sender);
    }

    function doStuff() {
        myBase.f();
    }
}

I only create an instance of derived which I expect to do the following:

call base constructor base()
base constructor creates instance mySep of separate contract

Now I am calling sepCall of that derived instance which I expected to do the following:

it calls the doStuff function of the separate contract.
the doStuff calls the overridden function f of the derived contract (since that's its type)

The last point is not happening, after calling sepCall of the derived instance its value v is 1 and not 2 which it would be if the overridden function of derived would have been called.

This might not be solidity related but a general JS issue but I'd like to find out how I could make sepCall invoke the overridden function f that sets v to 2.


texts: Determine if the contract transaction came from another contract or wallet account

texts:
Let's say, I've a function defined on contract and anyone can call that function(a user, a different contract etc.).

Is there a way to identify within that function if it is a contract address or a user address in solidity? And if it is a contract, is it possible to identify the type of the contract?

Thanks in advance!


texts:
If I create a token, and then want to distribute it to 1000 people, I am worried about the gas price of those transactions. Which is why I wanted to analyse the different options for distributing and their inherent costs.

option 1: function in token that distributes to an array of users

function distributeToken(address[] addresses, uint256 _value) onlyOwner {
     for (uint i = 0; i < addresses.length; i++) {
         balances[owner] -= _value;
         balances[addresses[i]] += _value;
         Transfer(owner, addresses[i], _value);
     }
}

source: Distribute token to multiple address

ELABORATIONG ON OPTION ONE: is it possible to use parameters with an array of 1000 different addresses? That would be a massively large parameter and I'm curious as to what the gas price would look like.

option 2: using an exchange

This option is very restrictive however. It would allow anyone to buy the coins, and I don't necessarily want them to be bought but given away for free to specific users.

QUESTIONS

Are there other options people are aware of?
Which option would be most suitable and cost the least amount of gass?

DIFFERENCES BETWEEN THE LINKED DUPLICATE QUESTION AND THIS ONE:
( How to transfer tokens to bounty participants? )

The questions have noticeable differences

The details that are being discussed.
I also have 2 specific questions at the end which are not identical to that

while the question linked that is similar asks:

What is best practice to send ERC20-compliant tokens to bounty participants?

It doesn't provide the specific criteria for what best would refer to, while I do, and I also ask the other available options to make a comparison with. Even though they have similarities, they are not the same.


texts:
This is more of a general "blockchain" question and not specific to Ethereum so if I'm off topic here I would appreciate it if you could direct me to a more relevant stackexchange maybe.
On PoW-based blockchains, participants mine for unique hashes with a specific number of leading zeros etc. (there's probably more to it but it's irrelevant to my question).
But I'm wondering whether a blockchain could ask participants to mine for something else. Think of it as a game, a challenge. Let's say a string of characters (bytes, a file whatever..) "hidden" inside the blockchain. Mining for that string should (as in: that's the challenge) be as hard as mining for these unique hashes.
My questions are the following:

Is it possible?
How/Where would you hide it (think of a "custom"/theoretical blockchain or even the Ethereum if it already allows for something like this)
How would you allow users to mine for it without giving too much away thus making it easy for them to hack their way around the mining?

When it comes to mining for unique hashes there is nothing to hide because you're trying to generate a random sequence of characters that doesn't already "exist" somewhere. But in my hypothesis, the "hash" needs to necessarily pre-exist "somewhere" but the user shouldn't have access to it, only "tools"/hints to mine for it..
Thank you in advance for your help :-)
I'm not a blockchain expert (I am a front-end Js developer) so I'm looking for more "high-level" answers :-)


texts:
When i use the Ens - Registry Contract to setResolver(), I am getting a bad jump destination.

I am the using the proper namehash of my newly won domain and the "0x1da022710df5002339274aadee8d58218e9d6ab5" proper ENS resolver addr for the resolver address.

I have tried this with 2, 20, and 40 Gwei, same problem every time.


texts:
Fifty days ago I've donwloaded Ethereum Wallet into my computer without letting the wallet to SYNC and download all BLOCKCHAINS because it took about 4-5 days and it is still not synched, anyways I've bought 8 ETH and scanned my  wallet and it's there.

Currently I received a computer which is way better than my own and finally installed the Ethereum Wallet again and synched the wallet at last so I can see my 8 ETH without scanning online.

The problem is when I installed the Ethereum Wallet 50 days back the app requested me a PASSWORD wich I didn't know it will be linked to my main account (I thought it was a password for the ethereum app).

So now in the present day, I have my wallet with all the ether in it but I can not move it to bittrex platform without the password.

The interesting thing is I have written down the passsword but does not match and I think I've a problem of a LOWER UPPER case letter

I only have on a USB the KEYSTORE FILE (UTC-xxxxxxxxxxxx), but I still have the Ethereum Wallet on the laptop if there is any file I might need from it.

Is there any chance that the password I put in my laptop without synching, did not reach the system, so therefore I have no password?

What can I do?


texts: How to take the average of two uint256s without overflowing?

texts:
Say you have two uint256 numbers, x, and y. One way to calculate the arithmetic average between them is this:
function avg(uint256 x, uint256 y) external returns (uint256 result) {
    result = (x + y) / 2;
}

But this doesn't work when the intermediate result x + y does not fit into uint256.
A seemingly better approach is the following:
function avg(uint256 x, uint256 y) external returns (uint256 result) {
    result = x / 2 + y / 2;
}

This doesn't overflow, but it doesn't work when both x and y are odd numbers - the 0.5 remainder is lost twice. Actually, if you'd prefer to round up the result, this doesn't work if either of x or y is an odd number.
How to take the average of two uint256 numbers in Solidity without overflowing?


texts: How to implement the ERC777 token standard?

texts:
Does anyone know how to correctly implement the new ERC777 token standard? I've been trying to create an ERC777 contract (see code below) but keep struggling with a couple of things.

According to the standard, recipient addresses must match the ITokenRecipient interface as returned by an ERC-672 reverse lookup. Any idea how to do this?
There seems to be a fallback interface ITokenFallback that is not mentioned in the standard at all. How does 777 handle fallbacks (e.g. in case foreign tokens are sent to the contract)?
The standard requires the usage of operatorData and userData but doesn't really say what to do with these values. Is it sufficient to include this data in the events that are defined in the 777 interface?

My ERC777 implementation so far:

contract MyToken is EIP777 {

string public name;
uint8 public decimals;
string public symbol;
uint256 public totalSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => bool)) authorizedOperators;

function send(address _to, uint256 _value) returns (bool success) {
    if (balances[msg.sender] >= _value && _value > 0) {
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        Send(msg.sender, _to, _value, msg.sender, null, null);
        return true;
    } else { return false; }
}

function send(address _to, uint256 _value, _userData bytes) returns (bool success) {
    if (balances[msg.sender] >= _value && _value > 0) {
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        Send(msg.sender, _to, _value, msg.sender, _userData, null);
        return true;
    } else { return false; }
}

function operatorSend(address _from, address _to, uint256 _value, bytes _userData, bytes _operatorData) returns (bool success) {
    if (balances[_from] >= _value && _value > 0 && isOperatorAuthorizedFor(msg.sender, _from) ) {
        balances[_to] += _value;
        balances[_from] -= _value;
        Send(_from, _to, _value, msg.sender, _userData, _operatorData);
        return true;
    } else { return false; }
}

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

function authorizeOperator(address _operator, bool _authorized) public {
    authorizedOperators[msg.sender][_operator] = _authorized;
    AuthorizeOperator(msg.sender, _operator, _authorized);
}

function isOperatorAuthorizedFor(address _operator, address _tokenHoler) public constant returns (bool) {
    return authorizedOperators[_tokenHoler][_operator];
}

}

I did some research and stumbled upon YogaToken. However, it uses ERC672 and a more complex implementation of authorizedOperators which adds globallyAuthorizedOperators and a doSend() function. It doesn't implement ITokenRecipient, either.


texts: Implementing security feature on token contract

texts:
I am trying to implement a security feature on a ERC20 Token for the event of a vulnerability on it's code or the solidity core. This feature consists basically in two steps :

First, the owner of the Token contract can freeze the token functions ( transfer, transferFrom, approve...)

Second, a new token with the same features but with its vulnerabilities fixed will be distributed to the vulnerable token holders at a time prior to the vulnerability exposure.

My questions are :

First: Is it a good idea?

Second: How can i fetch all token holder adressess and their balances at any past block ? I have event listeners for critical functions of my token and crowdsale but i don't know how to proceed to get the info i want.

Many Thanks.


texts:
I'm trying to convert a DApp that uses web3.js from JavaScript to TypeScript, but I have encountered a bunch of runtime errors. I'm using Visual Studio Code IDE, and I'm compiling to ES6. I've reduced the project to the smallest code that still has these problems.

Can someone help me fix this? Thanks in advance!

(if I forgot to include some important information, please feel free to comment)

NPM packages:

@types/web3 (version 1.0.12)
web3 (version 1.0.0-beta.36)

Web page:

<script src="system.js"></script>
<script>
System.config({
    baseURL: './out',
    packages: {
        './out': {
            defaultJSExtensions: 'js'
        }
    },
    meta: {
        '*': {
            format: 'register'
        }
    },
});
window.addEventListener("load", (async function(){
    await System.import("init");
}));
</script>

Init.ts:

import Web3 from "web3";

const ABI: any[] = [];
let web3: Web3;
export async function init()
{
    if (typeof (window as any).web3 !== "undefined")
    {
        const injectedWeb3: Web3 = ((window as any).web3 as Web3);
        web3 = new Web3(injectedWeb3.currentProvider); // This line produces the error: TypeError: web3_1.default is not a constructor
    }
    else
    {
        web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
    const myABIinstance = new web3.eth.Contract(ABI);
}
init();

The full stack trace of the run-time error:

TypeError: web3_1.default is not a constructor
init.ts:10
    at /home/jesse/MinimalWeb3Typescript/init.ts:10:16
    at Generator.next (<anonymous>)
    at /home/jesse/MinimalWeb3Typescript/out/init.js:8:76
    at new Promise (<anonymous>)
    at __awaiter (/home/jesse/MinimalWeb3Typescript/out/init.js:4:17)
    at init (/home/jesse/MinimalWeb3Typescript/out/init.js:14:17)
    at Object.execute (/home/jesse/MinimalWeb3Typescript/init.ts:18:1)
    at U (/home/jesse/MinimalWeb3Typescript/system.js:4:8818)
    at /home/jesse/MinimalWeb3Typescript/system.js:4:11430
    at /home/jesse/MinimalWeb3Typescript/system.js:4:11499


texts: Fatal: Failed to read genesis file: open genesis.json: permission denied

texts:
I try to init private network and run this command:
geth init genesis.json --datadir=ethdata/
Also, I try to run the same with sudo
sudo geth init genesis.json --datadir=ethdata/
But the result is no different.
My genesis.json file:
{
   "config":{
      "chainId":0,
      "homesteadBlock":0,
      "eip155Block":0,
      "eip158Block":0
   },
   "alloc":{

   },
   "coinbase":"0x0000000000000000000000000000000000000000",
   "difficulty":"0x20000",
   "extraData":"",
   "gasLimit":"0x2fefd8",
   "nonce":"0x0000000000000042",
   "mixhash":"0x0000000000000000000000000000000000000000000000000000000000000000",
   "parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
   "timestamp":"0x00"
}

chmod numeric value of file:
$ stat -c %a genesis.json
777

ls -alu
total 20
drwxrwxrwx 3 narnik users  4096 Jan 10 23:20 .
drwxrwxr-x 7 narnik narnik 4096 Jan 10 23:18 ..
drwxrwxrwx 2 narnik users  4096 Jan  9 20:15 ethdata
-rwxrwxr-x 1 narnik narnik  525 Jan 10 23:19 file.json
-rwxrwxrwx 1 narnik narnik  525 Jan 10 23:19 genesis.json

Also, I tried to reinstall geth, but this also did not produce the expected results.


texts:
I've been reading about Ethereum and it's fundamentals for a while now. I am familiar with blockchain and secure data concept. Completely secure data is awesome and I find it very interesting. What I am struggling with is trying to find some real life use cases where dApps could make actual difference, where dApps have potential to achieve something completely new. I've found a lot of articles how dApps will change the world but most articles have basic logic errors in them. Can you please give me real benefits of using dApps compared to creating traditional (for example relational) database with proper security? Removing middleman (e.g. middleman between photographer and photo buyer) is not argument because for average Joe it doesn't matter if he/she has to pay fees to Ethereum network or to middleman to process. And after all, he/she has to use some interface and someone has to create that same user interface and program backend logic into dApp. Also average Joe doesn't care if the technology uses some sql or blockchain, he only cares about getting his things done.
Is Ethereum smart contract real value in being trustworthy for those who can read smart contracts code? And even in this case, trustworthy only wants to be someone who is not yet, so big corporations are not potential users? I mean big banks, car dealers, e-shops etc, we trust them anyway no matter if they do or do not use dApps.
Can dApps do something completely new, something that wasn't possible before? It would be great if you could provide me with examples.

Thanks a lot


texts: I recovered ETH on MetaMask sent to my ledger wallet via Binance Smart Chain

texts:
I sent ETH to my ledger hardware wallet using the Binance Smart Chain. As ledger does not support Binance Smart Chain I was able to recover the ETH on MetaMask. But the problem is that to send it back to Binance for example, I need BNB but ledger does not support it.
How can I finance or send the ETH back to Binance without BNB?
Thanks!


texts: Are full nodes/archivals execute the whole blockchain when a block received?

texts: Are full archive nodes and full nodes the same? I know that when the full nodes get a transaction, it verfies it by executing it. Does it execute the transactions in previous blocks too?


texts: Genesis Block mismatch with seemingly exact same file

texts:
I run a private Eth network with geth. I have two nodes on the network. I had these nodes connected over the last months. However, today when I try to connect one to the other I get an error:

err="Genesis block mismatch - 6231b02ac967dff9 (!= d4e56740f876aef8)"

When I display the hashes in geth they are also different:

1st machine:

> admin.nodeInfo.protocols.eth.genesis
"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"

2nd machine:

> admin.nodeInfo.protocols.eth.genesis
"0x6231b02ac967dff9b0c799e956094408959de862d720d08776302ffefba0300b"

However, it is the same file (I copied it with scp). Also when I run

md5sum CustomGenesis.json

it will result in the same hash for both machines. Furthermore I start the nodes with the exact same settings (apart from the directory path).
Might this be related to different geth versions (1.8 on machine 2 and 1.9 on machine 1) or to a recent crash of machine 1?


texts: Why does the minimum transaction cost in ethgasstation and metamask differ so much?

texts: On ETH Gas Station it says that the standard cost for transfer is ~$0.06 currently but when I send ETH on metamask I could't set the gas limit lower than 21000 which is roughly half dollar (10 times more than what ethgasstation says). Why is there such a big difference?


texts: If a malicious party attempts to close a Raiden payment channel with incorrect balances, can they steal the deposit?

texts:
If a malicious party attempts to close a Raiden payment channel with incorrect balances, can they steal the deposit if the other party doesn't respond?

If they close the channel and transmit that they ended up with the entirety of the deposit as the final balance, (when in reality they had sent half of it to the other party in the channel) will this get added to the blockchain and allow them to effectively steal from the other party?

If there is a time limit for which the other party can challenge the balance, what is the length of time allowed?

Thanks.


texts: Contract transaction: Gas estimated doesn't fit gas used

texts:
After finding out how to estimate contract tx fees thx to How to estimate the cost to call a Smart Contract method? and Syntax for calling contract state changing methods I tried to use all that knowledge and implement my own contract transaction with previous gas estimation, but they differ quite a lot. Gas estimated is 27,348 meanwhile Gas consumed is 181,080. So, what is wrong? Is this gas estimation process well done when dealing with smart contracts?

This is the data I used to estimate the gas for the endpoint: "start(address, address)" in a Smart Contract with address 0x27c042342C9ba937214117e11A4970A6145034cB

web3_sha3(endpoint) = 0xaa6d19c0b1d22f6983033c255695177ad1db0a0aad0435b6f6a367b48d4b37f4
arguments = "0xa7e3c7c227c72a60e5a2f9912448fb1c21078769, 0xf28dafbfeb41bf32869c9d498da0d651d0206ed4"
strhex(arguments) = 0x3078613765336337633232376337326136306535613266393931323434386662316332313037383736392c20307866323864616662666562343162663332383639633964343938646130643635316430323036656434
data = 0xaa6d19c03078613765336337633232376337326136306535613266393931323434386662316332313037383736392c20307866323864616662666562343162663332383639633964343938646130643635316430323036656434

yielding a Gas estimation of: 27,348

On the other hand, following tx is performed:

sc.start.sendTransaction("0xa7e3c7c227c72a60e5a2f9912448fb1c21078769", "0x47978a69f410d0f61850c92acdb0d4c464d70937", {from:"0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d", value:"0x55ae82600", gas:1000000});

txHash: 0xbad5639d7f02cfb1658580eb8cab5f950d379ee8197f423178391dc70701459f

and once the tx has been mined this is the resulting gas values:

Gas: 1,000,000
Gas Used By Transaction: 181,080

So, why estimated gas is so off? Thx in advance!


texts:
What additional advantages would a multi signature address give?

Can it create multiple nodes for blockchain broadcasting?


texts:
The Ethereum launch process states that with the release of Homestead, the Ether mining will be at 100% rather than 10% of the usual reward rate.

Does that mean the full block reward would be 50 Ether? Or what is the full block reward?


texts: How can i watch multiple smart contracts on server

texts:
I would like to create a sever that continuously watch the events of multiple smart contract at once. Sending me an alert via email when an event is detected.

I understand that there is a web3.js function that watch contracts. But how do I make it run perpetually on my server to do the task?

Furthermore, when there is an additional contract i would like to watch, is it possible to dynamically watch the new contract.

Thanks!


texts: How to do the performance evaluation in terms of secs or minutes? what is the command to use in solidity?


texts: Request a transaction amount in a function

texts:
I'm trying to have a function generate a request such that it pops up a Metamask request.
I know I can do:
require(msg.value == amount);
to require the function call has a certain value.
But this requires the transaction sender to manually input the transaction value which is error prone or they may not know the value to send. I want the contract to request a certain amount so that the user only needs to accept the transaction in Metamask.
In psuedocode, something like "request X ETH from msg.sender"
Thanks.


texts:
Can someone explain what exactly Ethereum wallet file (v3) contains, and how it works. How exactly public-private key pair is encrypted. Why two encryption algorithms are mentioned in the file (aes-128-ctr and KDF-scrypt) ? How each of them is used ? What is "mac" value on the last line ? Considering following file:

{
   "address":"2600a448db443dc49f3c0b6bf46e6f9110914568",
   "id":"712b2934-7ccd-4ef7-87f3-6384627d5b7d",
   "version":3,
   "crypto":{
      "cipher":"aes-128-ctr",
      "ciphertext":"225c3c42c2d7834c844a26070b13da6d5ac0e812022e4a4be434833aef430ae6",
      "cipherparams":{
         "iv":"75304b13fcf01c67536eb985f88dfc43"
      },
      "kdf":"scrypt",
      "kdfparams":{
         "dklen":32,
         "n":262144,
         "p":1,
         "r":8,
         "salt":"cd623230c41b3c8a8a88547e150da6ca1653bff04951cedd13791243d910cb21"
      },
      "mac":"cbe1a233297b97518efdbebe4a250bf5b29461537384f0d83d9f016c747eff5f"
   }
}


texts:
In the following article Link, we read:

Token owner just needs to make sure that first transaction actually
changed allowance from N to 0, i.e. that the spender didn't manage to
transfer some of N allowed tokens before first transaction was mined.
Unfortunately, such checking does not seem to be possible via standard
Web3 API, because to do the check one needs to be able to analyze
changes in the storage of smart contract made by particular
transactions, including internal transactions

I understand why setting to 0 approval and setting to amount approval makes sense to mitigate the problem, but as it mentions, this process won't be automatic, meaning that sender should be checking the situation after his/her approval to 0 on ethers.camp.  What If we want to automate this process from front-end(multiple transaction sequence), meaning that approval 0 transaction goes first, and then when it's mined, approval to amount transaction goes to network ? Only running these 2 transactions one after another doesn't solve the problem though, as it's still possible to double spend.
So here is my solution:
before Alice runs approval 0 transaction, front-end first checks allowance. Then after approval 0 transaction is confirmed, front-end checks if the allowance again is the same as the allowance it received before approval 0 transaction. If they are not the same meaning that spender spent some of it. and will decide if to run approval 50 or not again. As we can see, this is kind of a solution.
Question:
Why does it mention on the link I pasted above, that we would need to analyze changes in the storage of smart contract and so on ? my solution seem to be working fine. I'd appreciate your thoughts on this..


texts: Is it possible to hard fork a private network to Berlin?

texts:
I have a Proof-of-Authority private Ethereum network that has Istanbul EVM version and created by clique engine. I have multiple signer nodes that has Geth version: v1.10.1-stable-c2d2f4ed.
"config": {
    "chainId": 23422,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "byzantiumBlock": 4,
    "constantinopleBlock": 2862930,
    "petersburgBlock": 2862930,
    "istanbulBlock": 3831182,
    "clique": {
      "period": 15,
      "epoch": 30000
    }

Please see my configuration file: custom.json.
When I start geth I get following output:
"{ChainID: 23422 Homestead: 1 DAO: <nil> DAOSupport: false EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 4 Constantinople: 2862930 Petersburg: 2862930 Istanbul: 3831182, Muir Glacier: <nil>, Berlin: <nil>, YOLO v3: <nil>, Engine: clique}"
[Q] I was wondering, is it possible to hard fork a private chain that has different EVM version to Berlin EVM?

Related to: Is it possible to hard fork a private network to Constantinople?


texts: Is there any way of converting bytes into bytes32 using solidity assembly? (avoiding a loop, and knowing the size of the input bytes array)


texts: No web3.min.js while download Zip file from Github

texts:
I am following a youtube tutorial to make a simple dApp. In this tutorial he is telling to get Web3 from GitHub. I downloaded the Zip of Web3 from the GitHub and i get following folders and file after decompressing it.

But in the tutorial he is referring to a .js file named web3.min.js in his html code. I searched all the above folders to get web3.min.js but i didn't find it.

Is there any way to get web3.min.js from the downloaded Zip file? OR if i have to clone it to get web3.min.js then how i can clone it from GitHub?


texts: How to debug transaction from truffle test on development network

texts:
I am trying to debug a failing solidity function, which I am calling from the JS test files with truffle.

When I run my test, I am successfully able to get a transaction id. However, my solidity function does not appear to be performing the desired behavior so I would like to debug it.

I am aware that I can run

truffle develop
> debug transactionId

At which point, it returns and error saying that it cannot find the transaction id.

My understanding is that running truffle develop only connects me to the local testnet running on port 9545, but my test code is communicating with a different network, which is why no transaction with that id is found.

I've attempted to run truffle develop on a different port than 9545, however according to the documentation:

This will spawn a development blockchain locally on port 9545, regardless of what your truffle-config.js configuration file calls for.

So I think there are two potential solutions:

I can run my JS test code on the develop network running on port 9545
Or I attach the debugger behind the truffle develop command to the "test network"

One challenge with solution two is that it is unclear to me what port the test network is running on, and it also doesn't seem to exist beyond the duration that the test are actually running.

I've also tried running the following:

truffle develop
> test
> debug txId

Which then prints out a new transaction id, but the transaction is still not found.

I've also tried:

truffle test --network development

Which also does not work.

Any help would be greatly appreciated.

Some additional information since posting:

When I try to run truffle debug txId while running the ganache GUI, the gui spits out the following error:

RangeError: Invalid string length
    at JSON.stringify (<anonymous>)
    at /node_modules/ganache-core/lib/httpServer.js:103:57
    at Object.intermediary [as callback] (/node_modules/ganache-core/lib/provider.js:114:5)
    at self.engine.sendAsync (/node_modules/ganache-core/lib/provider.js:169:12)
    at /node_modules/ganache-core/node_modules/web3-provider-engine/index.js:152:9
    at /node_modules/ganache-core/node_modules/async/internal/once.js:12:16
    at replenish (/node_modules/ganache-core/node_modules/async/internal/eachOfLimit.js:61:25)
    at /node_modules/ganache-core/node_modules/async/internal/eachOfLimit.js:71:9
    at eachLimit (/node_modules/ganache-core/node_modules/async/eachLimit.js:43:36)
    at /node_modules/ganache-core/node_modules/async/internal/doLimit.js:9:16
    at Object.end [as callback] (/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:127:5)
    at intermediary (/node_modules/ganache-core/lib/statemanager.js:401:12)
    at /node_modules/ganache-core/lib/blockchain_double.js:900:11
    at /node_modules/ganache-core/lib/blockchain_double.js:649:9
    at commmitIfNeeded (/node_modules/ganache-core/lib/blockchain_double.js:640:11)
    at /node_modules/ganache-core/lib/blockchain_double.js:644:7
    at /node_modules/ganache-core/node_modules/async/internal/once.js:12:16
    at replenish (/node_modules/ganache-core/node_modules/async/internal/eachOfLimit.js:61:25)
    at /node_modules/ganache-core/node_modules/async/internal/eachOfLimit.js:71:9
    at eachLimit (/node_modules/ganache-core/node_modules/async/eachLimit.js:43:36)
    at /node_modules/ganache-core/node_modules/async/internal/doLimit.js:9:16
    at VM.AsyncEventEmitter.emit (/node_modules/ganache-core/node_modules/async-eventemitter/lib/AsyncEventEmitter.js:42:3)

Perhaps this is a bug with ganache?


texts: How to transfer ERC20 tokens from an account to a contract?

texts:
I'm struggling to transfer my ERC20 token toward a contract address.
My code is like this. What's wrong with my code? the code is like this.

Contract A{
  function deposit(uint amount) public {
    ERC20.transfer(address(this), amount);
  }
}

I have confirmed contract type ERC20 is valid.


texts: What determines how much gas is required when transferring an ECR-721 non-fungible token?

texts:
When transferring an ECR-721 token, what determines how much gas is required?  Is it written into the contract of the ECR-721 token?  Does it depend upon how it was transferred (e.g. cryptokitties.com vs OpenSea.io)?
How can the amount of gas be appropriately estimated for this type of token transfer?


texts: Deploying a contract on private Ethereum network Harmony

texts:
I just started on ethereum and I created  a private ethereum network on harmony and we were able to syn up to other peers using the same router .

Question would like to ask is how do u deploy the contract on a private network in harmony?

Been searching around on how to do it but am not too sure.


texts: I want a function locked for a certain amount of time, what's the safest way to achieve this?

texts:
I want a store where someone can become tokenOwner for a certain amount of time. The following solutions seems the easiest:

pragma solidity ^0.4.24;

import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol";

contract PromotedDapp is Ownable{

    uint price;
    address tokenOwner;
    uint nextOwnerAllowed;

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

    function becomeOwner() public {
        require(now >= nextOwner);
        nextOwnerAllowed = now + 604800; // In a week
        tokenOwner = msg.sender;
    }

}

I know another option is to work with blockHeight since one block gets minted +/- every 10 seconds, what would be a reason to chose blockHeight over time in seconds?


texts: How two untrusted parties can make transactions without any involvement of the third-party?

texts:
I'm trying to create a contract where where PartyA and PartyB had to trade. PartyA sends money to a contract and PartyB sends goods to partyA. After partyA receives the goods it allows PartyB to retrieve it's money from the contract.
In any case possible a third party is needed. I'm I wrong?


texts: Mist password not working. Is there a way to open a new account?

texts:
I have a mac. How do I delete mist and re-download it + blockchain so I can start fresh? My original password is not working (only 1 eth in it so not worried about loss).

If it needs to be deleted through terminal and you can direct me through the process it would be much appreciated : )


texts: Comparing Rust and Solidity hash of big number or hex

texts:
I noticed that if I hash ordinary string using Rust and web3.sha3 I would get the same result. But if the number is big number or hex which would necessitate the inclusion of {encoding: 'hex'} as optional arg to web3.sha3 my result from Rust and web3.sha3 would not be same . So, my question is what should I do to my Rust input before hashing it?
For Rust I am using multihash which is a thin wrapper.

let nm_str1 = "00000000000000000000000000000000000000000000000000000000000000ea";
/let output = encode(Hash::Keccak256, &nm_str1.as_bytes()).unwrap();
//JavaScript
const nmStr1 = "00000000000000000000000000000000000000000000000000000000000000ea";//
let output web3.sha3(nmStr1, {encoding: 'hex'}


texts: Difference between ERC 20 and ERC 721 transaction receipt

texts: I want to fetch certain transaction logs from a local ethereum node. For that, I need to identify how to differentiate between ERC 20 and ERC 721 transaction receipts. From what I saw on Etherscan, i couldn't find any differentiating method as both the receipts look similar. The link of an ERC 20 transaction receipt is here https://etherscan.io/tx/0xbad497f6d96dd111c221ce41355cbb9ac912a6c0953ccb94113ba8232ab95e0a and ERC 721 transaction receipt is https://etherscan.io/tx/0x1ae8ba8417d6603e4f0b930b768814883af2d0ee091bc78145e871171768710e.


texts:
I am trying to withdraw some coins from my wallet (as I have done several times prior) but this time I am prompted with the error:

 {0x0000000000000000000000000000000000000000", value: web3.toWei(1, "ether")})
{
  code: -32000,
  message: "account is locked"
}

I've tried unlocking the account using the --unlock command

geth --unlock "0x0000000000000000000000000000000000000000"

but unfortunately it did not fix the issue.


texts:
I am trying to make a smart contract which can add /delete and modify users in the smart contract. I have just written the code for adding the user but I am getting an error saying "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."

How can I solve this problem? Here is my code:

pragma solidity ^0.5.0;

contract Add{
struct User {
    uint256 id;
    string name;

    // other stuff

    bool set; // This boolean is used to differentiate between unset and zero struct values
}
 address owner;
 modifier onlyOwner() {
       require(owner == msg.sender);
            _;
}

mapping(address => User) public users;

function createUser(address _userAddress, uint256 _userId, string memory _userName) public onlyOwner {
    User storage user = users[_userAddress];
    // Check that the user did not already exist:
    require(!user.set);
    //Store the user
    users[_userAddress] = User({
        id: _userId,
        name: _userName,
        set: true
    });
}

}


texts: Compatible versions of npm, truffle, node and web3 for Solidity 0.7.2

texts:
I'm using:
Solidity 0.7.2,
Node v12.18.4,
Truffle v5.1.49 (core: 5.1.49),
npm 6.14.8,
web3 1.3.0
I want to know what versions are compatible with solidity 0.7.2.
Many thanks and have a nice weekend.


texts: Proper number of confirmations in a small testnet

texts: In a private blockchain with just 4 miners, what should be the proper number of confirmations? 24 is by default, but does it make sense? should it be just 4 (one per miner)?


texts:
I am writing a smart contract which receives Ether.

How can I transfer Ether from the contract to my personal purse (non programmatically using such a program as Ethereum Wallet)?

Can I send Ether from the contract like as I can do with regular wallet?

In the "possible duplicate" question it is not said how to withdraw from the contract non-programmatically. It is should be easy for a user to withdraw, without him writing a code.


texts:
Under Ganache, I created some APIs with nodejs to managing a Smart Contract. One API is for the creation of new accounts with

newAccount = web3.eth.accounts.create(web3.utils.randomHex(32));

Then, with another API, when I try to access a function of the Smart Contract with

contractInstance.methods.myFunction(param1, param2, param3).send({
from: newAccount.address,
gas: 4600000
}).on('transactionHash', function(hash){
console.log(hash);
}).on('error', console.error);
});

the transaction fails with the error

sender account not recognized

Where am I wrong?

Thank you


texts: Why in solidity 0.6 these functions are no more free?

texts:
Try this code

pragma solidity >=0.5.0 <0.6.0;

contract test05 {

    address payable public admin = msg.sender;

    function() payable external {}

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

getBalance is callable for free. Event reading admin address is free.

But try this

pragma solidity >=0.6.0 <0.7.0;

contract test06 {

    address payable public admin = msg.sender;

    receive() payable external {}

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

getBalance now requires gas to be called, and also admin is no more free to read.

Why ?!!?

I am asking this because I'd like to develop directly on latest version of 'everything' tool/framework/language I uses.


texts:
I am curently working on a solidity project along with a web3js client. I made this procedure in my contract, ddployed it in my testrpc and made a client request using web3js.

The problem is in the response, I expected a simple array of uint like [1,2,3]
but got a strange response that even if it holds the desired response it is still not the one i needed.

here is the response :

[…]
   0: {…}
       c: Array [ 12355678 ]
       e: 7
       s: 1
   __proto__: Object { abs: another/P.abs(), absoluteValue:   another/P.abs(), ceil: another/P.ceil(), … }
   length: 1
   __proto__: Array []

here is the solidity function :

function getAllClientsOfABank(bytes32 BankName) returns(uint[]) {
    uint[] memory Clientss = new uint[](Banks[BankName].numberOfClients);

    for(uint i = 0; i < Banks[BankName].numberOfClients; i++) {
        Clientss[i]=Banks[BankName].Clients[i].cin;

    }
    return Clientss;
}

Note : cin is a uint type / Banks is a mapping of strings and BankStruct / Clients is a mapping of uint and ClientStruct

**Web3JS Client Call **

 contractInstance.getAllClientsOfABank.call('BAN556',{gas:3000000}).then(
     data => {
          console.log(data);
              }
 )


texts: Geth: How to debug an "invalid sender" error?

texts:
I am sending transaction to a private, local, instance of geth.

I run geth using

./geth --rinkeby --syncmode fast  --rpc  --rpcaddr 192.168.229.132 --ipcdisable

I am using web3.js to send signed transactions to this local ip

The problem is that I am getting, for each call, this

conn=192.168.229.1:57960 reqid=4 t=93.545µs err="invalid sender"

I have no idea of what this error means

I already checked that wallet address and wallet private key are right and matched.

I'm using a metamask account, on rinkeby network, so it's easy to re-export the private key from the chrome extension interface. It is right and it has eth in the rinkeby network.

Please, coould you suggest to me how to diagnose this error?


texts:
I am using a local testnet.
I send transactions with eth_sendRawTransaction but unfortunately sometimes the transaction pass and sometimes not.

When it does not pass I have two things happening at the same time:

I cannot get a transaction receipt, that is the eth_getTransactionReceipt returns null
If I resubmit the transaction then I got the known transaction error.

What is happening? What could be a possible solution to the problem?


texts: Can Smart Contracts be used to execute trades on exchanges?

texts:
I'd like to create a smart contract to execute trades on exchanges and transfer the received ethereum to another wallet.
Something like this:
* Receive token into wallet
* Smart contract sells token for ethereum
* Ethereum transfers to another address.

Is this possible?


texts: Ethereum Go Source: hexToCompact function

texts:
I have a question regarding the following code snippet. Specifically the following function:

func hexToCompact(hex []byte) []byte {
    terminator := byte(0)
    if hasTerm(hex) {
        terminator = 1
        hex = hex[:len(hex)-1]
    }
    buf := make([]byte, len(hex)/2+1)
    buf[0] = terminator << 5 // the flag byte
    if len(hex)&1 == 1 {
        buf[0] |= 1 << 4 // odd flag
        buf[0] |= hex[0] // first nibble is contained in the first byte
        hex = hex[1:]
    }
    decodeNibbles(hex, buf[1:])
    return buf
}

This is a implementation of Appendix-C Hex-Prefix encoding from the Yellow Paper and when I did a search on this in the repo. I found a function within slasher.go calls hexToCompact.

func (h *hasher) hashChildren(original node, db *Database) (node, node, error) {
    var err error

    switch n := original.(type) {
    case *shortNode:
        // Hash the short node's child, caching the newly hashed subtree
        collapsed, cached := n.copy(), n.copy()
        collapsed.Key = hexToCompact(n.Key)
        cached.Key = common.CopyBytes(n.Key)

        if _, ok := n.Val.(valueNode); !ok {
            collapsed.Val, cached.Val, err = h.hash(n.Val, db, false)
            if err != nil {
                return original, original, err
            }
        }
        return collapsed, cached, nil

    case *fullNode:
        // Hash the full node's children, caching the newly hashed subtrees
        collapsed, cached := n.copy(), n.copy()

        for i := 0; i < 16; i++ {
            if n.Children[i] != nil {
                collapsed.Children[i], cached.Children[i], err = h.hash(n.Children[i], db, false)
                if err != nil {
                    return original, original, err
                }
            }
        }
        cached.Children[16] = n.Children[16]
        return collapsed, cached, nil

    default:
        // Value and hash nodes don't have children so they're left as were
        return n, original, nil
    }
}

My questions are

What is the need for Hex-Prefix compactness as specified in Yellow Paper?
What is slasher.go is trying to do here by compacting a shortnode and why just shortnode?.


texts: Would it be possible to create a token that you can mint on-demand?

texts:
Is it possible to create a token that you can mint on demand?
Some possibilities might be to allow a specific wallet to execute the minting command, or to set the price ahead of time, or to use other data on the blockchain to set the price.
My assumption is that this would be too expensive with current ERC-20 contracts, since most of them mint all the tokens at once and issue them over time.
One possible workaround might be to issue the tokens all at once, then send them to a smart contract which will sell them based on a formula built into the code.


texts: With eth_getFilterChanges rpc-method, I can receive new transactions by existing filter. But as I understand, after receiving transactions by filter these transactions could be from uncle-block, so finally received transactions not exists in blockchain? Is it possible to track such situations?


texts: Is it possible to know when a block is mined? Is there any timestamp or event/subscription?


texts: How is the block interval constrained in Ethereum 2.0

texts:
Sorry if i get any of the terminology wrong here, i'm no expert when it comes to PoS protocols.

How does Ethereum 2.0 control for blocktime, typically we have the idea of a function that can be tuned via difficulty, i.e. requiring that as blocktimes (timestamps provided by miners) converge the difficulty of a function should increased.

Do we have the same idea in Ethereum 2.0? is there any measures in place to reduce the amount of blocks that can be created in a time period (do block producers include timestamps in blocks) and can block creation be limited by this?


texts: Will 'x.send(amount)' revert if 'x' is a contract with a fallback function which reverts?

texts:
I know that x.transfer(amount) reverts if either one of the following two scenarios takes place:

There is not enough ether in the calling contract, i.e., amount > address(this).balance
Variable x is the address of a contract with a payable fallback function which reverts

I know that x.send(amount) fails silently if the first scenario takes place.

But will it fail silently also if the second scenario takes place, or will it revert?

My overall purpose is to iterate a queue of (address wallet, uint256 amount) tuples, and for each tuple pay the given amount to the given wallet, until the queue is empty or my balance is too low.

So during this process, I am not concerned about failures due to insufficient funds.

I am, however, concerned about the possibility of a wallet being a contract with a payable fallback function.

If this function reverts, then this wallet will be stuck at the beginning of my queue forever, denying payment from the rest of my debt-owners.

So the only solution that I can think of is replacing transfer with send, but even this solution is very partial IMO, so I would be happy to hear alternative suggestions.

Thank you!


texts: How are pre-sale Augur's REPs stored on the Ethereum blockchain?

texts:
Does Augur's REP exist as Ethereum coin contract?

If so, does the coin contract already deployed on the Ethereum blockchain? What is the contract address for it?
If not, how do you know how many REP is owned by crowd-sale buyers?


texts:
I am trying to use ethash(hash(blockHeader),nonce) < TARGET to prove that the block was mined with at least a minimum difficulty.

Is the formula above correct?

When I try to use ehtereum.pow.ethash from pyethereum:

from ethereum.pow import ethash
difficulty = 3963642329
block_number = 4156209
nonce = int('0xf245822d3412da7f', 16)
block_hash = 0x47b8f62c1400dae65105d2f8e03824bfc58481c0b32f45788ad3378fbc05e9f6
cache = ethash.mkcache(block_number)
ethash = hashimoto_light(block_number, cache, block_hash, nonce)
print(ethash)

I get this error:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    cache = ethash.mkcache(block_number)
  File "(environment_path)/lib/python3.6/site-packages/ethereum/pow/ethash.py", line 15, in mkcache
    while len(cache_seeds) <= block_number // EPOCH_LENGTH:
NameError: name 'EPOCH_LENGTH' is not defined

Am I doing it wrong? Or is there a bug in ethereum.pow.ethash?


texts:
I have seen here and several other places that the correct way to send ether from a contract to an address is to call the .call{}() method.
Then here I have seen the method being used with arguments. Like so:
addr.call{value: msg.value, gas: 5000}(
    abi.encodeWithSignature("foo(string,uint256)", "call foo", 123)
);

I understand that the arguments in the curly braces. value: is the eth you want to send and gas: is the amount of gas you are willing to pay for the transaction to be mined. (correct me if I am wrong).
What I do not understand are the arguements in  brackets.

What is the abi object insside the contract and what does it do? Is it the same as the one you get when you compile the contract?
What does abi.encodeWithSignature()` method do?
How many arguments can the brackets take and what do they mean? And do you have to provide arguments to it or can you leave it empty?


texts:
The tab width on remix https://remix.ethereum.org defaults to 4 spaces. I have looked everywhere but I cannot see how to change it to 2 spaces, or 3 or whatever. Is it possible?

nb: don't care what the standards are, try working on a 13 inch laptop.


texts: Can a cyber cafe mine ETH seperately on each computer?

texts:
Is there a limit to how many computers can be mining from one ip address, and if i can make 1 ETH a month from one computer if i hook up 7 can i make the 7 ETH a month and could they go to one wallet or do i have to make 7 accounts?

and another thing is can it run while people are doing simple tasks (ex. ms word, youtube, facebook,) or will it lag the computer to the point it only has to stay mining where as i can turn it on at night only when i close up.

PS.

sorry in advance for my really long question


texts: Is it possible to implement the essence of smart-contract into another one before deploying the first one?

texts:
My question means for example that the primary contract stores names of secondary contracts, for example like this:

mapping (address => string) secondaryContractNames;

I know we can in the primary contract define the essence of secondary contract like this:
secondaryContract contract = secondaryContract(_address);

Is it possible to code something like this:

secondaryContractNames[_address] contract = secondaryContractNames[_address](_address);

or:

contract(secondaryContractNames[_address]) contract = contract(secondaryContractNames[_address])(_address);

So if we store secondaryContractNames[_address] as for example  secondaryContract the previous code will be transformed as
secondaryContract contract = secondaryContract(_address);

I  know that the code below doesn't work. It's just to explain my logic. And the question is it possible in solidity or not?


texts: How come I need to specify a higher gasLimit than estimateGas?

texts: If a contract call predictably requires 41043 of gas to be processed as estimated by estimateGas, how come I need to specify gasLimit of ~70000 to be processed?


texts:
I am new to solidity :)
I try to create a general contract which its attributes are known at run-time.
Suppose we have the following contract:
contract Product{
     string name;
     uint price;
     constrcutor(string memory _name, uint _price){
            name = _name;
            price = _price;
     }
}

And for the sake of simplicity I would like to create different Product contracts in the tests.
I know that I have to migrate the contract before deploy it, but really - no idea.
I try hard, excuse for me being newbie, I really have no idea how to do it or how to google it :(


texts: How to restrict ICO investors to redeem their ERC20 tokens while not restricting them to trade tokens among themselves?

texts:
We want to create an ICO where investors can purchase ERC20 tokens anytime but have to wait for atleast 3 months from the date of purchase in order to redeem/encash them on our platform.

But we do not intend to restrict the investors from trading /transferring/exchanging tokens among each other outside our platform.

Example 1) A buys 400 ERC20 tokens on 14th January. He sells 200 tokens to B (outside our platform) on 15th March. C buys 200 tokens on 15th March from the platform.

Now, A, B and C comes to redeem / encash the tokens for FIAT on our platform on 15th April (after 3 months from initial purchase of tokens)

Now, both A and B should be able to encash / redeem the tokens as both came to redeem after 3 months of original purchase of those tokens. But C cannot redeem it as 3 months are not over from the date of purchase.

How can we achieve this? Can we bind timestamp or any parameter with tokens or something? What is the best possible solution?


texts: Remix: creation of contract from within existing contract using Web3 Provider not working

texts:
I have an existing contact ManageMembers that allows new members to create a new contract via the AddMember function which also returns the address of the new contract. This works fine in the Remix Javascript virtual machine, but doesn't return the address with a Web3 provider.

contract ManageMembers {

  address[] members;

  function AddMember(bytes32 name) public returns(address) {
    address member = new Contract(name);
    members.push(member);
    return member;
  }
}

contract Contract {
  bytes32 public Name;

  function Contract(bytes32 name) public {
    Name = name;
  }
}

I know that the new member contract has been created because the address is pushed to members and I can access other variables in the new contract. Here is output from Remix:

status     1
 from   0x7598a74e87f325db2a521729208ac8f341a97a8e
 to     ManageMembers.AddMember(bytes32) 0xad5e8618c90cef613e6b42a60c795e74fcb51594
 gas    190860 gas

transaction cost   190860 gas
 hash   0xc2285112566da09f67f1b03e025191ae5d69ee5fa26cb486bec61a6bf0913424
 input  0xd0944ada712e7140712e636f6d0000000000000000000000000000000000000000000000
 decoded input  {
    "bytes32 name": "0x712e7140712e636f6d0000000000000000000000000000000000000000000000"
}
 decoded output      -
 logs   []
 value  0 wei

I'm using testrpc which normally works fine and all account addresses are shown in Remix.

Why does this not work with Web3?


texts: Automatically calling a contract function every 24 hours?

texts:
I want to have my smart contract call a function every 24 hours automatically. Can this be achieved as follows?

pragma solidity ^0.4.2;

import "http://github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";

contract MyContract is usingOraclize {

    function callThisToStart() {
        oraclize_query(1*day, "URL", "");
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        doSomething();
        callThisToStart();
    }

    function doSomething() {
        // then this should run every 24 hours
    }

}

I don't understand how Oracle works yet so this may be completely wrong - callThisToStart() would be called, which would then run the __callback function a day later, which will then run some code in doSomething() and call callThisToStart() afterwards so the process would be repeated in a day.


texts: How many tokens are transfered actually when we are using decimals

texts:
I have a code below and when I am transferring 1,695,000,000 to a particular address, so actually 0.000000001695  are being transferred. Why is it so?
Does that mean to transfer 1.695 billion tokens I need to put 18 leading 0s.
Here's the code:

function transfer(address _to, uint256 _amount) public returns (bool success) {
    require(_to != address(0));
    require(balances[msg.sender] >= _amount && _amount > 0
        && balances[_to].add(_amount) > balances[_to]);

    // SafeMath.sub will throw if there is not enough balance.
    balances[msg.sender] = balances[msg.sender].sub(_amount);
    balances[_to] = balances[_to].add(_amount);
    Transfer(msg.sender, _to, _amount);
    return true;
  }

contract SomeToken is MintableToken, BurnableToken {
     string public name ;
     string public symbol ;
     uint8 public decimals = 18 ;

     /**
     *@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
     */
     function ()public payable {
         revert();
     }

     /**
     * @dev Constructor function to initialize the initial supply of token to the creator of the contract
     * @param initialSupply The initial supply of tokens which will be fixed through out
     * @param tokenName The name of the token
     * @param tokenSymbol The symbol of the token
     */
     function SomeToken(
            uint256 initialSupply,
            string tokenName,
            string tokenSymbol
         ) public {
         totalSupply = initialSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount
         name = tokenName;
         symbol = tokenSymbol;
         balances[msg.sender] = totalSupply;

         //Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
         Transfer(address(0), msg.sender, totalSupply);
     }
}


texts: Sending string to deployed contract function

texts:
var source = fs.readFileSync("./vote.sol", "utf-8")
var compiled = web3.eth.compile.solidity(source);
var abi = compiled.identify.info.abiDefinition;
var Vote = web3.eth.contract(abi);
var ContractManager = Vote.at(contractAddress);
var csv = "a,string,like,this,";
ContractManager.voteNow.sendTransaction(csv, { from: web3.eth.accounts[0], value: 10000000 });

  The voteNow function expects a string as its input.

Error: Invalid address length, expected 40 got 160 bytes
    at Object.module.exports.InvalidResponse (node_modules/web3/lib/web3/errors.js:35:16)
    at RequestManager.send (node_modules/web3/lib/web3/requestmanager.js:61:22)
    at Eth.send [as sendTransaction] (node_modules/web3/lib/web3/method.js:145:58)
    at SolidityFunction.sendTransaction (node_modules/web3/lib/web3/function.js:133:26)

Here is the solidty function:

 event Broadcast(string x,string s1, string s2);

 function voteNow(string vote){
        Broadcast('voteLog','New vote','sender,vote');
        Broadcast('voteLog',toString(msg.sender),vote);

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


texts: Calling another contract's function fails for no apparent reason

texts:
I have this piece of code in Remix-IDE + Metamask, both at the most recent versions (but I also tried without Remix-IDE):

pragma solidity ^0.4.10;

contract Foo {
    bool public lastVal = false;

    function fooFunc(bool x) public returns (bool) {
        lastVal = x;
        return !x;
    }
}

contract Bar {
    bool public barBool = false;
    Foo myFoo;

    function Bar(address _myFooAddr) public {
        myFoo = Foo(_myFooAddr);
    }

    function barFunc() public {
        barBool = myFoo.fooFunc(barBool);
    }
}

Whenever I call barFunc() Remix-IDE refuses to run it because it says that the transaction will surely fail. If I force to run the transaction, it actually fails with a REVERT.

Anyway, I don't see any apparent reasons as to why this should fail.

Thanks a lot for your help.


texts: Mix wont connect to nodes: Error status 0

texts:
I managed to configure Morden test network to run, but Mix is unable to discover testnet node, it is giving this error:

A "Unable to initiate request to the live network. Please verify your ethereum node is up. Error status: 0"

Any help?


texts:
I am looking for a PHP library to interact with Ethereum. Are there any active open source projects of PHP libraries for Ethereum available?

Thanks for your help


texts: How to handle dynamic size string array in solidity?

texts:
I have a shop owner and a shop owner can have multiple products. I want to keep the products id in an array.

Also, A public method can return all the product id list of a shop owner.

I tried the following code

pragma solidity 0.5.0;

contract Shop {

    struct ShopOwner {
        string id;
        string[] productList;
    }

    struct Product {
        string id;
        string name;
    }

    mapping(string => ShopOwner) private mapShopOwner;

    function getUserProductList(string _shopOwnerId) public view returns(string[]) {
        return (mapShopOwner[_shopOwnerId].productList);
    }

}

This seems does not support the solidity language.

I am getting the error

  browser/Structure.sol:17:33: TypeError: Data location must be "memory"
  for parameter in function, but none was given.
      function getUserProductList(string _userId) public view returns(string[]) {
                                  ^------------^

and

  browser/Structure.sol:17:69: TypeError: Data location must be "memory"
  for return parameter in function, but none was given.
      function getUserProductList(string _userId) public view returns(string[]) {
                                                                      ^------^

And I do not want to use pragma experimental ABIEncoderV2;

I wonder, what is the correct procedure to handle this types of relation.


texts:
I am working on a web application where I need to generate Ethereum addresses in PHP, how do i go about generating a random Ethereum public/private key pair in PHP?

thanks.


texts: GTX Titan Z BIG problem, barely hashing anything at all!

texts:
so I just got a GTX Titan Z card as I read it should be able to run about mine ETH at about 50Mh/s since it has dual GPUs.  However, I just installed it and started up CGminer and was super shocked to see that each GPU is barley even running at 2MH/s.  I have current Windows 10 and the current Nvidia drivers installed as well, which are recommend for this card, so what the heck is going on here?

Any thoughts on this madness guys?


texts: Update private chain from homestead to byzantium

texts: I need to update my the version of my chain from homestead to Byzantium. Who can tell me how to do it? thanks.


texts: I'm studying proof of stake. I haven't found a clear definition of what "liveness" is. It is a main thing in PoS content, but I don't think I understand it clearly.


texts: unable to deploy contract on ropston testnet

texts:
I am trying to deploy contract on ropston testnet. I have created an account through truffle console and got three test ethers from https://faucet.bitfwd.xyz/. I have confirmed that my account has three ethers from this https://ropsten.etherscan.io/. But when I check balance from truffle console it always says zero. Although my node is synced.

web3.eth.getBalance('0x06ac473de96986b20b37f13ca311d07c0875e49b')
BigNumber { s: 1, e: 0, c: [ 0 ] }

here is screenshot of  https://ropsten.etherscan.io/ which clearly shows it has three ethers.

When I do truffle migrate I get following error.

Please help my finding where mistakes occur. Thanks in advance :)

Edit

Here is my truffle.js

module.exports = {
  networks: {
    development: {
      host: '127.0.0.1',
      port: 8545,
      network_id: '*',
      gas: 470000
    }
  }


texts: Does SUICIDE also free up stored hashes?

texts:
Here's a contract:

pragma solidity ^0.4.19;

contract StoreAndFree {
    mapping(int=>int) myStore;
    function StoreAndFree() public {
        for (int i=1; i<100; i++) {
            myStore[i] = i;
        }
    }

    function kill() external {
        selfdestruct(msg.sender);
    }
}

When you kill it, what happens to the stored values? Are they still stored? Should you reset them to zero? Do you get gas back for resetting them to zero?


texts: Creating Contract from Contract. Member "transfer" not found or not visible after argument-dependent lookup in address

texts:
I am having a problem with my smart contract making value transfers. My current environment:

Truffle v5.0.3 (core: 5.0.3)
Solidity v0.5.0 (solc-js)
Node v10.13.0

pragma solidity >=0.4.21 < 0.6.0;

contract ContractWallet {
    constructor() public{
    }
}

contract deposit {
    mapping (address=>ContractWallet) public users;

    constructor () public { }

    function testDeposit(
    )
        public
        payable
    {
        ContractWallet _newWallet = new ContractWallet();
        address(_newWallet).transfer(msg.value);
        users[msg.sender] = _newWallet;
    }

}

After creating a contract from a contract, I can not transfer ether to the newly created contract address.
I think I'll probably add 'payable', but I don't know how to do it.


texts: What are the meanings of `(uint256) (a)` and `(int256) (a)` in Solidity

texts:
I came across the following code
payoutsTo_[_customerAddress] +=  (int256) (_dividends * magnitude);
What is meaning of (int256) in this line, and is there any possibility of overflow here? Or here:
magnitude = 2 ** 64


texts: I understand it takes time to include a legitimate transaction in the blockchain. And I understand to execute a SmartContract function is nothing more than sending a transaction. My question is that if it takes more time to finish a SmartContract function execution than to include a plain transaction in Blockchain.


texts: Don't understand unsafe send transaction warning in solidity documentation

texts:
There is this warning on the solidity documentation (https://solidity.readthedocs.io/en/v0.4.24/types.html)

I understand the part about stack depth limitation of 1024 and transaction failure when it runs of gas.

Why does this warning specifically warns about caller forcing the stack depth problem and causes transaction as an unsafe ether transfer? If the caller intentionally fails the send transaction which will result in a rollback, what harm could it do to the smartcontract or the recipient?

Is this some attack vector that is so obvious which I don't understand?


texts: How to calculate generated fees from uniswap?

texts:
I try to calculate how much fees I earned for each transaction by providing liquidity.
In chunks I downloaded all swaps, mints and burns from the graph for my token pair. https://thegraph.com/explorer/subgraph/uniswap/uniswap-v2
I read the whitepaper and as far as I understand a swap at time t should generate
fees earned = token0_fee + token1_fee
with
token0_fee = 0.003 * amount0In * (number of LP tokens I own at time t  / all at time t existing LP tokens)
token1_fee = 0.003 * amount1In * (number of LP tokens I own at time t  / all at time t existing LP tokens)

However if I sum up all fees I do not get the results displayed (Total Fees Earned) at info.uniswap.org for my account.
Additionally if I try to calculate the number of tokens in the pair contract my result also differs from the token pair page at info.uniswap.org. I used the following formula.
(all tokens paid in at swaps) - (all tokens paid out at swaps) + (all tokens paid in at mints) -
(all tokens paid out at burns)

What am I missing here ?
Thanks


texts:
Couple of days ago Vitalik Buterin tweeted that Ethereum has no metadata limit.

Is that true? Two major questions that bothers me, as a developer:

I can store any amount of data inside contacts?
If so, does it mean that eth network can be abused, spammed and bumped to huge sizes for individual peer?


texts: How to attach geth to a parity node with admin?

texts:
I have installed two nodes under PoA using Parity.

I normally use this to attached geth to a geth node:

geth attach node/geth.ipc

I got working geth attach using rpc but there is no admin.

geth attach http://localhost:8540

But then I get no admin. I entered the admin into the toml file and the node fails to start.

Is there a way to get this working so that the admin functionality in geth can be used when attached to a parity node?


texts: Hash bytes32 and uint32 in Soldiity 0.5.8

texts:
How can we efficiently calculate a hash value for a combination of bytes32 and integer value?

Like in JavaScript "someString" + someInt.

I tried:

function fx(bytes32 _left, uint32 _right) public returns (bytes32 hash) {
    hash = keccack256(_left + _right); // wrong
}


texts: What are options re: transferring ETH and ERC-20 tokens out of Mist without having to synch?

texts:
I have some ETH and many custom tokens sitting in a Mist wallet that will take many days to synch.

I assume I can use the 'transfer from' function to move these tokens from this wallet without having to synch, using the JSON file.  Is that correct?  If so, is that the best way to do this quickly?

Grateful for all suggestions and thoughts.  Thank you!


texts: Python script - get balance and send transaction

texts:
I'm a developer who is new to ETH and I would like to write python CLI that can check balance of ETH address and can create -> sign -> publish transaction to network via locally running Geth node (I don't want a dependency to 3rd party service).

I have found this python lib https://github.com/ConsenSys/ethjsonrpc which looks fine for my use case.

My question is, whether this seems as a good setup and in what syncmode should be Geth node executed in my use case? Do I need full node or fast/light will be sufficient? I have read documentation but I'm still not sure what do I need.

Thank you for any help.


texts:
I tried a few things and after a few attempts and ~24 hours the chain was synced. One thing i tried was to sync my PC clock after "time.is". It always showed a delay. I downloaded a program which promised to sync the clock and it actually did. "time.is" showed me that my clock works right. Also my full node is working. the only strange thing is, everytime when i open Mist i get this popup message first

:

Do you know why?


texts: Transaction gas cost in truffle test case

texts:
Below is from a truffle test cases in javascript, where I was trying to add the gas cost to an account balance to confirm the sum of transaction, where the sum should be equal to the previous balance.

But I couldn't get it to work!

The rcpt.cumulativeGasUsed, web3.eth.gasPrice, getBalance(accounts[1]) are all correct, but the arithmetic is not, some fromWei, toWei kung-fu needed?

What am I doing wrong here?

            return instance.bailOut({ from: accounts[1] }).then(function (resp) {
            var rcpt = web3.eth.getTransactionReceipt(resp.tx);
            console.log("Sum: " + ((rcpt.cumulativeGasUsed * web3.eth.gasPrice) + web3.eth.getBalance(accounts[1]).toString(10)));

});

After a lot of experiments, it looks like the below method works fine, but couldn't explain the logic of transaction cost! Any idea is most welcome.

Anyways unit test is passing now!!!

return contractInstance.withdraw({ value: web3.toWei(1, "ether"), gas: 1000000 }).then(function () {
          var contractAddressBalance = web3.fromWei(web3.eth.getBalance(contractAddress).toString(10));
          console.log("contractAddress balance after withdraw: " + contractAddressBalance);
          return contractInstance.bailOut({ from: accounts[1] }).then(function (resp) {
            var rcpt = web3.eth.getTransactionReceipt(resp.tx);

            console.log("cumulativeGasUsed: " + rcpt.cumulativeGasUsed);
            console.log("gasPrice: " + web3.eth.gasPrice);

            var transactionCost = (rcpt.cumulativeGasUsed / 10000000); // How come this works???

            console.log("transactionCost: " + transactionCost);
            console.log("Account[1] balance after withdraw: " + web3.eth.getBalance(accounts[1]));

            contractWalletAfter = web3.fromWei(web3.eth.getBalance(accounts[1]).add(web3.fromWei(rcpt.cumulativeGasUsed)));
            assert.equal(((contractWalletAfter.minus(contractWalletBefore)).add(transactionCost)).valueOf(), 6, "6 wasn't in the contract wallet");
          });
        });


texts: questions regarding how many bytes each type is

texts:
I have questions about how many bytes each type might be.

Question 1) now()  timestamp. i think it's uint which means uint256 which means 32 bytes? Am I right?

Question 2) what does bytes32 mean? They say it's an array. but i can't do push on it. something like this: bytes32 public array; array.push("good"); so it's kind of an array like a string? string s = "good"; like this? but imagine what if I want to have arrays of 32 bytes?

Question 3) what about event logs topics? if I write uint indexed var1 in a log, a) i know that it's gonna cost me 32 bytes as uint is 32 bytes but what if b) I write bytes16 indexed var2 ,  is it still gonna cost me 32 bytes or just 16 bytes? and c) what if i save more than 32 bytes in a log and it's a topic, lets say 50bytes, is it gonna cost me still 32 bytes and keccak256 hash will be stored there ? Am I right in a) , b) and c)

Thanks guys. before writing questions, I always try to put my idea on it .


texts: How does the re-entrancy guard modifier work?

texts:
Following is code for a re-entrancy guard, but not sure if I understand it properly:

contract Test {
    using SafeMath for uint256;
    uint256 private counter = 1;
    modifier entrancyGuard() {
        counter = counter.add(1); // counter adds 1 to the existing 1 so becomes 2
        uint256 guard = counter; // assigns 2 to the "guard" variable
        _;
        require(guard == counter, "That is not allowed"); // 2 == 2?
    }

    function safeWithdraw(uint256 amount) external entrancyGuard() {
        // Withdraw code
    }
}

I'm not sure how the modifier prevents re-entrancy.


texts:
I have a small issue with remixd connecting to my browser IDE instance.
I have tried on both MacOS and Linux with the result being virtually the same
When I run the following:
remixd -s /home/garrett/ --remix-ide http://remix.ethereum.org/
I get this error:
[WARN] You may now only use IDE at http://remix.ethereum.org/ to connect to that instance
[WARN] Any application that runs on your computer can potentially read from and write to all files in the directory.
[WARN] Symbolic links are not forwarded to Remix IDE
/usr/local/lib/node_modules/remixd/lib/bin/remixd.js:35
throw new Error(error);
^
Error: TypeError: Class constructor PluginClient cannot be invoked without 'new'
at Object. (/usr/local/lib/node_modules/remixd/lib/bin/remixd.js:35:15)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3


texts: Calling a smart contract function inside another in web3

texts:
Here is  my code Sample in js script connected to ContractInstance through web3:

ContractInstance.Fire(function(error,res){
   if(!error){ContractInstance.dead.call(function(err, result){
              console.log(result);});}
             });

ContractInstance.dead.call(function(err, result){
                  console.log(result) });

So when I call fire function of contract then my dead variable
changes to true (I confirm it in remix )
And then I call dead variable inside Fire function.
Somehow it prints false in the console, but later when I call it
outside the function it prints true.

I don't know why this is happening maybe because

when I call fire function it stops for a while because metamask asks
for confirmation .
or it might be due to the fact that it does not update in the
contract so quickly.

Can somebody help me how should I call dead variable just after the the fire function is called ?


texts: geth.exe checksum is differant than what is writen on the website but the installers checksum is correct. is this an issue?

texts:
I started syncing geth with this command he command:
geth --rpc --etherbase <pulbic wallet adrress> --syncmode=fast --cache=2048

and about 25 hours later, the syncing stopped and this error showed up:  https://pastebin.com/YGUiexQD
so I ran the command again to resume it but it didn't continue syncing, instead, it gave me this error (it's not the exact same text as the last one but it's similar): https://pastebin.com/PrtxpFu7
It isn't a problem with the available storage because I have around 100 MB of storage free.
I asked in the Geth discord server for help and one of the people there told me it could be a problem with the ram or a problem with the checksum. I ran the memory diagnostics program and there weren't any problems so it must have been a problem with the checksum.
I checked the Checksum of geth.exe and compared it to what was written in https://geth.ethereum.org/downloads/ (Windows 64 bit installer geth 1.9.25) and it wasn't the same.
The checksum of geth.exe is: 89e048a0176ac1c92812eb4141c190b6
While the checksum on the website and the installer is for the same version is: 89e048a0176ac1c92812eb4141c190b6
Is that ok? or is it a problem with my installation? If it is, how do I download the correct one? I tried downloading it again and installing geth again but still the same result.
If the problem isn't with the checksum after all so what is it?
Thanks for your time people!


texts:
So the code is

struct A {
    uint8[] a;
}

I want to initialize A by A a = A([1,2,3]);. However, solc says that can't convert uint8[3] to uint8[].

In conclusion, I am looking for a way to convert fixed-length array to dynamic-sized array. (without recreating the array by push n times)


texts: How can I locate where I’ve sent eth I used a saved address I thought was unusual

texts: Quite new to crypto. Have sent eth to a pre saved address I thought was Uniswap - how do I recover it?


texts:
I'm trying to store transactions in a database and want to generate a unique identifier from the transaction data.  It must not change   My data source is api.etherscan.io, and I am currently making an id from the transaction blockHash + hash, eg:

Given this transaction (with hashes are shortened for clarity):

{ blockNumber: '6564583',
     timeStamp: '1540241421',
     hash:
      '0xf59dc77',
     nonce: '34',
     blockHash:
      '0x19f51a3',
     transactionIndex: '141',
     from: '0x83b2d2289f1a666659a0261f4e0cd046386d586f',
     to: '0x164013dfdfbf67b0dfca341ff12c4a616fb2a44a',

My database id would be something like 0xf59dc77_0x19f51a3.

Is this enough to guarantee uniqueness, or is there more?


texts: How does The DAO reimburse erroneous transactions to the sender?

texts: Looking at the account of The DAO in a blockchain explorer, multiple transactions are marked as Error occurred during contract Execution. Most of the time this seems due to an out of gas exception, sometimes with quite some ether (like this one with 15k ETH!) in the transaction. On the one hand transactions which cause an exception still transfer the value to the recipient but on the other the sender seems to be able to re-send these Ether later. How can the DAO send those Ether back to the sender if the contract execution stopped due to an exception? Does the DAO re-imburse everything if it expects that there will be an out of gas exception and then throws?


texts: Transaction being reverted by EVM during contract creation (Web3 / ethereumjs-tx)

texts:
Hey guys I am running into an issue deploying a smart contract with Web3 to the Ropsten network. The code is running seemingly correctly, and there is a contract address being created, but if I check the transaction hash on Etherscan it shows that there has been an error in executing the contract. I don't think it's the contract itself as I've tested a couple contracts and they both have the same error.

const fs = require("fs");
const solc = require('solc');
let Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;

const testnet = 'https://ropsten.infura.io/v3/APIKEY';

const address = '0x0764eDcCD0278Ee60C421148B8baB812306D90D5';

const privateKeyValue = 'PRIVATEKEY';

const privateKey = new Buffer(privateKeyValue, 'hex');

const web3 = new Web3(new Web3.providers.HttpProvider(testnet));

const input = fs.readFileSync('contract3.sol');
const output = solc.compile(input.toString(), 1);

const abi = JSON.parse(output.contracts[':ERC20Interface'].interface);

const contract = new web3.eth.Contract(abi);

const weiAmount = web3.utils.toWei('1', 'ether');

let data = contract.methods.transfer(address, weiAmount).encodeABI();

async function main(){
  const gasPrice = await web3.eth.getGasPrice();

  const gasPriceHex = await web3.utils.toHex(gasPrice);

  const gasLimitHex = await web3.utils.toHex(7957355);

  const nonce = await web3.eth.getTransactionCount(address);

  const nonceHex = await web3.utils.toHex(nonce);

  const rawTx = {
    // from: address,
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: data,
    value: web3.utils.toHex("97534000000000000"),
    chainId: web3.utils.toHex(3),
  };

  const tx = new Tx(rawTx, {'chain':'ropsten'});
  tx.sign(privateKey);
  const serializedTx = tx.serialize();

  console.log(serializedTx + 'serialized tx');

  const promiseEvent = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));

  return promiseEvent
    .on('transactionHash', (txHash) => {
        console.log('TRANSACTION HASH');
        console.log(txHash);
        console.log('TRANSACTION HASH');
      }
    )
    .on('confirmation', (confirmNumber, receipt) => {
        console.log('CONFIRM NUMBER, RECEIPT');
        console.log(confirmNumber, receipt);
        console.log('CONFIRM NUMBER, RECEIPT');
      }
    )
    .on('error', (error => {
        console.log('ERROR');
        console.log(error);
        console.log('ERROR');
      })
    );

}

main();

Here's a link to the transaction hash: https://ropsten.etherscan.io/tx/0x8f703e3f87486baa60725186e9469d65f8355af94c8f9f43baae2d4aa5cb39b0

Versions are as follows:
Web3 = 1.2.1
ethereumjs-tx = 2.1.0
solc = 0.4.25

Does anything seem out of sorts here? This is my first project trying to deploy a smart contract so I'm uncertain of the error and the tinkering I've been doing has been fruitless so far. Thanks!


texts: What's the difference between solc's bin bytecode versus bin runtime?

texts: Solc says that bin-runtime is the runtime part of the contracts. What exactly is the runtime bytecode part and how does it differ from bin bytecode output?


texts:
I am reading an article, it says:

  To enable deployment on the Ethereum platform, the contract functions
  are compiled into EVM bytecode and a piece of code called function
  selector is added, which serves as an entry point into the contract
  code.

Can some body please tell me what is a function selector?

I tried google and found:

  The first four bytes of the call data for a function call specifies
  the function to be called. It is the first (left, high-order in
  big-endian) four bytes of the Keccak-256 (SHA-3) hash of the signature
  of the function. The signature is defined as the canonical expression
  of the basic prototype without data location specifier, i.e. the
  function name with the parenthesised list of parameter types.
  Parameter types are split by a single comma - no spaces are used.

I can't understand what is call data?

Some body please guide me.

Zulfi.


texts: Does "this" keyword changes msg.sender on inherited methods invocations?

texts:
Take this scenario:

Contract A {
   function whoIsSender() public returns (address){
      return (msg.sender);
   }
}

Contract B is A {
   function withThis() public returns (address){
      return (this.whoIsSender());
   }

   function withoutThis() public returns (address){
      return (whoIsSender());
   }
}

I was expecting both functions to return the same. Apparently it is not. It seems that using the this keyword breaks it to a contract-to-contract invocation and then msg.sender becomes the contract address instead of the wallet? Is this by design and can someone explain why?


texts:
I wanted to run two geth instance simultaneously using
First console
geth --ws --ws.origins http://localhost:3000 --ws.port 8545 --ws.api eth,net,web3,personal --datadir="F:\EthereumMainNet`

Second console
geth --ws --ws.port 8546 --ws.api eth,net,web3,personal --datadir="F:\EthereumMainNet

and I get error about the folder being in used. Is it possible to run multiple instance sharing same --datadir? or do I need to duplicated the EthereumMainNet on different folder to be able to use by other?


texts: Why is it that when you give someone approval to spend funds, they cannot approve someone else to spend?

texts: Perhaps, this is already possible, but when I approve someone to spend tokens on my behalf using the approve method, why can't they just delegate their spending authority to someone else?


texts: Pegging a private chain to Ethereum public blockchain

texts: Are there any good tutorials or resources for sidechain development or are these just specialized private chain pegged to the Ethereum network?