texts:
Knowing that
account0 = 0x2ac971cfceb478a3db5a43598e098839007cec34
account1 = 0x55990a8c443a0eb296cff4bece4c54350185b019

I started testrpc. After that, I called a function buyItem(moneyPaid,{from:account1}) in a javascript test file. Then I verified the msg.sender inside the function. I realized that the msg.sender is not account1. Plus, it changes every time I called the function. Can anyone explain why the msg.sender is not account1 nor any account on the web3.eth.accounts list?


texts: Excuse this if this is a dumb question. Would the whole internet at some scale be something we can put on the ethereum blockchain?


texts: myc:90:6: ParserError: Function, variable, struct or modifier declaration expected

texts:
pragma solidity ^0.5.0;

// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
  function totalSupply() public view returns (uint);
  function balanceOf(address tokenOwner) public view returns (uint balance);
  function allowance(address tokenOwner, address spender) public view returns (uint remaining);
  function transfer(address to, uint tokens) public returns (bool success);
  function approve(address spender, uint tokens) public returns (bool success);
  function transferFrom(address from, address to, uint tokens) public returns (bool success);

  event Transfer(address indexed from, address indexed to, uint tokens);
  event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
    c = a + b;
    require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
    require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
    c = a / b;
 }
}

contract SkyClout is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it

uint256 public _totalSupply;

mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;

/**
 * Constrctor function
 *
 * Initializes contract with initial supply tokens to the creator of the contract
 */
constructor() public {
    name = "SkyClout";
    symbol = "SCLO";
    decimals = 18;
    _totalSupply = 4200000000000000000000000000;

    balances[msg.sender] = _totalSupply;
    emit Transfer(address(0), msg.sender, _totalSupply);
}

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

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

function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
    return allowed[tokenOwner][spender];
}

function approve(address spender, uint tokens) public returns (bool success) {
    allowed[msg.sender][spender] = tokens;
    emit Approval(msg.sender, spender, tokens);
    return true;
}

function transfer(address to, uint tokens) public returns (bool success) {
    balances[msg.sender] = safeSub(balances[msg.sender], tokens);
    balances[to] = safeAdd(balances[to], tokens);
    emit Transfer(msg.sender, to, tokens);
    return true;
}

function transferFrom(address from, address to, uint tokens) public returns (bool success) {
    balances[from] = safeSub(balances[from], tokens);
    allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
    balances[to] = safeAdd(balances[to], tokens);
    emit Transfer(from, to, tokens);
    return true;
}


texts: How do I get the return value of a solidity function with web3?

texts:
The docs mention using

MyContract.methods.myFunction().call().then(console.log);

but methids methods I get the error then I get the error that the function is undefined.

The code below doesn't give errors but only returns null in the browser console.

$('#getKidneyIds').click(async () => {
  await contract.getKidneyIds(err => console.log(err));
});

This is my contract
This is the javascript


texts: How can a transaction be out of gas but still complete?

texts:
This one has me scratching my head:
This transaction (which sent in a value of 0.01 ETH) executed correctly according to etherscan:

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

However:

1- I got an error in the callback that said:

  "Error: The contract code couldn't be stored, please check your gas amount."

..and the Total Gas Used looks to be higher than the max gas allowed.

2- Although the Tx says that 0.005 ETH was transferred to two wallets, neither of them actually show that transfer having happened:
https://etherscan.io/address/0xc122ca236edf7b33fb73fbb459a08f7935e6c96b
https://etherscan.io/address/0x39267ec3f4e1610cd871d3545e01918f1dba7b84

So I am totally puzzled. If there was not enough gas, I would expect the TX to fail and to lose the gas, but not the 0.01 ETH in value.
If it did not fail, why did I get the error in the callback and no transfer of value to the wallets?

At the moment it looks to me like 0.01 ETH just disappeared - it left the paying wallet, but did not arrive in the receiving wallets.

Can anyone explain?

Many thanks!


texts: Canonical way of setting external contract address?

texts:
There seem to be at least two ways of setting the address of an external contract:

At deploy/constructor time: function contractName(address _otherContractAddress)
A setter function that can be called once the contract is deployed: function setExternalAddress(address _otherContractAddress)

What are other ways of doing this and/or is there a canonical way of doing so?  I am leaning towards the second solution above because it is more flexible post-deploy and the deploy process will be simpler.


texts: In Ethereum: Who does keep track of users Ether balance and update them?

texts: It's not clear to me how the user's account is updated, and who does it. For instance, who update users account balance?


texts: How does the Solidity compiler translate the `using .. for` statement?

texts:
I'm trying to figure out how using [Library] for [type] is compiled by the solc compiler.  I noticed that address placeholders are not in the bytecode as with other library references.  So what exactly does the compiler do here?

I understand from the documentation, that it 'attaches' the functions to a type, but does that mean it takes the relevant library code and adds it to the compiled bytecode?


texts: How do I determine the constructor ABI for Etherscan contract verification?

texts:
I am facing issues trying to verify a contract that I deployed on Rinkeby.

My contract constructor has 3 parameters, how do I pass values of these parameters in the contract verification form?

How do I determine the constructor ABI for my contract. Btw, I am using compiler version 4.11 and the contract was built using truffle framework.

Any help would be truly appreciated.


texts: Notifying a smart contract of payments on other blockchains

texts:
Suppose I'm running an ICO and accepting other coins, in addition to ether. Whenever somebody sends me her bitcoins, I need to update her token balance.

Question: how do I make my smart contract "know" that the bitcoins are received? Not just bitcoins, any other altcoins.

In other words, whenever somebody sends her money to a certain bitcoin (or litecoin) wallet, I need to receive a notification. Is it possible?


texts:
While working with Infura in the past, if I remember correctly, I had troubles with retrieving events from old (non-recent) blocks.
Does the trouble (not only with Infura but with other popular Ethereum nodes) still exist?
In fact, I want to be able to retrieve events from very old blocks, even 100 years old (in the future).
Is it better to store such very old data on-chain? (It won't take much storage because it's just one storage slot per user.)


texts: EstimateGas reverts, actual transaction works

texts:
On Rinkeby I'm trying to estimate gas and send ERC-20 Weenus tokens.
If I shove the necessary data into an estimateGas call to Infura Rinkeby it returns with an error of execution reverted.
{
    "id": 0,
    "jsonrpc": "2.0",
    "method": "eth_estimateGas",
    "params": [{"to":"0xaFF4481D10270F50f203E0763e2597776068CBc5","data":"0xa9059cbb0000000000000000000000000F449538a11f1110A0b55319334d8996aA154Dd800000000000000000000000000000000000000000000000006f05b59d3b20000","gasPrice":"0x1fe5d61a00","value":"0x0"}]
}

If I use the exact same data with the correct nonce  and a gasLimit of 41395 (taken from Metamask) the transaction executes just fine.
So why does the gas estimation not work?


texts: How many iterations can I make per a loop inside Solidity's view (or pure) function?

texts:
Lets say that I have a view function that has a loop and that I must use this loop. This loop is calling another view function to verify some data per index key.
The view function is free to execute without getting charged for a GAS.
For example, this works
function retrieve() public pure returns (uint256){
    uint256 ret = 0;
    for(uint t=0;t<1000;t++){
        ret = t;
    }
    return ret;
}

However, this does not work
    function retrieve() public pure returns (uint256){
        uint256 ret = 0;
        for(uint t=0;t<1000000000000;t++){
            ret = t;
        }
        return ret;
    }
}

How many times can I iterate this kind of a loop in a view ?
In other words, what is the maximum number between 1000 and 1000000000000 (see the code example above) that I can use and make the loop work ? How is this number determined ?
Edit: I was able to make 15000 iterations on a testnet but not 20000, so I would limit it to just 10000 iterations as a max, assuming it is just calling the index and verifying the value (and use try-catch if possible). Regardless, I still don't know what determines the number, and how it is determined.


texts: Can I make a "secret" invite only Smart Contract?

texts:
I have a public smart contract where I am able to make a secret and hash it within the contract. I then share the "secret" with N number of my friends and with the secret they can create a new hash (secret + private key) to prove to the contract that they in fact know the secret and have access to send funds.

The contract would only know the secret internal hash + the new sent hash + the msg.sender public key. Would this be enough to prove to the contract that the msg.sender know the secret and is allowed access to the contract functions?

Can't this be done? It sounds like a zero-knowledge proof algorithm, but I am not an expert in cryptography so not sure if it's a viable solution.


texts: address.transfer executes but doesn't make the transfer

texts:
I'm using Metamask and web3.js to connect with a donation smart contract. Following is my JavaScript function:

function withdraw(){
    const contractInstance = connectToContract();

    var withdrawAmount = parseInt(document.getElementById('withdraw-amount').value);
    var goalID = 0;
    var donationEvent = contractInstance.DonationAction();

    contractInstance.withdraw.sendTransaction(goalID, web3.toWei(withdrawAmount, 'ether'), {

    }, function(err, wei) {
        if (err)
          console.log(err);
    });

    donationEvent.watch(function(error, result){
        if (!error) {
            if (result.args.action == 'unverified'){
                window.alert('The goal is still ' + result.args.action);
            } else if (result.args.action == 'insufficient balance') {
                window.alert('There is ' + result.args.action + ' in the account. Send a value less than ' + result.args.amount);
            } else if (result.args.action == 'donated') {
                window.confirm('You have successfully ' + result.args.action + ' ' + result.args.amount);
            }
        } else {
            console.log(error);
        }
    });
}

Following is my contract code:

struct Goal {
        address payable charityAddress;
        string status;
        uint amountNeeded;
        uint amountRaised;
        uint amountWithdrawn;
        uint balance;
        string proof;
        address verifier;
    }

function withdraw(uint _goalID, uint _amount) payable public {
        if (bytes(goals[_goalID].status).length != bytes("verified").length) {
            emit DonationAction(msg.sender, _amount, "unverified");
            return;
        } else if ((_amount * 1000000000000000000) > goals[_goalID].balance) {
            emit DonationAction(msg.sender, _amount, "insufficient balance");
            return;
        }

        goals[_goalID].balance = goals[_goalID].balance - _amount;

        goals[_goalID].charityAddress.transfer(address(this).balance);
        goals[_goalID].amountWithdrawn = goals[_goalID].amountWithdrawn + _amount;

        emit DonationAction(msg.sender, address(this).balance, "withdrawn");
    }

The transaction executes without any error but the ether doesn't get transferred to the Metamask account. The contract balance doesn't reduce either. And none of the events are emitted.

Is there something I'm doing wrong?


texts:
So, I've been using MetaMask to trade on various DEX. On 6 March, all of my tokens were moved out of my MetaMask wallet. I am using a cold wallet to HODL but always keep a small balance for trading in Metamask. Is it possible someone could have gained access when I connected Metamask to some new yield farms like pooltoken.finance or meerkat.finance? It's impossible for someone to have gotten access to my seed phrase.
I traced the funds and this seems to be highly professional and large scale. the funds all end up in this account: 0x0823beBa3f1F0CAad19Ce9e5724C4f5CE0a2Fb97. Unlikely to collect so many seed phrases from so many people.
Anyone has any thoughts?


texts: Is it safe for smart contracts to handle secrets?

texts:
Is the runtime environment of a smart contract going to be seen by the hosting node? If not, how?

Can the smart contract safely pass an API key to memory?

Should Solidity developers just deem smart contracts runtime as endangered similarly to web apps front ends?


texts: When submitting smart contract calls to infura or subscribing to a contract's events, does infura have it's own finality bound or will I have to implement this in the client?


texts:
I am currently making a game where you collect gear pieces and upgrade them. There will not be a 1-1 upgrade, but rather 3-1, meaning 3 items may or may not upgrade to 1.

I am aware of the difference between the two different ERC standards, but as this is my first dapp I am not sure which 1 to go for. I am estimating there to be between 1m-10m different item-stat combinations. I am also hoping to add new layers of items in the future, so hoping for it to be a scalable solution.

Also, what may be a good implementation for the suggested token standard? I was thinking maybe an array of all ERC 721 tokens, with a map that layers account addresses to the array indexes. But then how will I fall with the empty array slots after I burn tokens?


texts: Can i use the public chain to bootstrap my own private chain?

texts: I'd like to take the existing public chain and use it to bootstrap a private chain. Change the difficulty and add custom endpoints.


texts: Can't initlized contract class in mythrill

texts:
I'm doing my first steps in mythril.
Here is the code I'm trying to run:

from mythril.ether.soliditycontract import SolidityContract
from mythril.laser.ethereum import svm
contract = SolidityContract("./examples/rubixi.sol", "Rubixi")

But I get the following error:

 Traceback (most recent call last):
  File "/home/username/PycharmProjects/untitled/p.py", line 4, in
    contract = SolidityContract("./examples/rubixi.sol", "Rubixi")
  File "/home/username/.local/lib/python3.6/site-packages/mythril/ether/soliditycontract.py", line 99, in init
    super().init(code, creation_code, name=name)
  File "/home/username/.local/lib/python3.6/site-packages/mythril/ether/ethcontract.py", line 20, in init
    self.disassembly = Disassembly(self.code, enable_online_lookup=enable_online_lookup)
  File "/home/username/.local/lib/python3.6/site-packages/mythril/disassembler/disassembly.py", line 50, in init
    signatures.write()  # store resolved signatures (potentially resolved online)
  File "/home/username/.local/lib/python3.6/site-packages/mythril/support/signatures.py", line 129, in write
    self.signatures_file_lock.aquire()  # try to aquire it within the next 10s
  File "/home/username/.local/lib/python3.6/site-packages/mythril/support/signatures.py", line 40, in aquire
    self.lockfile.touch(mode=0o0000, exist_ok=False)  # touch the lockfile
  File "/usr/lib/python3.6/pathlib.py", line 1236, in touch
    fd = self._raw_open(flags, mode)
  File "/usr/lib/python3.6/pathlib.py", line 1044, in _raw_open
    return self._accessor.open(self, flags, mode)
  File "/usr/lib/python3.6/pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
FileNotFoundError: [Errno 2] No such file or directory: '/home/username/.mythril/signatures.json.lck'


texts: How to get public key from private key in C?

texts:
I know the theory behind generating the public address.

convert to 65 byte uncompressed key
removed first "04" byte, we have
5f37d20e5b18909361e0ead7ed17c69b417bee70746c9e9c2bcb1394d921d4ae612d83e3487012034792ff36357ee25f382913cfeb54a8622b7ef35d635d8740 for 0x025f37d20e5b18909361e0ead7ed17c69b417bee70746c9e9c2bcb1394d921d4ae
Keccak this 64 bytes to 32 bytes:
81862025a6a8b333133c9b9ad09d3103ccabfb769edc3e9b01500ca7241d470a
Get last 20 bytes: 0xd09D3103CcABfb769eDc3e9B01500Ca7241D470A

I'm interested if there is a library or code written in C that already does that?


texts: What does PoS formula mean in Vitalik's blog post?

texts:
I don't understand what exactly the PoS formula means in Vitalik's blog post On Stake on the Ethereum blog:

SHA256(prevhash + address + timestamp) <= 2^256 * balance / diff

Why do you need to multiply by 2^256?
Why do you need to divide balance by difficulty?
Does a miner create a candidate block only per second because timestamp is the only difference for new block?

Each variable means:

prevhash: the hash of the previous block.
address: the address of the stake-miner.
timestamp: the current Unix time in second.
balance: the account balance of the stack-miner.
diff: an adjustable global difficulty parameter.


texts: So I got an if-else statement if the price of eth is the same as stop order sell will be = to true, but I also want to do if the price is same or bigger then limit also sell = true. If price under limit it should be false, or if the price was not stop order. So I need if price == StopOrder or price >= LimitOrder in one if statment.


texts: How do I manage unlocking accounts in a test in Truffle

texts:
I have a test that exercises a contract function across different accounts. How do I unlock these accounts in the context of the test?

contract('MyContract', function (accounts) {

    it("should perform differently for different accounts", function (done) {

        var thisContract = MyContract.deployed();

        thisContract.addAccounts([accounts[1], accounts[2]], {from: accounts[0]} ).then(
            function (tx_id) {
              /* this works because I manual unlock acc 0 on geth */
                return thisContract.doSomething({from: accounts[0]});
            }).then(
            function (tx_id) {
              /* is there something here I can do to unlock acc 1? */
                return thisContract.doSomething({from: accounts[1]});
            }).then(
            function (tx_id) {
              /* then here... */
                return thisContract.doSomething({from: accounts[2]};
                done();
            }
        ).catch(done);

    });

});


texts: Call a zero-initialized variable of internal function type

texts:
I was reading solidity documentation about when an assert-style exception is generated. In the 6th point it says:

"If you call a zero-initialized variable of internal function type."

I don't understand it. Can someone give me an example?


texts:
I am rather new to Ethereum and I wonder if the following scenario is possible. I want/need to store some data encoded as a JWT in the blockchain and have it (publicly) accessible via an ID. Only the "owner" of the data can change it, where the ID always remains the same.

As far as I can see, this is achievable via Ethereum EOAs:

Creating:

Owner creates EC keypair
Owner creates an EOA, the public key becoming the ID of this account
Owner stores the JWT in the account

Retrieving:

Viewer knows the ID (i.e. the public key of the owner). How is irrelevant here.
Viewer fetches contract from the chain and extracts the enclosed JWT

Updating:

Owner creates a transaction to change the JWT in the account
Transaction is signed with his private key

Does this check out or do I have an error in this concept? Maybe I misunderstood how details work in Ethereum or with EOAs in general.

Edit: To clarify:

EOA = Externally Owned Account in Ethereum
JWT = JSON Web Token, for the sake of simplicity it is a base64-encoded String, nothing more


texts: How to sign the transaction using Geth in android

texts:
I'm using Geth.aar library for handling ethereum.

I generated the address, gas price, gas estimation, and transaction count.

now I want to sign the transaction.

Please help who knows the answer.


texts:
I am creating a contract which will allow an atomic transfer of a token with only the buyer needing to pay gas (instead of both parties). I am doing this by creating an agreement with price, quantity and sellerAddress as elements in a bytes32 array which is then hashed and checked against a valid authority signature. (the hash should be the same as the message hash has the same params are hashed together in both cases).

The problem I am running into is that ecrecover is not verifying as true despite the fact that the signature is valid. I understand that this might be because the javascript code which generated the signature was hashing string types for the message and solidity is using bytes32 which will have slightly different data, hence I have casted the bytes32 vars into strings (see code below).

Here is my solidity code:

//buyer pays all the fees, seller doesn't even need to have ether to do trade
function adminAuthorizedSwap(bytes32[] agreement, uint8 adminV, bytes32 adminR,
    bytes32 adminS) public payable returns(bool)
{
    // 0 = price, 1 = quantity, 2 = sellerAddress
    **//hash is 64 + 0x, thus 66.**
    bytes memory prefix = '\x19Ethereum Signed Message:\n66';
    bytes32 agreementHash = keccak256(prefix, bytes32ToString(agreement[0]),
        "|", bytes32ToString(agreement[1]), "|", bytes32ToString(agreement[2]));
    //if the agreement hash matches then the trade can take place
    bool agreementIsValid = ecrecover(agreementHash, adminV, adminR, adminS) == admin;
    if(agreementIsValid && msg.value == uint(agreement[0]) *
        uint(agreement[1]))
    {
        //send over ether and tokens
        balances[msg.sender] += uint(agreement[1]);
        balances[address(agreementHash[2])] -= uint(agreement[1]);
        uint commission = (msg.value / 100) * transferFee;
        uint sellerAmt = msg.value - commission;
        address(agreementHash[2]).transfer(sellerAmt);
        admin.transfer(commission);
        numOfTransfers++;
        return true;
    }
    else revert();
}

function bytes32ToString(bytes32 x) public pure returns (string) {
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
        byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
        if (char != 0) {
            bytesString[charCount] = char;
            charCount++;
        }
    }
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
        bytesStringTrimmed[j] = bytesString[j];
    }
    return string(bytesStringTrimmed);
}

The signature is creating in Javascript using the following:

createSaleDeed : (price, quantity, address, wallet) =>
{
    try
    {
        //wallet is from: ethers-wallet
        let sig = wallet.signMessage(price, "|", quantity, "|", address).slice(2);
        let signatureObject = {};
        signatureObject.r = "0x" + sig.slice(0, 64);
        signatureObject.s = "0x" + sig.slice(64, 128);
        signatureObject.v = parseInt(sig.slice(128, 130), 16);
        signatureObject.signature = "0x" + sig;
        signatureObject.originalMessage = price + "|" + quantity + "|" + address;
        return signatureObject;
    }
    catch(e)
    {
        console.log(e);
        return e;
    }
}

Where the output of this code is:

{"r":"0x40952c3bbf6fc314d6469c8eb401d8a371980cc03443e6b0dd2c52403ff9db00","s":"0x07a63c8578da73818e4d7dba9ff5e3b48f608d637cfc0dfe33a2dccc663b375c","v":28,"signature":"0x40952c3bbf6fc314d6469c8eb401d8a371980cc03443e6b0dd2c52403ff9db0007a63c8578da73818e4d7dba9ff5e3b48f608d637cfc0dfe33a2dccc663b375c1c","originalMessage":"100000000|1|0xFE6d4bC2De2D0b0E6FE47f08A28Ed52F9d052A02"}

My solidity code is hitting the revert on the if/else statement...

Thank you!


texts: What's the difference between a Slot and a Block?

texts:
I'm running a private beacon chain with the Lighthouse client with some local validators:

Mar 23 10:35:08.281 INFO Block from local validator              block_slot: 13009, block_root: 0x2bab…25a6, service: http
Mar 23 10:35:12.010 INFO Attestation from local validator        slot: 13009, index: 0, source: 403, target: 403, service: http
Mar 23 10:35:14.001 INFO Synced                                  slot: 13009, epoch: 406, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier
Mar 23 10:35:20.247 INFO Block from local validator              block_slot: 13010, block_root: 0x91df…1c45, service: http
Mar 23 10:35:24.013 INFO Attestation from local validator        slot: 13010, index: 0, source: 403, target: 403, service: http
Mar 23 10:35:26.000 INFO Synced                                  slot: 13010, epoch: 406, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier

It shows a Block from local validator - fine, I guess that's a block as in block chain, isn't it? That block has a block_slot: 13009 - is that the block number? What is a slot?

What is an Attestation from local validator for slot: 13009?

Now, and this is what puzzles me most, once I shut down my validators, I will see the following:

Mar 23 10:39:02.001 INFO Synced                                  slot: 13028, epoch: 407, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier
Mar 23 10:39:14.000 INFO Synced to current epoch                 current_slot: 13029, head_slot: 13028, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier
Mar 23 10:39:26.000 INFO Synced to current epoch                 current_slot: 13030, head_slot: 13028, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier
Mar 23 10:39:38.001 INFO Synced to current epoch                 current_slot: 13031, head_slot: 13028, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier
Mar 23 10:39:50.001 INFO Synced to current epoch                 current_slot: 13032, head_slot: 13028, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier

What is current_slot: 13032? Is it empty on purpose? Why is it progressing even though the validators are offline?

Once I turn back on my validators, it creates blocks in the current slot skipping the previous ones:

Mar 23 10:40:20.267 INFO Block from local validator              block_slot: 13035, block_root: 0x829b…a2ef, service: http
Mar 23 10:40:24.016 INFO Attestation from local validator        slot: 13035, index: 0, source: 403, target: 403, service: http
Mar 23 10:40:26.000 INFO Synced                                  slot: 13035, epoch: 407, finalized_epoch: 398, finalized_root: 0x17e7…eee2, peers: 3, service: slot_notifier

So what is a slot and what is a block and why is there a need to have that differentiation?


texts: Can anyone freely call the `tokenFallback()` function in ERC223?

texts:
Since the function seems to always be implemented as public, can't an unfair user just call the tokenFallback() function of a receiver contract?

That way one could let contracts believe that they received the appropriate amount of money, when they actually haven't.


texts:
I have a struct like so :

struct fooStruct {
  uint foo;
  uint figther;
}

I would like to initialize that struct but it won't be stored in a mapping but inside an array.

Is there a way to initialize the struct like

fooStruct myStruct = fooStruct.new(par1,2,3)


texts: Can the smart contracts guarantee that I can get the coffee that I paid in cryptocurrency?

texts:
Let's assume that there is no any protection from any authority, government or law. They are completely absent.

Can the smart contracts guarantee that I can get the coffee in the real world that I paid in cryptocurrency and also guarantee that the seller can get the money after I received the coffee?


texts: Solidity | How to throw "string" argument using Send() function?

texts:
I have a function which get a parameter as String and compare it like below.

function freezeAccount(string _value) onlyOwner public {
    if (keccak256(_value) == keccak256("true")){ isFrozen = "true"; }
    if (keccak256(_value) == keccak256("false")){ isFrozen = "false"; }
}

Above is my smart contract code.
I wanna use this my method using web3 so I'm trying to make transition by send() function like below.

export const setFreezeAccount = value => {
console.log("setFreezeAccount :: value: ", value);
  const str = value.toString();

  myContract.methods
  .freezeAccount(str)
  .send({ from: TOKENOWNER })
  .then(receipt => {
    console.log("setFreezeAccount :: receipt: ", receipt);
  })
  .catch(err => {
    console.log("setFreezeAccount :: err: ", err);
  });
};

The freezeAccount() function is working well on Remix IDE but the Error: Invalid JSON RPC response: ""  error returned When I execute the setFreezeAccount() function.


texts: See state changes of a simulated function call

texts:
assuming I am working in hardhat framework (ethers, web3) using public Infura/Alchemy node. Is it possible to simulate transactions then retrieve all the storage changes?
Thanks in advance.


texts: How to create a variable in storage via the solidity assembler

texts:
Similar to this question How to get access to the storage array through the solidity assembler?

But instead of accessing a storage variable, I want to create a new storage variable via assembly. That means instead of declaring a variable, I use a function to generate the variable.

Instead of:

contract MetaCoin{
 uint A;
}

Do this:

contract MetaCoin{
 function createVariableA(){
  //assembler code here
 }
}

After generating the variable, other functions can somehow use it like a normal declared variable.

Is this possible?


texts:
I am running go-ethereum that has x amount of ether, i want to distribute some ether to friends.

Rather than 5 seperate transactions:

eth.sendTransaction({from: eth.accounts[0], to: "0xxxxxxxxxxxxxxxxxxxxxxxxx1", value: web3.toWei(1, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: "0xxxxxxxxxxxxxxxxxxxxxxxxx2", value: web3.toWei(1, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: "0xxxxxxxxxxxxxxxxxxxxxxxxx3", value: web3.toWei(1, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: "0xxxxxxxxxxxxxxxxxxxxxxxxx4", value: web3.toWei(1, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: "0xxxxxxxxxxxxxxxxxxxxxxxxx5", value: web3.toWei(1, "ether")})

Can i somehow send to multiple addresses in a single transaction? I'm trying to reduce fees.


texts: What is the mean transaction size and average number of transactions per block on the Ethereum blockchain?

texts:
I found an April 7, 2017 post on Bitcoin Stack Exchange saying that

  Over roughly the past two months, the mean transaction size was about
  506 bytes, and the average count of transactions per block was 1,956.
  Current figures can be found here: Tradeblock Historical Data

I followed the link to see if I could find that sama data for Ethereum but could not locate it. Does anyone know the answer (or how / where to find it), and how it has evolved over time?


texts: Can multiple transaction be on the same block?

texts: It seems like multiple transaction can be grouped under the same "block" number?


texts: Transaction reverting when it hits Require statement in function

texts:
I have below contract. I deploy my contract in remix and put 1 ether in value but when I execute enter() function I get an error.

This is the contract:

pragma solidity ^0.4.17;

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

constructor() public payable{
 manager = msg.sender;
}

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

    players.push(msg.sender);
}

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

function pickWinner() public {
    uint index = random() % players.length;
    players[index].transfer(this.balance);
}
}

This is the Error message:

from:0xca3...a733c
to:Lottery.enter() 0xb87...69cfa
value:0 wei
data:0xe97...dcb62
logs:0
hash:0x1a5...811a1

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


texts: Do state-channels only work for transactions that affect the sender negatively?

texts:
Mind the payment-channel case:

Parties A and B lock the state of their balances, S0, on the blockchain.
A makes a transaction by updating the state to S1, signing it and sending to B.
B makes a transaction by updating the state to S2, signing it and sending to A.

That can go on and on indefinitely. Now, suppose, instead of payment-channel, we're trying to implement a chess game off-chain. They bet $50 on the outcome.

Players A, B init a new game on the blockchain and lock the board state, S.
Player A performs a move by updating the board state to S1, signing it, sending to B.
Player B checks A's move was valid, performs a transaction the same way.

That, again, goes on for a while. As soon, though, as A performs a move that is clearly advantageous to him - say, capturing B's queen - B will just not sign anything on top of A's move, forcing him to continue on the blockchain.

Does that mean that state-channels only work for transactions that affect the sender negatively?


texts:
So far I've gotten these rather cryptic messages while syncing:

Imported new block headers
Imported new block receipts
Imported new state entries
Stalling state sync, dropping peer

What do they mean?
What is a block header? What is a block receipt? And what is a state entry?


texts:
I am trying to access an event from my contract to observe in Javascript.  I expect to get c.QuantumPilotKeyPurchased but that is undefined

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
let c = new web3.eth.Contract(abi, keyaddress);
console.log(c.events);
console.log(c.QuantumPilotKeyPurchased);

Output:

node server.js
{ QuantumPilotKeyPurchased: [Function: bound ],
  '0x55985f5332be13e699aaa51a5d3c003941f60e74af84533ebab5626b72cf3f51': [Function: bound ],
  'QuantumPilotKeyPurchased(address)': [Function: bound ],
  allEvents: [Function: bound ] }
undefined

See the above^

Why is this happening?


texts: Difference between STOP and INVALID opcode

texts: STOP halts execution and according to this mentions INVALID is used as an abort. Is the difference between these opcodes purely semantical?


texts: Setting up MyEtherWallet on iOS device from Coinbase

texts: Can I securely set up and store a MyEthereumWallet on iOS only without an computer? I want to transfer ethers from Coinbase.


texts:
I am reading this article : https://medium.com/@jgm.orinoco/why-use-the-withdrawal-pattern-d5255921ca2a

It seems interesting. Could anyone explain the idea of the Withdrawal pattern in a simple way ?


texts:
pragma solidity 0.4.24;

contract ArraysExample {
   uint[] numbers;

   function addUser() public returns (uint[]) {
      numbers.push(random());
      return numbers;
   }

   function random() private view returns (uint8) {
      return uint8(uint256(keccak256(block.timestamp, block.difficulty))%251);
   }
}

When I call the following contracts method

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

const fs = require("fs");
const abi = JSON.parse(fs.readFileSync("abi.json", "utf8")).abi;
const contractAddress = "0x1fba6995e24ffa28bd0d14acd16e6f4cdac8df68";

const contractInstance = new web3.eth.Contract(abi, contractAddress);

contractInstance.methods
.addUser()
.call()
.then(numbers => console.log(numbers));

I get this response when I execute the following code instead of ['142', '215', '8' ... ]:


texts: Cant receive wETH to my contract after swap on uniswap

texts:
I write a simple contract to do a flash loan from aave and interact with uniswap in it. I found out that no wETH is sent to my contract after swaping on uniswap. Transcations are here: https://kovan.etherscan.io/tx/0xc98a9b944ef4815c95fd8308cec304cc3052e51f696258dbf23f90762c05008a

in which 0x68c78e23a27068fe4e2348b5b3cd6cfff45a0695 is my contract address
here is my code:
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.0;

import { FlashLoanReceiverBase } from "./FlashLoanReceiverBase.sol";
import { ILendingPool, ILendingPoolAddressesProvider, IERC20 } from "./MyInterfaces.sol";
import { SafeMath } from "./MyLibraries.sol";

import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";

contract FlashLoanV5 is FlashLoanReceiverBase {
    address constant kovanDAI = address(0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD);
    address constant uniswapRouterAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    IUniswapV2Router02 private uniswapRouter;
    IERC20 private DAI;

    using SafeMath for uint256;

    event Received(address, uint);
    receive() external payable {
        emit Received(msg.sender, msg.value);
    }

    constructor(ILendingPoolAddressesProvider _addressProvider) FlashLoanReceiverBase(_addressProvider) public {
        uniswapRouter = IUniswapV2Router02(uniswapRouterAddress);
        DAI = IERC20(kovanDAI);
    }

    /**
     * This function is called after your contract has received the flash loaned amount
     * overriding executeOperation() in IFlashLoanReceiver
     */
    function executeOperation(
        address[] calldata assets,
        uint256[] calldata amounts,
        uint256[] calldata premiums,
        address initiator,
        bytes calldata params
    )
        external
        override
        returns (bool)
    {
        // do something
        uint256 loanAmount = amounts[0];
        uniswapSwap(loanAmount);

        // Approve the LendingPool contract allowance to *pull* the owed amount
        for (uint i = 0; i < assets.length; i++) {
            uint amountOwing = amounts[i].add(premiums[i]);
            IERC20(assets[i]).approve(address(LENDING_POOL), amountOwing);
        }

        return true;
    }

    function myFlashLoanCall(uint256 loanAmount) public {
        address receiverAddress = address(this);

        address[] memory assets = new address[](1);
        assets[0] = kovanDAI;

        uint256[] memory amounts = new uint256[](1);
        amounts[0] = 1 ether;
        amounts[0] = amounts[0] * loanAmount;

        // 0 means revert the transaction if not validated
        uint256[] memory modes = new uint256[](1);
        modes[0] = 0;

        address onBehalfOf = address(this);
        bytes memory params = "";
        uint16 referralCode = 0;

        LENDING_POOL.flashLoan(
            receiverAddress,
            assets,
            amounts,
            modes,
            onBehalfOf,
            params,
            referralCode
        );
    }

    //event GetDestAmount(uint destAmount);

    /**
     * Swap from DAI to wETH on uniswap
     */
    function uniswapSwap(uint256 daiAmount) public payable {
        // convert to Wei
        uint256 amountIn = daiAmount;
        //require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');

        require(DAI.approve(address(uniswapRouter), amountIn), 'approve failed.');

        address[] memory path = new address[](2);
        path[0] = address(DAI);
        path[1] = uniswapRouter.WETH();
        uint deadline = block.timestamp + 15;
        uint[] memory amounts = uniswapRouter.swapExactTokensForETH(daiAmount, 0, path, address(this), deadline);
        //emit GetDestAmount(amounts[1]);
    }
}

It will be grateful if anyone can help, thanks!


texts: Test if a map element has been deleted or does not exist?

texts:
I have a map of game IDs to game structs in my Solidity contract.  I want to test if a game struct for a given ID does not exist or has been deleted.  I am using the code below:

// The map that maps a game ID to a specific game.
mapping(uint256 => structGame) public s_mapGameIdToGame;

/// Make sure the game ID has been explicitly set and does not belong to a deleted game.
/// @param _gameId - a valid game ID.
modifier onlyIfValidGameId(uint256 _gameId) {
    // Make sure the game ID has been explicitly set.
    require(_gameId != id_invalid, "The game ID  is invalid.");
    // Make sure the game has not been deleted.
    require(s_mapGameIdToGame[_gameId] != 0, "The ID given belongs to a deleted game.");
    _;
}

Unfortunately Solidity is giving me the following error for the existence check on the game struct:

./contracts/GameFactory.sol:178:17: TypeError: Operator == not
compatible with types struct EtherBandBattlesManager.structGame
storage ref and int_const 0
    require(s_mapGameIdToGame[_gameId] == 0, "The ID given belongs to
a deleted game.");
            ^-----------------------------^

How can I make my existence check/test work?


texts: How to handle multiple solidity versions

texts:
I need Solidity version manager to manage multiple version of solc installed globally.
Is there a rbenv, nvm, pyenv tool for solidity?


texts: Error: Returned error: VM Exception while processing transaction: revert when using methods.MyMethods.Send

texts:
I am writing a simple betting application that will return double the ether deposited by the player, provided they guess correctly the random number generated by the virtual slot machine.
it works like this:

Player inputs their Ethereum Address, a guess and amount they are willing to deposit in the user interface.
if the users guess is the same as the randomly generated number then they receive 2x what they credited to the slot machine. If their guess is incorrect they simply lose their deposit.

Like any slot machine in the real world in order to play you must first credit the machine with some money. Similarly, I am scripting my virtual machine to work in this way except to keep the transaction fees low the ether must be sent to the contract along with the data payload:
here is my solidity code:
   contract Slot_Machine is Mortal{

  // A struct type that defines state variables of a player.
  //Every player has a wallet, amount they are willing to
  //deposit and a guess.

  struct Player{
      address payable wallet;
      uint deposit;
      uint guess;
  }

  address payable slotMachine;

  mapping (address => Player) public player;

  //The random number returned from the generator.
  uint randomNumber;

  constructor() public{
    randomNumber = 5;
  }

  fallback () external payable{}

  receive () external payable{
    require(msg.sender.balance >= msg.value,
          "Insufficient balance to complete transaction.");
  }

  function main(uint pdeposit, uint pguess) public{

    player[msg.sender] = Player(msg.sender, pdeposit, pguess);

    if(player[msg.sender].guess != randomNumber){
      emit Message("Unlucky this time! try again when you are feeling lucky!");

    } else {
          player[msg.sender].wallet.transfer(player[msg.sender].deposit*2 ether);
          emit Message("You Win!");
    }

  }
}

The main function is the method called when the player hits the 'Play' object.
My my issue is that when I call this function using web3 via node, there is no ether credited to the contract.
here is my web3 script:
contract.methods.main(amount, guess).send({from: Hannah, value: amountWei, gas: 3000000}, (error, result) => {console.log(error)})

on making this call I met with this error:
Error: Returned error: VM Exception while processing transaction: revert

However, calling this method without the value option in the send function:
contract.methods.main(amount, guess).send({from: Hannah,gas: 3000000}, (error, result) => {console.log(error)})

returns a Tx number.
So is the former the incorrect way to send ether to a contract while simultaneously calling a method?


texts: Can you run `geth inspect` while geth is running?

texts:
I'd like to get some of the info provided by geth inspect, but it complains about a lock when I try running it, presumably because geth is indeed currently running.
$ geth inspect
...
Fatal: Failed to create the protocol stack: datadir already used by another process

I would be fine stopping geth for a few minutes, but it appears from log messages that it can take around 30 minutes:
INFO [11-11|19:19:35.100] Inspecting database                      count=4996000 elapsed=8.002s
INFO [11-11|19:19:43.108] Inspecting database                      count=10062000 elapsed=16.010s
INFO [11-11|19:19:51.115] Inspecting database                      count=14730000 elapsed=24.017s
...
INFO [11-11|19:50:53.083] Inspecting database                      count=1821919000 elapsed=31m25.985s
INFO [11-11|19:51:01.090] Inspecting database                      count=1828550000 elapsed=31m33.992s
INFO [11-11|19:51:09.097] Inspecting database                      count=1835247000 elapsed=31m41.999s

For my personal use case, I'm not able to stop my geth node for more than a few minutes without potentially incurring eth2 penalties.
But more importantly, it seems like an inspection should be able to be done live, since it's presumably a read-only action. Right?


texts: Listening to transactions on any of the wallets on my full node

texts:
I am running my ethereum full node, and from my application, I generate wallets for users on their request.

Now, what I need to do is that whenever a transaction happens on any wallet created using the full node, I need to do some action using the details of the transaction, like update their balance etc.

So, is there any way built into Geth which will execute a callback whenever such a relevant transaction is recieved?


texts: Can I create & run test cases for smart contract without truffle?How?

texts:
does truffle is  necessary for smart contract testing?
Is there any alternative way, so that we can perform smart contract testing without truffle?


texts: How does the network validate a block in PoS

texts:
In general PoS, the forgers stake their coins and then a validator chosen in a pseudorandom fashion gets the chance to validate a block. But how do the whole network validate it?

In PoW, for example, the whole network can easily verify the block by hashing the solution proposed by the miner, which takes considerably less computational power. Once verified by the network, all full nodes accept the block and work to mine the next block.

What I am confused about is what is the procedure of validation by the network in PoS? How is a forged block accepted as valid and added to the blockchain?

note: I am only a beginner in this and I could not find the answer anywhere.


texts: Setup brownie to run certain test in a specific network

texts:
I am using brownie to run tests and right now my project is using two networks, development and mainnet-fork.
I have a test which only runs in mainnet-fork and I am trying to figure out a way to tell brownie that the test shouldn't be run when I execute:
brownie test -s --coverage --network development

is there a way to do that?


texts: I am trying to make a D'app. But I don't know how to fix this issue of paying gas every time. Do the user or owner need to pay everytime they use the application ? can we make it default gas by some API or code? Please give me a simple example how to make it for the end user.


texts:
In State, use Merkle Patricia Trie for storing data.

"key value" is account address(hash value).

And also, Ethereum block uses MPT for storing transactions.

However, Additionally Ethereum Block use a transaction sequence;

miners already decided the execution sequence of the transaction.

This situation(Transaction have not only hash but also order) looks different from that of the state.

Q. How are transactions stored in a block?

is similar to the state?
If so, how the transaction sequence is considered?


texts:
I sent 3.99 eth to address 0x2cd41e1ba0bb66d3c05eaf8ee031e0c1f8866183

This address was provided by coinexchange.io. This is what I see from them now: "Internal Transactions Please note we do not support incoming 'internal transactions'. Please make sure the service you are using is using a regular transaction for all deposits to our system. We will not recover internal transactions."

I don't understand how you are an exchange and knowing this could happen would still execute as internal transaction. Did I just lose my eth?


texts: How to convert bytes32 to uint8 in solidity ^0.5.0?

texts:
I can see that conversions from bytes to uint used to be much easier in previous versions of solidity. Now, using the same syntax, I get this error:

  TypeError: Explicit type conversion not allowed from "bytes32" to "uint8"

I know about Piper Merriam's library, but I wouldn't add so much code just for a small type conversion. Isn't there a more elegant way?

Using solidity 0.5.2.


texts: Why is my web3j wrapper failing to generate?

texts:
I've created a smart contract in solidity which I've compiled with solc into a .bin & a .abi file. However, when I run the generator on the .abi and .bin files it returns a JSONParseException citing an unexpected character.
io
This is my smart contract:

    pragma solidity ^0.4.9;

    contract Contract {

      address public creator;

      event Log(uint256 id);

      function Contract() {
        creator = msg.sender;
      }

      function kill() {
        selfdestruct(creator);
      }

      function add(uint256 id) {
        Log(id);
    }
   }


texts:
Googling "Ethereum Roadmap" just brings up outdated blog posts.

Where can i find the current, updated roadmap?


texts: A object returned for public uint256 instead of integer when calling a contract getter

texts:
My app calls a public method to retrieve value from a contract with ethers 5.1. Here is the code:
                let contractValue = await contract_forsale.value();  //value is a public getter
                console.log("contractValue in deal : ", contractValue); //<<==an object returned
                console.log("escrow is : ", escrow);  //<<==33
                console.log(" contractValue != escrow ", contractValue != escrow)  //<<==false

Here is the console output:
 contractValue in deal :  {"hex": "0x21", "type": "BigNumber"}  //<<==shall be 33. why obj is returned???
 LOG  escrow is :  33
 LOG   contractValue != escrow  false  //<<== false???

I don't quite understand why the returned is an object instead of an integer. Here contractValue != escrow is false in log output and this is confusing. Since contractValue returned is an object and escrow is integer 33 and they shall not equal (true from the evaluation).


texts:
This is my contract code.

    contract StartCoinCrowdsale is TimedCrowdsale, MintedCrowdsale, CappedCrowdsale, FinalizableCrowdsale   { //100000000000

    uint256 public constant TOTAL_SHARE = 100;
    uint256 public constant CROWDSALE_SHARE = 80;
    uint256 public constant FOUNDATION_SHARE = 20;
    function StartCoinCrowdsale
        (
            uint256 _openingTime,
            uint256 _closingTime,
            uint256 _rate,
            address _wallet,
            uint256 _cap,
            MintableToken _token
        )
        public
        Crowdsale(_rate, _wallet, _token)
        TimedCrowdsale(_openingTime, _closingTime)
        CappedCrowdsale(_cap)
        FinalizableCrowdsale() {
    }

    function finalization() internal {
        uint256 totalSupply = token.totalSupply();
        uint256 finalSupply = TOTAL_SHARE.mul(totalSupply).div(CROWDSALE_SHARE);//100*8000/80=10000

        // emit tokens for the foundation
        MintableToken(token).mint(wallet, FOUNDATION_SHARE.mul(finalSupply).div(TOTAL_SHARE));//20*10000/100=2000
        super.finalization();
    }
}

This is my deployment code

    module.exports = function (deployer, network, accounts) {
    const openingTime = web3.eth.getBlock('latest').timestamp + 2; // two secs in the future
    const closingTime = openingTime + 120; // 3 minutes
    // const closingTime = openingTime + 86400 * 20; // 20 days
    const rate = new web3.BigNumber(1000);
    const wallet = accounts[1];
    const cap = new web3.BigNumber(8000000000000000000); //8 ether
    return deployer
        .then(() => {
            return deployer.deploy(StartCoin);
        })
        .then(() => {
            console.log(openingTime, closingTime, cap, wallet, rate, StartCoin.address);
            return deployer.deploy(
                StartCoinCrowdsale,
                openingTime,
                closingTime,
                rate,
                wallet,
                cap,
                StartCoin.address
            );
        })
        .then(() => { // giving the crowdsale ownership over the token
            return StartCoinCrowdsale.deployed().then(crowdsale => {
                crowdsale.token().then(tokenAddress => {
                    const startCoinInstance = StartCoin.at(tokenAddress);
                    startCoinInstance.transferOwnership(crowdsale.address).then(output => {})
                })
            }).catch(err => {
                console.log(err);
            })
        });
};

This is my error.

    Running migration: 2_deploy_contracts.js
  Running step...
  Deploying StartCoin...
  ... 0xf719c61552cc15ddf5f951a95a7261d3b8aa6cbb4a6109940bd54dc9b004e6a5
  StartCoin: 0xa8a6b3b9fc3db2831bafc68c4ee60b32e5e49c87
1525510753 1525510873 BigNumber { s: 1, e: 18, c: [ 80000 ] } '0x93a0fd6e1af85eab7045244e972704b498836bcb' BigNumber { s: 1, e: 3, c: [ 1000 ] } '0xa8a6b3b9fc3db2831bafc68c4ee60b32e5e49c87'
  Deploying StartCoinCrowdsale...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: StartCoinCrowdsale contract constructor expected 5 arguments, received 6
    at /usr/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:390:1
    at new Promise (<anonymous>)
    at /usr/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:374:1
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)

Any help would be appreciated.


texts: Decode transaction input INSIDE contract with solidity?

texts:
I would like to know if it is possible to read blockchain transactions from a smart contract.
How web3 has the possibility to scroll, read and decrypt the input data of the transactions, does solidity have similar possibilities?
What kind of operations does this allow me to do on the blockchain?

Only these?
Thanks!


texts: Is Metamask (and other tools like it) a threat to decentralization?

texts: The concept of cryptocurrencies were to remove trust but tools like metamask require you to trust them with your front end.


texts: What is signing method that is used in remix IDE and how is the hash value calculated from the message that is being signed?


texts: I have a public and private keys of my account and need to send it to another account. I'm really new to this and both it a year ago and now want to sell it on exchange. So I need a really simple way to transfer funds from one account to another without getting much deeper into technology


texts: Geth Stopped Syncing after Constantinople

texts:
The geth node stopped syncing after the Constantinople upgrade. Highest block I see is 7280001.

I did not think I need to upgrade geth, else my node will stop syncing if that is the reason. I can see on error logs Constantinople: <nil> which means geth is running with config which does not support Constantinople.

Geth Details:

Version: 1.8.11-stable
Git Commit: dea1ce052a10cd7d401a5c04f83f371a06fe293c
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.10
Operating System: linux
GOPATH=
GOROOT=/usr/lib/go-1.10

Error logs:

WARN [03-01|11:17:41] Synchronisation failed, dropping peer    peer=68677387327cf808 err="retrieved hash chain is invalid"
ERROR[03-01|11:17:58]
########## BAD BLOCK #########
Chain config: {ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSupport: true EIP150: 2463000 EIP155: 2675000 EIP158: 2675000 Byzantium: 4370000 Constantinople: <nil> Engine: ethash}

Number: 7280000
Hash: 0xeddb0590e1095fbe51205a51a297daef7259e229af0432214ae6cb2c1f750750

Error: invalid difficulty: have 2957101900364072, want 2958201410943272
##############################

WARN [03-01|11:17:58] Synchronisation failed, dropping peer    peer=589a0c5101eb2ea5 err="retrieved hash chain is invalid"
ERROR[03-01|11:18:15]
########## BAD BLOCK #########
Chain config: {ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSupport: true EIP150: 2463000 EIP155: 2675000 EIP158: 2675000 Byzantium: 4370000 Constantinople: <nil> Engine: ethash}


texts:
I am testing my Dapp and need host:port for testnet and mainnet.
Please can you let me know where can I find these urls?
Also, what if the url (host:port) i provide and it goes down?


texts:
Why does below control structure return 250 in both value scenarios?

function bonusCalculate(uint _value) public pure returns(uint) {

        if(_value <= 50 ether) {
          return 250;
        } else if (_value >= 100 ether) {
          return 500;
        }
     }


texts: Is there a Solidity library for generating addresses?

texts: I'm generating a few thousand addresses to test a contract, could I do that in Solidity, or do I have to use something like ethereumjs-lib ?


texts: How can I connect a local Hardhat network to Metamask?

texts:
I have started a Hardhat network with default configuration using npx hardhat node. After running this command, I see Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/ and a list of 20 seed accounts along with their private keys.
Then, in Metamask, I've gone to "Custom RPC" network configuration, and entered the following:
Network Name: Hardhat
New RPC URL: http://localhost:8545
Chain ID: 31337
But when I try to apply the changes, I see this error: Could not fetch chain ID. Is your RPC URL correct?
If I enter http://localhost:8545 in my web browser, I see this JSON: {"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}
I am able to successfully run code that connects to the local Hardhat network and passes tests. I'm able to successfully run Hardhat tasks by using commands like npx hardhat TASKNAME --network localhost. I've tried using 127.0.0.1 instead of localhost in the Metamask config. I'm using WSL2 to run Bash and the Hardhat server.


texts: Can anyone help me make sense of the balance on this Ethereum address?

texts:
I've gone over and over and over the transaction list on etherscan.io and the csv export and I can't make sense of the 0.384x Ether shown on etherscan.io, in MEW and on ethplorer.io, they all agree on the balance.

However, the transaction detail shown on etherscan.io indicates a total of 1.45 ETH in and 1.33x out plus 0.0278x ETH in fees out for a total of 1.367x out.

However tx hash 0x5add6627bc38ec7084b4c55edd61b3af712f3b598fc657c32047a70058f0e2bc for 0.1 ETH failed (out of gas) and tx hash 0x1e85f2195186fb09dff4abf79566b6efd468776061d88aa3819665c343601ae2 for 0.1 ETH also failed (unknown reasons).

So we have 1.45 transactions in - 1.367 transactions out (including fees) = 0.083 + 0.2 for two transactions that failed to go out. This yields a balance of approx ~0.283x. But this isn't the balance displayed in MEW, or etherscan.io or etherplorer.io - there we see ~0.3843x ETH and it agrees across all three sites.

However, ethplorer.io shows different figures for total in and out (Total In ~1.723x Total out ~1.339x) which does match up to the current balance shown across all three sites. But I cannot the supporting transaction details that yield the figures given by ethplorer.io. The transactions detail given on etherscan.io suggests a balance 0.10 less!

I did notice that on the "internal transactions" tab on etherscan.io there is a 0.10 transaction (tx hash 0x9aca88a62adb439fd737f43a6e8f3ddee27e124a9e4bb42f95f2a8db1198e5a4) but I don't understand what an "internal transaction" is, where this comes from, who sent it, what it's for, etc. It explains the discrepancy in the current spendable balance, but it does not appear to be something like a return of one of failed transactions because it doesn't match up with the time of either of the failed transactions. Furthermore, this still doesn't explain the discrepancy in total in and total out between etherscan.io and ethplorer.io.

I am super confused and I've already wasted over an hour trying to figure out what is going on here and why. Can anyone explain?

Is it possible that this "internal transaction" is one of the ICOs that were purchased in prior to that transaction retroactively rejected and returned the funds?

Regardless, why is this an "internal transaction" when it doesn't appear to be internal at all? What does that mean? And how do you track down who is doing this transaction and why?

Besides the internal transaction issue, why is there a discrpancy between total in and total out between etherscan.io and ethplorer.io?

Thanks a lot. So lost here. I thought I knew how to reconcile ETH transactions but apparently I don't have a clue.


texts: How an Ethereum account hold nounce, eth balance, contract code and storage?

texts:
I am looking go-ethereum code and it is a bit hard to understand, how actually an account holds its information.

Based on Ethereum White Paper,

  An Ethereum account contains four fields:

  The nonce
  The account's current ether balance
  The account's contract code, if present
  The account's storage (empty by default)

When I look at account type(/accounts/accounts.go) in go-ethereum, it only has Address and Url. I looked at Address type but there is not much information what I am looking for but I found StateDB has some more functions which are related the White Paper's explanation.

Could you explain Account and StateDB relationship or the mechanism how an account holds that information?


texts: How to backup and restore accounts in the Ethereum wallet

texts: How can I use the Ethereum wallet to restore the account, before this I have backuped that account and the client generate an UTC file, how can I use this file to restore my account?


texts: How to convert string to bytes32 in web3js?

texts:
I have a contract with a public variable that's bytes32.  If I enter the value 20160528 then it auto converts to bytes32.  Is there anyway to convert it back from the nodejs terminal?  I've been trying

web3.toAscii(testInstance.Date.call())

but it just gives me nonsense.  Here is the the test code:

contract test {
  bytes32 public Date;

  function test(bytes32 _date){
      Date=_date;
  }
}


texts: Referencing events of interfaces in libraries

texts: When writing a contract and using an interface, events that are part of the interface do not need to be declared in the contract. Can this be avoided when not writing a library and emitting events that are already defined in an interface definition?


texts:
as the source code shows below: transactions in orphaned/uncle block are deleted from local db, but there're some posts say those txs would be put back to tx pool and would be packed later. So which one is correct, did I lost some detail in the code?

// source file: github.com/ethereum/go-ethereum/core/blockchain.go:1246
func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
    // ...
    // calculate the difference between deleted and added transactions
    diff := types.TxDifference(deletedTxs, addedTxs)
    // When transactions get deleted from the database that means the
    // receipts that were created in the fork must also be deleted
    for _, tx := range diff {
        rawdb.DeleteTxLookupEntry(bc.db, tx.Hash())
    }
    // ...
}


texts: can a hacker call constructor() function after deploy if it is public?

texts:
Is below function can be called by a hacker after deploy

constructor() public
{
    test = true;
}


texts: What is the address of EthereumDIDRegistry used for and where is it in a private network?

texts:
According to EIP-1056: Ethereum Lightweight Identity, the address for the EthereumDIDRegistry is 0xdca7ef03e98e0dc2b855be647c39abe984fcf21b on Mainnet, Ropsten, Rinkeby and Kovan.
What is that address used for?
If we are running a private network, either ethereum or stellar, where is it?


texts: Listening to broadcasted transactions using geth --syncmode light

texts:
Since my attempts of using Web3.py to get pending txpool content rely on methods unsupported by Infura (and other) endpoints, I am trying to run a lightweight geth peer. I am using the following snippet:
from web3 import Web3, HTTPProvider
thing = Web3(HTTPProvider("http://127.0.0.1:42424"))

txp=thing.geth.txpool.status()

and everything works, but there are no tx's in the pool. The geth command I ran is:
geth --rpc --rpcapi eth,net,web3,txpool --rpcport 42424 --rpcaddr 127.0.0.1 --syncmode light

Also, I waited long enough and saw geth find another peer and sync the last couple of weeks quickly.
Is this just a limitation of the light node? What is a simple/lightweight way to act as some relay node without doing a full/fast sync of the entire blockchain? I would like to avoid using an API.


texts:
Hi I am trying to run this code in remix. It deploys successfully but whenever I add a Customer using the addCustomer function, it shows this message
 "transact to MyContract.addCustomer pending ...".
 Afterwards if i try to interact with any other function it just prints for example
"call to MyContract.totalRooms"
and later the browser window hangs. May I know what's the issue.

pragma solidity ^0.6.0;

contract MyContract {

    enum Statuses {Vacant,Occupied}
    uint internal counter = 0;
    event occupied (string cname, address raddr);
    uint public constant totalRooms = 5;
    struct Room{
        address roomAddress;
        Statuses roomStatus;
    }

    mapping(uint => Room) public rooms;

    function roomInfo() public {
        rooms[1] = Room(0x33c5E8069F3F5b653fEDdE8c628B1e0DE48382a1,Statuses.Vacant);
        rooms[2] = Room(0x88789bB3d6B1eF931d3DF5aB008A38F86EA3da8d,Statuses.Vacant);
        rooms[3] = Room(0xDaEf09dE138de7C27f1a43cA6c544c1a6A50BAf9,Statuses.Vacant);
        rooms[4] = Room(0xC72C577e4450E4AAF9eaf2FF3ff6b3eC597F894b,Statuses.Vacant);
        rooms[5] = Room(0xF68af2bAC4c9Db4a27186C6382eAD0c0BA04638F,Statuses.Vacant);
    }

    // Mappings
    mapping(uint => Customer) public customers;

    struct Customer {
        address _address;
        string name;
        address room;
    }

    constructor() public {

    }

    function addCustomer(address _add, string memory _name) public {
        address _room;
        while(counter<=totalRooms){
            for(uint i =0; i< totalRooms;i++){
                if(rooms[i].roomStatus==Statuses.Vacant)
                  _room = rooms[i].roomAddress;
                else
                i++;
            }
            customers[counter+1] = Customer(_add, _name,_room);
        }

        emit occupied(_name,_room);
    }

}


texts: Metamask now longer interacts with PetShop Dapp

texts:
Since November the 4th - In order for MetaMask to interact with your webpage dapps, you need to implement the windows.ethereum.enable as part of your scripts

I have run through the pet shop tutorial - https://truffleframework.com/tutorials/pet-shop - everything works as expected

but metamask is no longer working - can anyone assist as to how i would implement the code change above into the existing script for the pet shop tutorial

code change is this:

Details of the code required are on this link below -

https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8 - To integrate the new window.ethereum.enable() feature

I have 3 js file loading on startup with the webpage for the pet shop dapp - which one should that code go into ?

thanking in advance
DubIrl


texts:
I am playing around with a private blockchain, and I realize that I do not know how to get the "genesis block" info. The eth.getBlock(0) does not show the Genesis information, for example, pre-fund by "alloc".

So, how can I retrieve the information of the Genesis block?

My Genesis file looks like:

  "gasLimit": "0x30000000",
  "difficulty": "0x1",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    "e9722f81388f8f99771cad2770aba1f4b9e2d86c": {
      "balance": "1000000000000000000000000"
    }
  },

What I want to know is how can I get the "alloc" information through the web3 or JSON-RPC API.


texts: newcomer here, any suggestions about developing a new smart contract

texts: I want to develop a new smart contract as my graduation project, any suggestions about which client to use to develop a new contract?


texts: Ropsten network contract method call not executing

texts:
I have function I'd like to execute onto the ropsten blockchain. I expect my metamask account to update balances however I just get this following output back

<Function Method(uint256,bytes32) bound to (3, '0x025c9a993431412e485703ef238e0a8d6252cb29a84b7adc4dd6e25b33467394')>


texts:
I'm making a computation query to Oraclize:

import "https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol"

bytes scriptMultihash = "QmVJyXAmxdfuVgazi2PtnwXJdSiYPpkcvv6EydccQKkiZW";

Buffer.buffer memory cborArgs;
Buffer.init(cborArgs, 64);
cborArgs.startArray();
cborArgs.encodeUInt(9000);
cborArgs.endSequence();

oraclize_query("computation", [scriptMultihash, cborArgs.buf]);

The contents of my python script are simply:

print("hello world")

When I run this with bridge, everything is fine. __callback is called, and "hello world" is returned as result.

However, when I change cborArgs.encodeUInt(9000); to cborArgs.encodeUInt(9000000);, no result is returned. I get "result": ""

The behavior seems to be that if I try to encode a uint larger than 9000000, the python script doesn't run.

Is this a bug with CBOR Buffer.buffer, and/or oraclize_query?

I was able to change my spec and use a lower number, so I don't care for my own personal app at this point. Just being a good citizen and reporting a potential problem.


texts: Which exchange should I trust to provide ether price in USD?

texts:
There are many exchanges that provide APIs for getting the market price of ether in USD and other currencies. As an example of the different data sets:

  Cryptonator  1 eth = $19.27
  CoinGecko    1 eth = $19.33916452
  Ether Pricre 1 eth = $19.15060
  Etherscan.io 1 eth = $19.42

The price on each exchange is different.

From where do these exchanges get the current market price of ether? There is no centralized authority which provides these prices.

Also, which of them should I trust for real price information?

I want to create an API to get the price of ether in different currencies. How can I achieve that?


texts: intrinsic gas too low: how to increase gas in Mist?

texts:
I cannot deploy a contract using Mist because of the error intrinsic gas too low

How can I increase the value of it?


texts: Can someone get the source code if it's not "verified"?

texts: my question is: When I deploy contracts on ropsten or other networks but do not verify the source code (make it public with it), can then someone still see my source code? I know, that function calls will be public but I mean if the whole source code will still be readable in any way. Thanks for answers!


texts:
Is it a wei, kwei, mwei, gwei, ... Something else?

The API doesn't say much.


texts: remove contract on ethereum blockchain using web3

texts:
Is it possible to remove or update already deployed contract using web3 or truffle console or geth console??
if we know the contract details like address and ABI array, and we create a object of contract using web3.js

like var contractObject = web3.eth.contract(abi).at(contractAddress);

then is it possible to remove this contract from block chain using the object created.

I am curious about,Is there any way to call selfDistruct("address") using web3.js??,
I have specified contractObject  is the object of contract

can I call
 contractObject.selfDistruct("new address to transfer remaining balance")

the question here explains how to update existing contract but I need a way to remove existing contract even if the contract dose not contain seftDistruct() method.


texts: A miner chooses a particular transaction on basis of its GAS price i.e. miner generally doesn't pick a transaction with a lower gas price if he has options of other transactions with more gas price. So, can there is a chance of transaction starvation?


texts: Meaning of "fungibility" in "Zerocash (Zcash)"?

texts:
According to the following article, Zcash provide a high level of "fungibility". compared to other crypto-currencies.

Article link: https://www.investopedia.com/terms/z/zcash.asp

fungibility definition in Oxford dictionary:

(of goods contracted for without an individual specimen being specified) replaceable by another identical item; mutually interchangeable.

So, according to this definition, fungibility is NOT related to "privacy" (this is main concept Zcash provides). So, why other crypto-currencies such as Bitcoin and Ethereum does NOT have the same level of fungibility of Zcash?


texts: Why WhatToMine predictions are so wrong about etherum mining?

texts:
Being new to mining game, I set up a 5 x RX 580 Rig. WhatToMine predicts that this setup make 151 Mh/s and $15.41 per day.

Very prosmising, isn't it?

Alas, the reality is not so rosy.

When I started to mine in nanopool.org using Claymore miner, I got 90 Mh/s and the estimate of revenue was just $1.7 per day, which definitely does not worth mining at all, so I stopped after an hour or so.

If the estimate was %50 less, I could understand, because my hashrate is %50 less than what WTM predicts.

But I'm wondering why there is such discrepanc in terms of revue estimates by WhatToMine? And which estimate is closer to reality? WhatToMine or nanopool.org?


texts:
How can we manage cyclic dependency in solidity smart contracts?

for example:

contact A {
   B b = B();

}

contract B {
 A a = A()
}


texts: tokenByIndex method don't work for contract, how could I get Token Id

texts:
I use opensea.io for create nft tokens.
I want create 100 tokens and then create redeem  mechanism on my site (allow download music).
I created contract using: "?enable_supply=true" https://rinkeby.etherscan.io/address/0xee45b41d1ac24e9a620169994deb22739f64f231
But I can't get Token Id:
contract.methods.tokenByIndex(walletAddress, 0).call()

seems theres no method tokenByIndex.
I need know  TokenId for each  item, it for my redeem  mechanism.
Could I do it with this  contract or I need use custom contract?


texts:
For example, i have:

mapping(string => MyType) map;
var value = map[key];

What is equal 'value' if 'map' not contain the 'key'?

And how to determine the presence of the key in mapping?


texts: I'm trying to figure out how to interact with the current version of the  Casper contract from Solidity. The vote-function in the casper contract takes an array of bytes, which represents the RLP-encoded vote message. Is there a straightforward way of encoding messages using RLP in Solidity?


texts: How to setup a Ethereum private chain by using pyethapp?

texts:
For some reason, I want want setup an Ethereum private chain by using Pyethapp instead of Geth.

Any suggestion any idea?


texts: How to convert BN result into readable string or number in ethjs?

texts:
I'm receiving the result in BN format. How can I convert it into actual string or number? I'm using ethjs library to interact with Smart Contract.

token.totalSupply().then((totalSupply) => {
  // result <BN ...>  4500000
});


texts: Is it possible to obtain GENESIS transactions through RPC API?

texts:
When querying the genesis block via the RPC-API (of geth), no transactions are returned by eth_getBlockByNumber.

eth_getTransactionByBlockNumberAndIndex similar fails to return any information.

I have had a look at how various Ethereum explorers handle the genesis block, but they all exhibit errors and discrepancies when looking up the genesis transactions, which makes it looks like they "manually" injected the relevant data into their respective DB, and things do not perfectly "click" with the rest of the blockchain data.

So is there an API to obtain the genesis transactions, or is this something that has to be obtained from another source? (if yes, then which?)

edit: yes, the genesis JSON can be imported, but the idea here is to have an API that takes data from the blockchain, rather than from another external source which would have to be validated/obtained independently (I am thinking of clones and private chains here)


texts: Trying to understand Uniswap liquidity and their API with autoliquidity, need some help

texts:
So I'm trying to understand liquidity and the API from Uniswap. I understand the initial liquidity provided by their interface, i.e. I add 1 eth and 1 of my tokens, it means that 1 token costs 1 eth. And current holders can only sell up to 1 Eth and buy up to 1 token since there is not more in the pool. Right?
Now if I understand correctly, auto liquidity adds a fraction of the custom tokens with each transaction to the pool so that there will always be supply right? Or does it provide Ethereum on each sell? Or does it transfer both?
Now many tokens have this auto liquidity feature and use the addLiquidityETH function to add liquidity to uniswap. Does this function send Ethereum, custom tokens or both to the liquidity pool? I can't really make this up from their API since they just speak of tokens.


texts: How (without libraries) can I get the public address from a private key?

texts:
I want to know a way to know the public address used for funds transfer from the private key. (As myetherwallet do when you get your wallet info by entering your private key)

I don't care with wich programming language (even if I prefer javascript, if it's possible).


texts: How will regular users be able to use dApps without buying ether?

texts: Requiring users to get ether before they can use a dApp, is too much of a barrier for any kind of mainstream adoption.  If dApps offer free ether in a naive way, they can be attacked by Sybils where a user just creates many "accounts" to get the free ether.  What are potential solutions and which ones are closer in actual practicality?


texts:
Is it possible to stack transactions which depend from themselves?

Example:

State on start: Account A (2 ETH), Account B (0 ETH), Account C (0 ETH)

Transaction 1 - Account A sends 2 ETH to Account B.

Transaction 2 - After few seconds Account B sends 2 ETH to Account C, but the first transactions is not already in block, so Account B has 2 ETH pending and not confirmed.

Question: Will second transaction be rejected by nodes or realized?


texts: How to build an Ethereum hot wallet for an exchange

texts:
I’m developing an exchange.
When a new user register on website we will create new eth wallet for them.
When they deposit USDT on their wallet how can I transfer that USDT amount to another address (pool) and pay gas fee with another account (because new user’s eth balance is 0)?


texts: Where can i find record for transactions/transfer made using smart contracts?

texts: I might be missing something obvious here, but where can i find the records/ receipts for transactions made using transfer() method in smart contract? Without using events or something explicit for this purpose.


texts: Geth Error: Cannot access contractAddress from the transaction receipt

texts:
I am trying to instantiate contracts via the geth console.

Here are the instructions I am running:

var bytecode = "0x6003600501600202600055"
var createTx = eth.sendTransaction({ from: eth.accounts[0], data: bytecode })
var created = eth.getTransactionReceipt(createTx).contractAddress

When I run the last line, I get the following:

TypeError: Cannot access member 'contractAddress' of null
    at <anonymous>:1:15

I would appreciate any pointers on how to resolve this


texts:
How I understand MEW suppose three cases of wallet:

MEW Wallet
By Keystore File
By Mnemonic Phrase

I know the created wallet by Mnemonic Phrase is kinda HD.
What wallets are HD? And how can I determine the kind of wallet?


texts: Sent Real Ether via Rinkeby to Ledger Nano

texts:
I feel so stupid, MetaMask on MEW account has Rinkeby as my default account and I sent 3 real ether to my Ledger Nano. i see it up on etherium.io on the Network Rinkeby. How do I reverse this or get it out of the test network. I'm so new at this and don't even remember adding rinkeby to my MetaMask account let alone as my default account.
please help! thanks in advanced.


texts: Ethereumjs: How to save the blockchain / state

texts:
Ethereumjs noob here. Using the code below, I'm able to create a new blockchain and add blocks to it. But the blocks are not being saved to the database.

var blockdb = levelup("./blockdb", {createIfMissing: true});
var blockchain = new Blockchain({"blockDB": blockdb, "validate": false})

blockchain.getHead(function (err, head) {

    var myblock = blockFromRpc(blockdata);

    blockchain.putBlock(myblock, function(a,b) {
        ...
    })

})

This seems to work fine. But when I try reloading the blockchain with the same DB's as above, it's empty. How do I save the blockchain with the added blocks?


texts: Is truffle based on node and is it possible to run some kind of node debugger in order to pause the Javascript tests and examine variables?

texts: I am currently developing a Dapp and using truffle test to verify the contract. However, I find that I am also debugging the Javascript that runs the test with a lot of console.log() statements. This is time consuming and inefficient. I would like to use a debugger to examine the Javascript in order to refine my tests, and also because I'm still figuring out how to interact with web3 correctly.


texts: solidity function not being called through web3/JS

texts:
I have the following contract (Test.sol):

contract Test {

bytes32 message = "This is a message.";

function setMessage(bytes32 _message) {
    message = _message;
}

function getMessage() constant returns (bytes32) {
    return message;
}

function stringToBytes32(string memory source) returns (bytes32 result) {
    assembly {
result := mload(add(source, 32))
    }
}}

I am trying to make an app where the user enters text and clicks a button, then the setMessage() and getMessage() functions are executed, and the message is displayed.

My index.html file (straightforward):

<input type="text" id="textbox" placeholder="enter something">
Submit

and the app.js file that index.html refers to:

  window.setMessage = function () {
  let message = $('#textbox').val()

  Test.deployed().then(function (contractInstance) {
    contractInstance.setMessage(stringToBytes32(message), { gas: 140000, from: web3.eth.accounts[0] }).then(function () {
      contractInstance.getMessage().then(function (v) {
        $('#displayedMessage').html(web3.toAscii(v))
      })
    })
  })

}

There is something wrong with the above code in app.js as the setMessage() function doesn't get called at all, though I don't know why not (I'm not getting any errors in the browser or truffle console). Or maybe it's an issue with converting the string to bytes32. The contract is deployed properly - if instead of the above, I have something like the following:

window.setMessage = function () {
Test.deployed().then(function(contractInstance) {
        contractInstance.getMessage().then(function(v) {
          $('#displayedMessage').html(web3.toAscii(v));
        })
      })

Then getMessage() gets called. But I can't seem to call setMessage()


texts: Does etherscan require the use of an api key

texts:
I want to list transactions for accounts. However, I'm confused as to if etherscan requires an api key. One https://etherscan.io/apis, it says it you can create a api key to use with the api.

But if you check the following linked in the page: https://etherscan.io/apis#accounts

https://api.etherscan.io/api?module=account&action=balance&address=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae&tag=latest&apikey=YourApiKeyToken

You can clearly make the request. It even shows YourApiKeyToken as a place holder. But Removing it also allows me to view transactions. So, is an api key required?


texts: TypeError: web3.eth.sendTransaction(...).then is not a function

texts:
I was trying to transfer some ether using ganache desktop application in nodejs. It was properly working but suddenly an error occurred.

var s = 1;

try{
 web3.eth.sendTransaction({
 from: '0x627306090abaB3A6e1400e9345bC60c78a8BEf57',
 to:'0x821aea9a577a9b44299b9c15c88cf3087f3b5544',
 value: web3.toWei(s.toString(), "ether")

}).then(function(receipt) {
    console.log(receipt);
    res.json({success: true});

}).catch(function(e){
console.log('error occured');
console.log(e);
res.json({success: false });
});

If .then() and .catch() is removed, ether is transferred.


texts: When writing tests in Truffle, is it possible to force specific wallet addresses to be used?

texts:
I have Solidity code that, given the input of the sender's wallet address, deterministically produces a resulting output.

My goal is to write a unit test for this functionality.  Is there a way I can override the msg.sender value?

I'm using Truffle 4.0.4 alongside testrpc.


texts: Is There a Good Way to Compile Solidity on the Frontend?

texts:
By using web3deploy on remix, it is one click to copy, and one click function for you to allow someone on the the frontend to deploy a contract you are hosting via MetaMask.

If you wanted to make that contract variable, so the data: {bytecode} field could vary based on some variables in the Solidity code, you would need to compile it and then update the data: field of your web3.js deployment.

Is there a way to make solc work on the frontend? Is there a service that lets you compile Solidity remotely?

Update: I got Eric Tang's project to compile in the browser, but I haven't figured out how to only output the bytecode, nor what regex to turn the solidity contract code into one big string.


texts: Run bot on same server as your own Ethereum node

texts:
I have been tinkering with running a bot on a server and it uses Web3 to talk to my solidity contracts via infura.
Given the latency of a bot running in location X and the infura API being based in location Y, I was wondering if it would make sense to spin up my own ethereum node and run my bot on the same server and skip the whole infura step. Is this possible and would it provide any advantage?


texts: What do the parameters in the Ropsten genesis file mean?

texts:
Here's a snippet of Geth's Ropsten genesis:

  "config": {
      "chainId": 3,
      "homesteadBlock":0,
      "eip150Block":0,
      "eip155Block":10,
      "eip158Block":10,
      "eip160Block":10 }

It appears that chainId is the same as networkID (3), which is indeed what it's called in Parity's Ropsten genesis.  Most other values in Geth's genesis can be explained by this.  3 questions:

What do the other config values mean, and why are they needed (since homestead is quite old)?
Why do specific accounts need to be explicitly allocated a balance of zero?
Who are the key holders to this account?

  "874b54a8bd152966d63f706bae1ffeb0411921e5": { "balance":
  "1000000000000000000000000000000" }

Additional information about Parity's Ropsten genesis would also be welcome.


texts:
I apologize preemptively for the very basic question.  I have added and installed web3 using yarn in my react project.  Inside my index.js file in /scr and based on the web3 docs I have tried both (not at the same time)

var Web3 = require("web3");
var web3 = new Web3();

and

import Web3 from 'web3';
var web3 = new Web3();

before adding

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

web3.eth.getAccounts((error, accounts) => console.log(accounts[0]));

and end up with an error complaining "Cannot read property 0 of undefined" leading me to think the issue is with accounts[0].

Confusingly, when my require/import statements at the top of the page are deleted and the page is refreshed, the browser detects metamask and prints my address to the console. Additionally I get complaints that my web3 object is undefined but that is to be expected.

I have not explicitly run webpack or browserify because webpack is included in react projects. Is this something I need to do?

What is going on here and how can I get my React project to work with metamask?


texts:
I'm trying to subscribe to a smart contract event from my java app using web3j.
I deployed my contract to truffle, here it is:
pragma solidity ^0.4.24;

contract MyContract {

  string message;
  event MyEvent(address contractAddress, string message);

  constructor() public {
    message = "I'm ready!";
  }

  function setGreetings(string _message) public {
    message = _message;
  }

  function getGreetings() public view returns (string) {
    return message;
  }

  function triggetEvent() public {
    MyEvent(address(this), message);
  }

}

In my java app I'm subscribing to this event:
web3 = Web3j.build(new HttpService("http://localhost:9545/"));
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
MyContract myContract = MyContract.load(CONTRACT_ADDRESS, web3, credentials, GAS_PRICE, GAS_LIMIT);
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, myContract.getContractAddress());
String encodedEventSignature = EventEncoder.encode(MyContract.MYEVENT_EVENT);
filter.addSingleTopic(encodedEventSignature);
log.info("subscribing to event with filter");
web3.ethLogObservable(filter).subscribe(eventString -> log.info("event string={}", eventString.toString()));

Where MyContract.MYEVENT_EVENT looks like this:
public static final Event MYEVENT_EVENT = new Event("MyEvent",
            Arrays.<TypeReference<?>>asList(),
            Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Utf8String>() {}));

Now I'm calling the triggetEvent() method from truffle console, the method runs but my java app prints nothing.
What am I missing here?


texts: How can you parse blockchain files stored in a local node to get blocks and transactions details?

texts:
I want to get all details of blocks and transactions without using event logs.
For example, I want to get a list of of transaction data which are sent to a specific contract.

How can I parse local blockchain data?
Where can I find the spec of blockchain data structure?

This is not about parsing the programming code.


texts:
I've been reading a few articles and StackExchange posts (e.g. What are truffle migrations?) about Truffle Migrations, but I still don't get it: why do we need them?

It seems they do only one thing (correct me if I'm wrong): store a number in a contract so we know which (version of) the contracts we already deployed.

Thing is, deploying a contract and making transactions isn't cheap: it means spending Ether and also increasing the size of the blockchain forever. It seems like a heavy cost for just storing an integer we could store locally for example.

So I'm wondering: did I miss other features offered by Truffle migrations? Why don't we store that information locally (or somewhere else)?


texts: Why are ERC20 tokens displayed differently on Etherscan?

texts:
I've noticed that tokens are displayed slightly differently on Etherscan.

When you are on an address and click on the dropdown to see the tokens, some appear as an address, and some appear as a name:

This is how the Token "Titanium BAR" is displayed:
https://etherscan.io/token/0xc7579bb99af590ec71c316e1ac4436c535039594

And on some other tokens, you have "ERC-20 Token" instead of "Token" written on the token page:
https://etherscan.io/token/0xfa74f89a6d4a918167c51132614bbbe193ee8c22

So, do you have an idea why it is like that, and does it have something to do with the validation process on Etherscan?

Thank you!

ps: already found this hint How Can I Add My Name Next To Address On Etherscan? - not sure if it is the right path though


texts:
I created a transaction in Go, signed it with a EIP155Signer signer, but when I try to publish the transaction through the Go client to the private blockchain, I get the error Invalid sender. Any idea what's happening here?

This issue seems to have the same error: https://github.com/ethereum/web3.js/issues/566

The transaction gets signed correctly (string output below), but the From field is never populated, and I'm unable to set it in Go because it's a hidden struct field that is internally set by the EIP155Signer

tx before sign=
    TX(e694193e2f4d6dc099444ff0057456e23cafe0f8035c7c70daf688bc2bf5546a)
    Contract: false
    From:     [invalid sender: invalid sig]
    To:       b424f3bcc3da6f54f27f5f4af0c9c18d567702e6
    Nonce:    0
    GasPrice: 0x0
    GasLimit  0x0
    Value:    0x0
    Data:     0x746865626573746461746165766572
    V:        0x0
    R:        0x0
    S:        0x0
    Hex:      ec80808094b424f3bcc3da6f54f27f5f4af0c9c18d567702e6808f746865626573746461746165766572808080

signed tx=
    TX(ff6c011c7527f74e00fde94f6a4a5e523211f21f221c0b7133bf723486b3284c)
    Contract: false
    From:     [invalid sender: invalid sig]
    To:       b424f3bcc3da6f54f27f5f4af0c9c18d567702e6
    Nonce:    0
    GasPrice: 0x0
    GasLimit  0x0
    Value:    0x0
    Data:     0x746865626573746461746165766572
    V:        0x0
    R:        0x91a89e1ee55cc959572c050780301701c7f02436701db5961ccb01d556c2e708
    S:        0x699559f036a1153b2f979cd01ee9b0beb0e889c8aaab0dbd5a46dd7931842f02
    Hex:      f86c80808094b424f3bcc3da6f54f27f5f4af0c9c18d567702e6808f74686562657374646174616576657280a091a89e1ee55cc959572c050780301701c7f02436701db5961ccb01d556c2e708a0699559f036a1153b2f979cd01ee9b0beb0e889c8aaab0dbd5a46dd7931842f02

Seems that the sender can't be derived according to this source file when the transaction is printed: https://github.com/ethereum/go-ethereum/blob/8771c3061f340451d0966adcc547338a25f2231f/core/types/transaction.go#L273


texts: Using a contract multiple times with multiple people

texts:
Just a question for my understanding.

Let's say I have a contract that has two people involved (for example, a buyer and a seller). Through ethereum, is it possible to re-use this contract and use an instance of this contract for every sale, or do you need to deploy a contract for every sale?

Do you actually copy the contract every time, or can you just create a new address for each sale but use the same code?


texts: The reason for "Could not find artifacts for" in truffle?

texts:
Any ideas about the reason for the following error from truffle? The contract is from the solidity docs.

Truffle.js -

//var Set = artifacts.require("./Set");
var Consumer = artifacts.require("./Consumer");
var Infofeed = artifacts.require("./Infofeed");
//var med1 = artifacts.require("./med1");
module.exports = function(deployer) {
  //deployer.deploy(Set);
  //deployer.link(Set, d3);
  deployer.deploy(Consumer);
  deployer.deploy(Infofeed);

};

Code -

pragma solidity ^0.4.18;

contract InfoFeed {
    function info() public payable returns (uint ret) { return 42; }
}

contract Consumer {
    InfoFeed feed;
    function setFeed(address addr) public { feed = InfoFeed(addr); }
    function callFeed() public { feed.info.value(10).gas(800)(); }
}

Filename - Consumer.sol

Output -

Writing artifacts to ./build/contracts

Using network 'development'.

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x8a2f45296c97a1393b9ef1b21e63ba5616944f893b70fd84c589fcf66ec7a29e
  Migrations: 0x9a57fa3522a99d6b8d19ecca976edc2168260580
Saving successful migration to network...
  ... 0xb232b7a1a42e1abf795f60686b00b301a346464c08ffbe2c0df5d955b195070e
Saving artifacts...
Running migration: 2_deploy_contracts.js

/usr/local/lib/node_modules/truffle/build/cli.bundled.js:63957
  throw new Error("Could not find artifacts for " + import_path + " from any sources");
        ^
/usr/local/lib/node_modules/truffle/build/cli.bundled.js:63957
  throw new Error("Could not find artifacts for " + import_path + " from any sources");
  ^

Error: Could not find artifacts for ./Infofeed from any sources
    at Resolver.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:63957:9)
    at Object.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:176376:36)
    at ResolverIntercept.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:305479:32)
    at /geth/mybc/geth/zt/migrations/2_deploy_contracts.js:3:26
    at ContextifyScript.Script.runInContext (vm.js:59:29)
    at ContextifyScript.Script.runInNewContext (vm.js:65:15)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:204344:14
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)