texts:
I've been looking through EthereumJ, Trying to understand how transaction hashing and signing works.

From what I can tell from the code, the signature is created by signing the hash of the RLP encoded transaction. The reason I'm confused, however, is because the hash is generated from the r and s values of the signature along with the rest. Considering those r and s values don't exist yet, how would they be included?

A bit more digging into the code looks like two different hashes are generated. One "raw" hash, in which the r and s values are simply empty byte arrays, which is the hash that gets signed, and then one actual hash, which includes the generated r and s values.

Is this understanding correct? Why bother including the signature in the signing process? As in, why doesn't the signature simply sign the hash of the non-signature elements of the transaction? Why does the "raw" hash include the v r and s values (even though the r and s are empty)?


texts:
I'm using the command line to delete the existing chaindata so I can fast sync:

geth removedb

But I am returned with:

Database deletion aborted
Database doesn't exist, skipping

So then I run:

geth --fast

And I'm returned:

Fatal: Error starting protocol stack: leveldb/storage: corrupted or incomplete meta file

I repeat the removedb command under the assumption that whatever chaindata is there is corrupted. But then it tells me nothing is there. What am I missing?


texts:
I have setup Ubuntu on my laptop after having Windows 10 on it, and I lost my Ethereum wallet backup file. Now I have returned to Windows 10, is there any way to restore my wallet again without my backup file?

Or any way to recover my .json backup file on Windows 10?


texts: Is there a way to know the contract creation Address from a the transaction?

texts:
I know that in the transaction receipt I can get the contract address by getting a transaction receipt from a generated transaction.

But I am wondering since smart contract addresses are deterministic in some sense if there is a way to predict the address from the transaction its self, not the receipt.


texts: sendTransaction to send tokens with Metamask and custom data

texts:
My question is similar to How to use sendTransaction to send ERC20 tokens through Metamask?. I have a contract, and currently I send a transaction to this contract through Metamask with this code:
var abiInterface = new ethers.utils.Interface(this.abi);
var functionData = abiInterface.encodeFunctionData('myFunction', [type, level]);
const transactionParameters = {
  nonce: '0x00', // ignored by MetaMask
  gasPrice: ethers.utils.hexlify(ethers.utils.parseEther(GlobalConstants.gasPrice)), // customizable by user during MetaMask confirmation.
  gas: GlobalConstants.gas, // customizable by user during MetaMask confirmation.
  to: this.contractAddress, // Required except during contract publications.
  from: ethereum.selectedAddress, // must match user's active address.
  value: ethers.utils.hexlify(ethers.utils.parseEther(price.toString())), // Only required to send ether to the recipient from the initiating external account.
  data: functionData, // Optional, but used for defining smart contract creation and interaction.
  chainId: GlobalConstants.chain, // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
}
const txHash = await ethereum.request({
    method: 'eth_sendTransaction',
    params: [transactionParameters],
  });

Now I want to send the transaction from a custom token, and according the response from Hamza Ahmed in question link above, to do it I need to remove the parameter 'value' and send some like this
contractInstance.transfer.getData(address, amount);

in the 'data' parameter.
The problem is I need to send this
abiInterface.encodeFunctionData('myPayableFunction', [type, level]);

in the data parameter, to interact with a function in my contract.
So the question is, how can I send tokens together with the custom data to interact with the contract function?


texts: web3.js: How to get password from private key?

texts:
I want to make transaction using web3.js but I am not understanding from where I get password to unlock account .

web3.eth.personal.unlockAccount('account address ', " password", duration);


texts: how to write a Withdraw function from my contract contract

texts:
So I am new to solidity and I want to add a withdraw function to the attached smart contract so that when i call the withdraw function it will give me Eth / token in the contract.
Link to smart contract code


texts:
I am new to ethereum and curious about interacting with dApps while keeping a private key in cold storage.
I like the idea of keeping the private key for an Ethereum wallet on an air-gapped computer. I have done this with bitcoin using a program called electrum. Electrum enables a workflow where you 1) generate transactions on an online computer, 2) transfer them to an air-gapped computer for signing, and 3) transfer the signed transaction back to an online computer for broadcasting. I know that there are similiar programs that can achieve this for Ethereum, such as MyCrypto.
Most of the Ethereum dApps I have come across (Compound, Uniswap, MakerDAO vaults) offer several options to connect to a wallet. The options are usually browser based wallet extensions (like metamask) mobile apps (like coinbase wallet) or hardware wallets (like trezor or ledger.)
Are there any solutions that enable using dApps with arbitrary cold wallets? For instance, some kind of browser extension that will generate the transactions to sign, and allow you to process them manually? That is, I envision that after being presented with the transction, the user would transfer them manually to an air gapped computer, sign the transaction, and then transfer back to this extension/app for broadcasting onto the Ethereum network.
If this is nonsensical then please don't hesitate to let me know :)


texts: Hey I want to transfer the blockchain to a new computer, however my usb only has 32GB. Could I use gzip on the chaindata folder, or will this corrupt it?


texts: How can the functionality of multisignature transactions of Bitcoin be remodeled in Ethereum?

texts: So in Bitcoin we have multisignature transaction. Does Ethereum also have the same? or it has some other type of process for doing the similar tasks that can be done by Bitcoin's Multisignature Transaction.


texts: Mist Wallet: How to increase desired fee?

texts:
I put in an ether transaction through that had a pretty low fee limit.  I didn't quite understand the alert that the program showed during the confirm step of the payment, but there could have been something there.

Anyways, the transaction is pending for 1 day now with 0 confirmations.  I can see it on etherscan.  I have been doing some reading.  I would like to try to increase the fee that I want to pay to see if that will help getting my transaction through the bottleneck ( #ucking cats! ).

How can I do this?  I have just read a nice how-to about how to do this using the geth app interface.  Does anyone have experience with this technique?  Does it work?  Is there an easier way through the Mist Wallet interface?

Thanks so much.

Mist Wallet v 0.9.3


texts: Assuming EIP140, is remaining gas refunded when a called contract throws?

texts:
Under EIP140 (REVERT) and assuming Solidity ≥0.4.10. If I call from my contract to a function on an external contract, and this external function does an invalid jump, does my contract still call REVERT? If so, do I:

pay only for total consumed gas
pay for locally consumed gas, plus all gas Solidity sends to the external contract

I'm asking because I have a new contract that will call token contracts, some of which are compiled with older Solidity. But the way Solidity bubbles exceptions makes me believe that I would still benefit from REVERT and the lower gas cost. Is this correct?


texts:
I was reading through Vitalik's blockchain interoperability paper available here

One thing he mentions is a company / project called EthereumLottery.io (currently not operating) which managed to achieve one way blockchain interoperability by reading Bitcoin's block height.

This sounds extremely exciting so I decided to give it a go and understand how its smart contract works. The smart contract is available here and I recommend reading it.

I read it and from my understanding, the blockchain interoperability part happens with those lines of code:

contract BTCRelay {
function getLastBlockHeight() returns (int);
function getBlockchainHead() returns (int);
function getFeeAmount(int blockHash) returns (int);
function getBlockHeader(int blockHash) returns (bytes32[3]);
}

I tried to go through it in full, however I do not understand at which point the smart contract manages to get the last Bitcoin block height. Is it a function called manually / centralized which uses a server/API to get the last block?

If so, does that mean that the contract owner could, at anytime pass anything else than the last bitcoin height?


texts: I got this error during truffle testing. AssertionError: it returns true: expected { Object (tx, receipt, ...) } to equal true

texts:
DappToken.sol

   function transfer(address _to, uint256 _value) public  returns (bool success){

    require(balanceOf[msg.sender] >= _value);

    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;

    emit Transfer(msg.sender, _to, _value);
    return (true);

DappToken.js file

it('transfer token ownership', function() {
    return DappToken.deployed().then(function(instance) {
        tokenInstance = instance;

    something larger than the sender's balance
    return tokenInstance.transfer.call(accounts[1], 999999);
    }).then(assert.fail).catch(function(error) {
        assert(error.message.indexOf('revert') >= 0, 'error message must contain revert');

        return tokenInstance.transfer(accounts[1], 2500, { from: accounts[0] });
    }).then(function(success) {
        assert.equal(success, true, 'it returns true');

    return tokenInstance.transfer(accounts[1], 2500, {from: accounts[0] });
    }).then(function(receipt) {

        assert.equal(receipt.logs.length, 1, 'triggers one event');
        assert.equal(receipt.logs[0].event, 'Transfer', 'should be the "Transfer" event');
        assert.equal(receipt.logs[0].args._from, accounts[0], 'logs the account the tokens are transferred from');
        assert.equal(receipt.logs[0].args._to, accounts[1], 'logs the account the tokens are transferred to');
        assert.equal(receipt.logs[0].args._value, 2500, 'logs the transfer amount');

    return tokenInstance.balanceOf(accounts[1]);
    }).then(function(balance) {
        assert.equal(balance.toNumber(), 2500, 'adds the amount to the receiving account');
    return tokenInstance.balanceOf(accounts[0]);
    }).then(function(balance) {
        assert.equal(balance.toNumber(), 7500, 'deducts the amount from the sending account');
    });


texts: Convert bytes32 to ordered bytes2, bytes4, etc

texts:
For example,
I need to slice my bytes32 variable to chunks, and put result into 5 variables, saving the order, bytes2, bytes2, bytes2, bytes2, bytes8, bytes1 (aka byte), the order should be saved and I don't really care about the rest of bytes.

Is solidity has some tools for that? Or it is only possible with bit operations.

I found some difficulties working with this low-level types.

UPDATE:
So I did prepare this function which parses numBytes bytes from source starting from start byte.

function bytesChunck(bytes32 source, uint start, uint numBytes) constant returns(uint _result){
            uint counter = 0;
            uint result;

            for(uint i = 0; i < numBytes; i++) {
                result += uint8(source[start + i]);
            }
            return result;
            //
    }

then I just convert result to needed bytes, like bytes8(result). But it seems to be overflowed, since if I have like 8 bytes it first bytes always zeros. Any ideas? :)

Thank you.


texts: How to create transactions and delay its broadcast to other nodes

texts:
I am creating a project where i need to use my smart contract to add data to the storage but in a programatically delayed way:

I am using web3 in my nodejs server, and i want to create the transaction as usually, using web3 but delay or halt the transaction broadcast until I want to send it.

My idea is to get the raw transaction and save it in an off-chain database as the string it is. then when I want to broadcast the transaction I can get it from the database and use web3 to send it as a raw transaction.

So first i want to know if my idea is achievable, and is there anyway i can save transactions inside my node instead and then send them programatically because the idea of saving transactions in relational databases is not really appealing and seems unsecure.


texts:
Let's say that Ethereum solidity returns a number from one of its functions and I get that into Javascript.
Now ,because I write tests in my js application, I have to check if the returned value is equal to some number multiplied by some number.
Basically, let's look at the scenario.
In javascript,
Way 1)
web3.utils.toBN('100000000000000') * 30
Way 2)
web3.utils.toBN('100000000000000') * web3.utils.toBN('30')
Depending on the above 2 ones, can I use Way 1 ) ? reason is that if I use Way 2, my code just becomes bloated with toBN functions all the way.


texts: truffle won't run tests while initializing a global contract instance

texts:
I am testing my smart contract in truffle. I need to declare some global variables hence I did so outside 'it'.

I also tried declaring a global contract instance that I can use in all test cases.
Though when I do so, none of the test cases are executed.

Consider this test script:

const MFT= artifacts.require('MFT');

contract("MFT", async (accounts) => {

let instance = await MFT.deployed();
let owner = accounts[0];

it("should be deployed by owner", async () => {

    let _onwer = await instance.getOwner.call();
    assert.equal(_onwer , owner);
});

});

The output that I get is:

> Compiled successfully using:
   - solc: 0.5.0+commit.1d4f565a.Emscripten.clang

  0 passing (1ms)

But when i do not initialize my instance outside the test case and do that within the test case, it works!

Consider the following test script:

const MFT= artifacts.require('MFT');

contract("MFT", async (accounts) => {

let instance;
let owner = accounts[0];

it("should be deployed by owner", async () => {
    instance = = await MFT.deployed();
    let _onwer = await instance.getOwner.call();
    assert.equal(_onwer , owner);
});

});

When I run this, i get the following output:

> Compiled successfully using:
   - solc: 0.5.0+commit.1d4f565a.Emscripten.clang

  Contract: MFT
    √ should be deployed by owner (43ms)

  1 passing (87ms)

What am i missing?


texts: Transaction Ordering doubt for msg.sender.balance

texts:
I searched for SE and google, but did not find answer to this simple doubt.

If I include two transactions (state changing ones which cost gas) in same block for execution.

Then my question is: will the value of msg.sender.balance  (user's ETH balance) change in both transaction calls, or it will remain the same?

Thanks in advance.


texts: Address casting into contract implicit conversion

texts:
What happens when an address(or an uint) is cast into a contract?

The documentation says that implicit conversions are done when no information is lost so you can convert from an uint128 to an uint 256 and not the other way around. From what I can tell the address type is just an uint160 with some extra functionality so the compiler doesn`t compile the following assignments:

uint160 a;
uint256 b;
address addr;

a = b;
addr = b;

On the other hand casting an uint256 into a contract compiles just fine even though that would mean an implicit conversion from uint256 to uint160:

contract Foo {

}
contract Bar{
Foo public foo;
uint256 addr;
foo = Foo(addr);

}

I set addr to uint256(-2) to wrap it around and checked the value of foo in remix and it seems to work the way explicit conversions are described to work in the docs, i.e. higher-order bits are cut off.

How come this is allowed? I couldn`t find anything relating to contract casting in the solidity docs, i.e. found nothing on the type that is expected by the cast contract.


texts: Public-of-chain using proof-of-authority, where authority is defined as the amount of work on your public key

texts: I'm wondering if there would be benefits to create a public blockchain based on the same algorithms used for private, proof-of-authority blockchain, except replacing the concept of authority by the amount of work you did on your public key. That way, you could have the same efficiency of voting-based private blockchains, but in a public one.


texts: Is it possible to pass arrays to events?

texts:
I've seen no documentation on whether this is possible or not, and when I tried the following code, I get a revert error:

pragma solidity ^0.4.0;

contract Hello {

    event TestEvent(uint256[] array);

    function hello() public {
        uint256[] memory output;
        for (uint i = 0; i < 5; i++) {
            output[i] = i;
        }
        TestEvent(output);
    }

}

The compiler raises no warnings about this code, so I'm unsure if it's some other issue or because I'm trying to pass an array to an event.


texts: Including transactions fees when sending out ETH from a smart contract

texts:
Let's say I have a simple Solidity wallet contract as shown below. When I want to withdraw from the contract using send the transaction fees (gas cost) are reduced from the amount the receiving party gets. How can I send ether from the smart contract so that gas cost is imposed on the contract itself, not on the receiver?

Also, I want to know the fee imposed on the wallet before calling the contract. Is it possible to determine the fee that is imposed for send() over JSON-RPC interface?

/**
 * Simple hosted wallet contract.
 */
contract Wallet {

    event Deposit(address from, uint value);
    event Withdraw(address to, uint value);

    address owner;

    function Wallet() {
        owner = msg.sender;
    }

    /**
     * Simple withdrawal operation.
     */
    function withdraw(address _to, uint _value) {
        if(msg.sender != owner) {
            throw;
        }

        Withdraw(_to, _value);

        _to.send(_value);
    }

    /**
     * Somebody sends ETH to this contract address
     */
    function() {
        // just being sent some cash?
        if (msg.value > 0) {
            Deposit(msg.sender, msg.value);
        }
    }

}


texts: what is more gas efficient? Looping through an array or storing the index?

texts:
I have an array that stores withdrawal information of users (funds are held in a wallet not the smart contract and users can request withdrawals).
In the end the withdrawals are paid out with a for loop.

If a user wants to cancel a withdrawal, what is more gas efficient?
storing the index of the array in a mapping or looping through the array?

I guess up until a certain length looping is more efficient but I'm not exactly sure.


texts: java.lang.RuntimeException: Error processing transaction request: insufficient funds for gas * price + value when deploying smart contracts

texts:
I am trying to deploy smart contract using web3j.
My code is as follows:

 @RequestMapping("/")
    public String index() throws Exception {
        Web3j web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/v3/2a42af3ce74e407cae9e20a7e7001ddb"));
        String walletId = "97a0987c270cd6cfa77972b83026eb56524857c5";
        String walletSource = "resources/testnet-keystore/UTC--2018-09-26T00-58-36.238000000Z--" + walletId + ".json";
        System.out.println(walletSource);
        Credentials credentials = WalletUtils.loadCredentials("admin1234", walletSource);
        System.out.println(credentials);
        ProofOfExistence contract = ProofOfExistence.deploy(web3j, credentials, ProofOfExistence.GAS_PRICE,ProofOfExistence.GAS_LIMIT).send();;
           String contractAddress = contract.getContractAddress();
           return "Contract is deployed at address: " + contractAddress;
    }

I have started my geth console.When i try running the contract. I get funds insufficient error.I am using spring boot to run my applications.
Any help would be appreciated!!


texts:
I know that there is no contract instance copy implementation (yet) in solidity but what would be the best way to backup a contract?

Suppose the following scenario:

contract is deployed to the block chain
contract has a number of attributes that each have a getter() method
callable by the owner (an address)
contract is populated with new data
the contract needs a new functionality (implemented through a new set
of methods)
a new contract is developed and deployed to the network but it needs the data from the previous contract

How can the new contract retrieve the state of the previous contract?

The trivial approach would be to use getters for all attributes in the original contract and setters in the new contract and simply copy the attributes from one contract to another.


texts: Empty string value returned when returns variable is not named in declaration

texts:
I'm trying to implement a simple "pop" function in solidity, and I am getting very different behaviour with string values depending on whether or not I name the returns value in the function declaration.

contract PopArray {
    string[] public string_arr;

    function PopArray() {
        // fill the array with some data
        string_arr = ['zero', 'one', 'two', 'three', 'four'];
    }

    // Calling this once returns 'four', calling it a second time returns 'three', etc.
    function pop_string () returns (string member) {
        member = string_arr[string_arr.length-1]; //get the last value
        string_arr.length = string_arr.length-1;  // reduce the length of the array
        return member;
    }

    // Calling this returns nothing, but does reduce the length of the array.
    function broken_pop_string () returns (string) {
        string member = string_arr[string_arr.length-1];
        string_arr.length = string_arr.length-1;
        return member;
    }
}

Here is how the results look in remix when I call one function, then the other :

Conversely, with other types I've checked, a value is returned regardless of whether the return value is named in the function declaration. Here is some code trying this out with uint and bytes32 values.

Is there a subtlety regarding strings that I'm missing here?


texts:
I have geth running on localhost:

geth.exe --testnet --fast --cache 1024 --ipcpath \\.\pipe\geth.ipc --rpccorsdomain * --rpcport 8545 --rpc

If I do the following:

var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var abi = ...
web3.eth.Contract(abi,"0x5cb023C894D7838Ee7C0eE43AFD8D10D75Cd89bd");

This gives me an error: TypeError: Cannot redefine property: currentProvider on the last line, error happens inside web3-core\src\index.js:42:16

Second syntax, which one can find on the net:

web3.eth.contract(abi)

gives another error: TypeError: web3.eth.contract is not a function

What is the right syntax to execute contract from nodejs with geth?


texts: I am not able to assign value to a string storage and retrieve the set value

texts:
below is the test.sol file
pragma solidity ^0.5.0;
contract test {

    string initialstring = "Hello World!";

    function getstring() public view returns(string memory){

        return initialstring;

    }

    function setstring(string memory newstring) public  returns(bool success) {
        initialstring = newstring;
        return true;
    }

}

This is the test case written in truffle js
const Test = artifacts.require("test.sol");

contract('Test',(account) => {
    it('Reading Default value', async() => {

        let TestContract = await Test.deployed();
        let orgstring = await TestContract.getstring.call();
        assert.equal("Hello World!", orgstring, "Initial Say Matches");
    });
    it('Inserting new value', async() => {
        let TestContract = await Test.deployed();
        let setstatus = await TestContract.setstring.call("Hi World");
        assert.equal(true,setstatus, "New Value inserted");
        let Newphrase = await TestContract.getstring.call();
        assert.equal("Hi World",Newphrase, "Updated value received");
    });

});

The second test case fails and I am not able to comprehend why it is failing.


texts: Where does the length parameter end and the actual string start in an abi encoded string?


texts: Are there any blockchain/transaction APIs for the Ethereum network?

texts:
In the Bitcoin world there are a number of APIs such as:

blockchain.info blockr.io blockcypher.com etc.

which allow a web application to access block and transaction data from the blockchain, as well as send transactions.  Are there similar services available for the Ethereum network?


texts: What is the difference between Ethereum and Eris?

texts: When I first searched for Turing complete blockchains towards the end of 2015 Google returned both Eris and Ethereum at the top. My initial impression was that they are quite distinct. More recently though I read that Eris is a spinoff. What exactly is their relationship, if any, and how do they compare?


texts:
I have a smart Contract which generates a random number within a range and then check if the number is equal to the user's input.
For the same input sometimes it works and sometimes it gives me exception(Error: VM Exception while processing transaction: out of gas).
Though I am using same gas price and gas limit for all the transactions.

contract GuessNumber {

  uint public range;
  uint public totalNoOfGuesses;

  //structure to store the Guess
  struct Guess {
    uint lastGuess;
    uint lastCorrectGuess;
    uint correctGuessCount;
    uint wrongGuessCount;
    uint lastGuessAt;
  }

  mapping(address => Guess) public guesses;

  event Guessed (
    address indexed _from,
    uint _randomNumber,
    uint _guess
  );

  //Initiazed the range between which a number should be guessed.
  function GuessNumber(uint _range) public {
    range = _range;
  }

  //function to store the guess in the mapping when a guess is made.
  function guessIt(uint _guess) public returns (bool) {
  //Need to check if the guess number is less than or equal tp range
  require(_guess <= range);
  uint random = generateRandomNumber(range);
  // uint random = 10;
  if (random == _guess) {
    Guess storage correctGuess = guesses[msg.sender];

    correctGuess.lastGuess = _guess;
    correctGuess.lastCorrectGuess = _guess;
    correctGuess.correctGuessCount = correctGuess.correctGuessCount + 1;
    correctGuess.lastGuessAt = now;
    totalNoOfGuesses = totalNoOfGuesses + 1;

    Guessed(msg.sender,random, _guess);

    return true;

  } else {
    Guess storage wrongGuess = guesses[msg.sender];

    wrongGuess.lastGuess = _guess;
    wrongGuess.wrongGuessCount = wrongGuess.wrongGuessCount + 1;
    wrongGuess.lastGuessAt = now;
    totalNoOfGuesses = totalNoOfGuesses + 1;

    Guessed(msg.sender,random, _guess);
  }
  return false;
  }

  function generateRandomNumber(uint _range) public returns (uint) {
    return uint(sha3(block.timestamp)) % _range;
  }

}


texts: Geth send full account balance and automatically calculate gas price and costs

texts:
I'm struggling with transferring 1 ETH to an address using Geth console. I used all sorts of codes and examples I found online, but it all returns "insufficient funds for transfer" or some other errors.
I have 1 ETH and some in this wallet. Is there a function of some sort where it can calculate required gas price, pay the bare minimum and transfer ALL my funds as much as possible (after deducting the gas price)?
Example function I used that didn't work:
var transferAll = function(from, to) {
  var gas = '30000';
  var gasPrice = eth.gasPrice;
  var gasTotal = gasPrice.mul(gas);
  var totalValue = eth.getBalance(from).sub(gasTotal)-1;
  console.log("Transfer :"+totalValue+", from "+from+" to "+to);
  personal.unlockAccount(from);
  var result = eth.sendTransaction({from: from, to: to, value: totalValue});
  console.log("Transaction hash:", result);
};

I'm getting 2 errors

"gas required exceeds allowance (0)"
" insufficient funds for transfer"

no matter what I do I can't satisfy the requirements and initiate a transaction


texts: How to download the blockchain of a single ethereum contract’s address?

texts:
The blockchain required to run ethereum is several Terabytes large. This means more than 9 years would be required to download it with my connection speed.

In my case, I just want to know if the storage of a single contract’s address contains a specific value and in which transaction such value was created.

So how to download all key/values pairs of a single contract address ?


texts: What are the implications of a race condition with the following code?

texts:
In a popular sale contract, what would happen if the following code was true?

totalNumberOfTokensDistributed = 0;
totalNumberOfTokensAvailable = 100;

function claimTokens() {
    uint tempTotalCollected = totalNumberOfTokensDistributed + 2;
    require(tempTotalCollected <= totalNumberOfTokensAvailable);

    totalNumberOfTokensDistributed = tempBeingCollected
    // Address that calls function gets 2 tokens
}

The function allows the creator the check if the function call will not be over than the total number available. If two or more users were to call this function in the same block, how would totalNumberOfTokensDistributed = tempBeingCollected behave? If 4 users called this function in one block, would totalNumberOfTokensDistributed be 8? Or would it be overwritten by every use and only end at 2?

I know a solution is totalNumberOfTokensDistributed += 2;, but I am curious about race conditions in Solidity.


texts: Problems syncing small private net consisting of 2 PC miner nodes and 3 Raspberry Pi nodes

texts:
I've read countless posts referencing some form of "Synchronisation failed, dropping peer err='retrieved hash chain is invalid'" and of the few that had solutions, none of them worked for me.

I started using this tutorial, from which I used Geth to create a private PoW network with two local miner nodes on my PC (Windows 10). Initially things went swimmingly; I got the two miner nodes synced and mining properly, and was able to add a RPi into the mix and eventually deploy a smart contract using truffle that the RPi would then monitor through Python. Recently I got 2 more RPi's, but upon following the same steps as for the first RPi I was not able to sync them with my blockchain.

My chain is fewer than 50 blocks, yet I have been unable to get this up and running as I originally did no matter what I try. I've tried fast and full sync, I've added peers using a static-nodes.json file and the admin.addPeer() method, I've updated geth on each node/machine to 1.8.27-stable. All nodes are connected to a network switch and I can ping/ssh into any of them with no problems. I've deleted the geth folder/reset my database countless times and used several simple genesis.json files to no avail. I've gone back to trying to successfully sync a single RPi node, but even that seems to be hit or miss. Any ideas? Otherwise I might just try Parity instead.

I'll leave some of the commands/files I'm using for reference.

{
"config": {
"chainId": 2424,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"nonce": "0x0000000000000042",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"difficulty": "0x200",
"alloc": {},
"coinbase": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0xffffffff",
"alloc": {
}
}

geth --identity "miner1" --syncmode "fast" --networkid 2424 --datadir "~/Documents/Spencer/PrivateChain/miner1" --nodiscover --mine --rpc --rpcport "8042" --rpcapi "admin,db,eth,net,web3,miner,personal" --port "30303" --unlock 0 --password ~/Documents/Spencer/PrivateChain/miner1/password.sec --ipcpath "~/AppData/Roaming/Ethereum"

--

geth --identity "miner2" --syncmode "fast" --networkid 2424 --datadir "~/Documents/Spencer/PrivateChain/miner2" --nodiscover --mine --rpc --rpcport "8043" --rpcapi "admin,db,eth,net,web3,miner" --port "30304" --unlock 0 --password ~/Documents/Spencer/PrivateChain/miner2/password.sec

Maybe it would be worth trying to run the miner nodes in a Linux environment using Docker? I know Windows can be wonky sometimes...


texts: Solidity 0.6.1 Receive Fallback Forwarder reverts due to insufficient gas

texts:
I am playing around with Solidity 0.6.1 and trying to build a simple funds forwarder. So ETH is sent to the contract and it sends the funds to another address.

I deployed it to Ropsten. But every time I send ETH to the contract address the transaction fails due to

Warning! Error encountered during contract execution [Out of gas]

Here is my contract

pragma solidity ^0.6.1;

contract testFallback  {
    address payable public addr = 0x...;
    receive() external payable {
        if (msg.value > 0) {
            if (!addr.send(address(this).balance)) revert();
        }
    }
}

and an example of a failed transaction.

I have tried using the

fallback() external payable

function as well. I have been reading up on it here but I am unsure. why my contract cannot accept and then forward the ETH i=I send it. Thanks for your help.


texts:
I am running private block chain using geth, Here is my geth command :

geth
 --datadir $ethereum_home/chaindata
 --networkid 45683
 --verbosity 3
 --rpc
 --port 30304
 --rpcport 8545
 --rpcaddr "0.0.0.0"
 --rpcapi "web3,eth,personal,net"
 --rpccorsdomain https://remix.ethereum.org
 --nodiscover
 --gcmode archive
 --allow-insecure-unlock console 2

I am trying to run following contract in remix ide, I have compiled the contract using compiler version 0.4.24 and I am able to deploy my contract successfully on my blockchain.

But when I am trying to call methods like addEmployee, updateEmployeeOrder etc. then I am getting this error:
Returned error: gas required exceeds allowance (8000000) or always failing transaction I tried to optimize my contract but still I am getting this error

pragma solidity >=0.4.17 <0.7.0;
contract EmployeeOrder{

    struct Employee{
        string employeeName;
        uint128 order;
    }

    uint128 departmentId;
    uint128 goal;
    uint32 startDate;
    uint32 endDate;
    mapping (uint128 => Employee) public employees;
    uint128[] public departmentEmployees;
    address public owner;
    uint128 minimumOrder;
    uint128 public totalOrder;

    //This will call when we deploy contract for the first time
    constructor(uint128 _departmentId, uint128 _expectedOrder, uint32 _startDate, uint32 _endDate) public {
        owner = msg.sender;
        minimumOrder = 1;
        totalOrder = 0;
        departmentId = _departmentId;
        goal = _expectedOrder;
        startDate = _startDate;
        endDate = _endDate;
    }

    //This will tackle order history of all the employees
    event logEmployeeData(uint256 _employeeId, string _name, uint _order, uint256 _time);

    //It will restrict access of the contract to owner only
    modifier restricted() {
        require(msg.sender == owner);
        _;
    }

    //It will not allow to update data after endDate of department
    modifier beforeEndDate() {
        require(now < endDate);
        _;
    }

    //This will add new employees data on the block chain
    function addEmployee(uint128 _employeeId, string memory _name, uint128 _order) public {
        require(_order >= minimumOrder);
        Employee storage employee = employees[_employeeId];
        employee.employeeName = _name;
        employee.order = _order;
        totalOrder = totalOrder + _order;
        departmentEmployees[_employeeId] = _employeeId;
        emit logEmployeeData(_employeeId, _name, _order, now);
    }

    //This will update order of existing employees on the block chain
    function updateEmployeeOrder(uint128 _employeeId,  uint128 _order) public {
        require(_order >= minimumOrder);
        employees[_employeeId].order = employees[_employeeId].order + _order;
        totalOrder = totalOrder + _order;
        emit logEmployeeData(_employeeId, employees[_employeeId].employeeName, _order, now);
    }

    //This will change end date with new date
    function extendEndDate(uint32 _newEndDate) public {
        endDate = _newEndDate;
    }

    //This will return all the employee ids
    function getAllEmployees() public view returns (uint128[] memory) {
        return departmentEmployees;
    }

    //This will return true if goal achieved
    function isGoalAchieved() public view returns (bool) {
        if(totalOrder>= goal) return true;
        else return false;
    }
}


texts: Code Exception (VM error: revert): The constructor should be payable if you send value

texts:
I am creating a contract where to store a sort of ADN for a game, here is the code:

pragma solidity ^0.4.22;

contract Player{
    struct ADN{
        string[] html; //direccion donde estará la imagen
        uint maxQTY;
        uint created;
    }

ADN[] public bodies;

address public owner;

function addBody(string _html, string _html1, string _html2, string _html3, uint _maxQTY) public{
    require(msg.sender == owner);
    string [] memory images = new string[](4);
    images[0] = _html;
    images[1] = _html1;
    images[2] = _html2;
    images[3] = _html3;
    bodies.push(ADN({
        html: images,
        maxQTY: _maxQTY,
        created: 0
    }));

}

function showHTML(uint id) public view returns (string){
    return bodies[id].html[0];
}

}

I am trying to run it but it says the constructor must be payable, why do I need a payable constructor if I am not paying anything?

This contract it´s supouse to be called from another one when need the ADN for a player. At the momment I am just calling addBody to have a body stored as an option from the game...


texts:
Im getting the following error when trying to run my js test file using truffle:

Error: VM Exception while executing eth_call: invalid opcode

The js test file is the following:

var DebitService = artifacts.require("./DebitService.sol");

contract('DebitService', function (accounts) {
    it("Should execute newDebitObject method from Debit Service.", function () {
        return DebitService.deployed().then(function (instance) {
            return instance.newDebitObject.call("0x4d9139268c5a22aa17aa04219ffee71d110b2ec8", 1, "TestTokenFromDebitService", 10);
        }).then(function (success) {
            assert.equal(success.valueOf(), true, "Error executing newDebitObject method from Debit Service. Error: ");
        });
    });
});

And the contract function being called abd the modifier are the following:

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

function newDebitObject(address _contentCreator, uint _amountInWei, string _name, uint _debitFrequency) onlyOwner returns (bool success)
{
        if (debitObjectID[_contentCreator] != 0) return false;
        return true;
}

When I remove the only owner clause from the function, it seems to run the test correctly. However it gives the mentioned error when I try to use the onlyOwner clause on the function.
Am I doing something wrong ? Can someone help me with this issue ?

Thanks.


texts: How to get return value of function for solidity contract

texts:
I want to get the return value of a function for solidity contract. I deployed is using solidity browser in testnet. I am using nodejs client and it uses geth for web3 provider.Here are the details

contract ( from solidity example)

contract ShapeCalculator{
    function rectangle(uint w, uint h) returns (uint s, uint p) {
        s = w * h;
        p = 2 * (w + h);
    }
}

client code ::

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.defaultAccount=web3.eth.accounts[0];
var abi = '[{"constant":false,"inputs":[{"name":"w","type":"uint256"},{"name":"h","type":"uint256"}],"name":"rectangle","outputs":[{"name":"s","type":"uint256"},{"name":"p","type":"uint256"}],"payable":false,"type":"function"}]';
var address = "address which I received after deployment";
var shapeCalculatorContract = web3.eth.contract( JSON.parse(abi)).at(address);
var holdReturnValue = shapeCalculatorContract.rectangle(10,20);
console.log(holdReturnValue);

At console I am getting "0x83ddb750b799c62f73013c34f89295e3ff2af5cc98755a51e41e00a13c389735", I was expecting the area and perimeter. Appreciate any help.


texts: sent my eth to unknown eth FREEWALLET address

texts:
How can i recover my eth it was sent to an eth address with a one transaction from FREEWALLET. I am using the trust wallet while sending and im very sure that what i copay and paste is the same transaction from the previous one.

0x1b38d30857a869263545e62ce5d0333c79ac02ff330a3665bc66c93203d6c1c7 tx hash

thank you!


texts:
Is it possible to transfer ETH(not erc20) by approve+transferfrom?

Im so confused about it. Does ETH support itself all erc20 standard functions?


texts: How can I convert existing ethereum token to new coin

texts:
How can I convert a Token e.g. TOT(built on ethereum) to Coin TOT e.g. with same name and same value in another public blockchain?

Or is there any way to convert token value to new coin using new blockchain network?


texts: Does Ethereum 2.0 still have a gas cost?

texts:
I read various articles about this. Some said there is no gas cost, some said there was, some said the whole question was in transition until 2021.
Has anyone the official statement about gas costs and Ethereum 2.0?


texts: What algorithm is used to generate nonce hash in genesis file?

texts:
When looking for information about the nonce property of the genesis file, everything says that it is a 64-bit string hash etc.

But which algorithm is used to generate this hash ?


texts: Getting Uncaught Error: new BigNumber() not a number: [object Object]

texts:
I am quite new to this. Please help me out.
I am trying to build a dapp using meteor. I am having a little trouble with calling a function of the contract using web3.
Here's the code snippet that's trying to call the function of the contract:

myContract.startAFunc.sendTransaction(
  "Name",{from: fromaddress, value: 500000000000000000},
  function(err,address) {
    if(!err)
      console.log(address);});

//myContract is the ABI array at the contract address, startAFunc is the function name

The function prototype is as follows:

function startABet(string _Input} payable

I am getting this error:

  Uncaught Error: new BigNumber() not a number: [object Object]

The code was working a while ago. I wanted to make a little modification by sending a variable instead of a hard coded value, but was not able to do so. Later I tried to revert back, now this is not working either.
Can anyone please tell me what is the wrong that I am doing here. I have spent days on this, but haven't been able to figure it out.
I am running it on chrome browser with metamask extension on a ubuntu machine.


texts: truffle exec scripts/seed-exchange.js --network kovan

texts:
I've been running into an error when I attempt to seed my exchange/contracts on the kovan test network. Any help would be appreciated.

Using network 'kovan'.

Token fetched 0x69e0a4354aa5c2Ba68D4DF44D05f91BaEB3701Ed
Exchange fetched 0x700Be86E624f370202169C4F352db5Bf8464d7E8
{ Error: invalid address (arg="_to", coderType="address", value=undefined)
    at Object.throwError (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/errors.js:68:1)
    at CoderAddress.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:467:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:605:21
    at Array.forEach (<anonymous>)
    at pack (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:604:1)
    at CoderTuple.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:764:1)
    at AbiCoder.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:897:1)
    at ABICoder.encodeParameters (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/src/index.js:96:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/src/index.js:426:1
    at Array.map (<anonymous>)
    at Object._encodeMethodABI (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/src/index.js:425:10)
    at constructor.detectNetwork.then.network (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-contract/lib/execute.js:170:1)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)
  reason: 'invalid address',
  code: 'INVALID_ARGUMENT',
  arg: '_to',
  coderType: 'address',
  value: undefined }```


texts: How to transfer ETH between two addresses using geth and json rpc

texts:
I have geth running on my server. I am building a php website which act as wallet. Now iam able to create addresses.
I need to be able to deposit and withdraw ETH between addresses on same node.  I start geth with below command.

go-ethereum/build/bin/geth console  --rpc --rpcapi="db,eth,net,web3,personal,web3" --rpccorsdomain "*" --syncmode "light"

How to acheive the functionality of a wallet on geth over rpc ? Is there a command or API call for that? Iam finding it hard to understand the documentation.

UPDATE: What I want to do is transfer ETH from one account to another. Below are the api calls i tried and the errors I got in the browser when i call transfer function in my php class. Can someone please correct me

  {"jsonrpc":"2.0","id":1,"method":"personal_signAndSendTransaction","params":[[{"from":"0xb60e8dd61c5d32be8058bb8eb970870f07233155","to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","gas":"0x76c0","gasPrice":"0x9184e72a000","value":"0x9184e72a","data":"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"}],"passphrase"]}

Fatal error: Uncaught RPCException: json: cannot unmarshal array into Go value of type eth.SendTxArgs

  {"jsonrpc":"2.0","id":1,"method":"personal_sendTransaction","params":[[{"from":"0xb60e8dd61c5d32be8058bb8eb970870f07233155","to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","gas":"0x76c0","gasPrice":"0x9184e72a000","value":"0x9184e72a","data":"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"}],"passphrase"]}

Fatal error: Uncaught RPCException: The method personal_sendTransaction does not exist/is not available thrown

  {"jsonrpc":"2.0","id":1,"method":"eth_sendTransaction","params":[{"from":"0xb60e8dd61c5d32be8058bb8eb970870f07233155","to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","gas":"0x76c0","gasPrice":"0x9184e72a000","value":"0x9184e72a","data":"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"}]}

Fatal error: Uncaught RPCException: account is locked thrown

Please help!


texts: Correct syntax for estimating gas cost of a function in Web3?

texts:
Suppose I have the following function:

function SetMessage (bytes32 _message) returns (bool success) {
    message = _message;
    return true;
    }

Which might be called in Web3 as follows, for example:

MyContract.deployed().then(function (contractInstance) {
      return contractInstance.SetMessage(_message, { gas: 200000, from: web3.eth.accounts[0] })
    })

What is the correct syntax for using the estimateGas function in Web3 for this function? I have seen the following example for how to use estimateGas (here it's just checking how much gas to transfer ether from one account to another, not checking a function in a contract):

console.log(web3.eth.estimateGas({from: web3.eth.accounts[0], to: "0xEDA8A2E1dfA5B93692D2a9dDF833B6D7DF6D5f93", amount: web3.toWei(1, "ether")}))

However I'm unsure how to use estimateGas to estimate gas for executing a function in a smart contract.


texts: Best way to send an address to the constructor in Remix?

texts:
I know how to pass an ETH address to the constructor in truffle. What is the best way to do it in Remix?

Say contract A is in Remix to create Tokens and contract B (another solidity file) is the actual Crowdsale contract.

What is the best way to send the contract address that is generated when you compile the token contract to the crowdsale's constructor?

For example here is my Constructor:

function Crowdsale(address _tokenAddress) {
    require(_tokenAddress !=0);
    token = Token(_tokenAddress);
  }

I
In truffle you pass it in to the 2_deploy_contracts.js file. How would the same be done in Remix?


texts:
I've seen a contract that stores -1 as an unsigned integer.

uint256 can = allowed ? uint256(-1) : 0;

Can anyone explain the benefit of this over something like:

uint256 can = allowed ? 1 : 0;


texts: Can Ethereum based tokens be used to represent a voting share in a private company?

texts:
If tokens are issued to represent votes for a private company are they considered securities by the SEC?

I want to create a legal entity, like a trust, that will appoint board members who oversee a private company. Tokens will be issued to represent votes for these purposes as well as rights to a share of company profits.

The company would be wholly owned by the trust, and legal matters/decisions like the appointment of board members could only be affected by votes from token holders.

I would disseminate profits by creating a "pool" from which token holders would be able to claim their share periodically, for example quarterly.


texts: If I understand correctly, DGD pays you a small free on all digix gold trades. Now, what happens when you deposit your DGD in an exchange? The DGD is still yours, so you're supposed to receive the dividend, but obviously it goes to the exchange instead. Wouldn't it cause a massive withdrawal/deposit movement surrounding payment days?


texts: Drizzle Installation: pauses at fetchMetadata: sill resolveWithNewModule http-https@1.0

texts:
I am following this tutorial https://www.trufflesuite.com/tutorials/getting-started-with-drizzle-and-react. Everything is working smoothly until I have to npm install drizzle. I then run into the problem where it shows "fetchMetadata: sill resolveWithNewModule http-https@1.0" forever and just pauses.

Also the versions(if they help at all):

Truffle v5.0.21 (core: 5.0.21)

Solidity v0.5.0 (solc-js)

Node v10.16.0

Web3.js v1.0.0-beta.37


texts: how to find destination address and value from transaction


texts:
Debugging smart contract errors can be surprisingly hard. There is one particular kind of error that annoys me the most: the infamous rpc error with payload.

For instance, just a few hours ago, while deploying a smart contract from the front-end using new web3.eth.Contract().deploy() into ganache-cli, I got the following in the browser's console:

MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload {
  "id": 4972589614702,
  "jsonrpc": "2.0",
  "params": ["<a long hex string>"],
  "method": "eth_sendRawTransaction"
} [object Object]

I've seen other errors like this while googling it, except the last part, [object Object], contains an actual error message. But in my case, no.

I tried converting the long hex string to Unicode, but no luck:

> web3.utils.toUtf8('<a long hex string>')
Uncaught Error: Invalid UTF-8 detected

Then I tried with the .toAscii method and got garbled text. Some of it was legible, though; here's a sample:

'\u0003\u0019\u0016R` \u0001P[PPPP`@Q\u0003
a\u0017)Wþ[\u0004PPPPPVþSafeMath: multiplication overflow¢ebzzr1X \u001aó9r\n' +
  '¢¥Ä

However, since there were other error strings as well, I doubt that this is the actual error. So maybe it was fruitless to try to decode that hex string.

After banging my head against the wall for some time, I truffle compiled the solidity code again, copied the new JSON into my front-end, and things were working again. Most people seem to solve these errors in seemingly random ways like this, but there should be a less frustrating path. So I have two questions for you:

What steps do you recommend to debug this kind of error?
Is there an issue raised somewhere to make handling this kind of error a little bit more dev-friendly?


texts:
I was about to create my first smart contract which I came across these questions:

Where exactly the contract code gets stored, I read that it kind of stores in blockchain so does that mean every node that has an instance of a full blockchain has the contract code too?
Should a miner in order to mine a new block first run all the contract calls and set the values and then start too looking for POW puzzle solving and nonce value, and if so then can we have ASIC miners for ethereum like bitcoin, because they can do only a specific job but running a contract codes are different every time?
When a miner wants to verify a transaction which has a contract call should it run the contract code? if so, does it mean that each contract gets to run multiple time until finally one miner can find the right nonce and solve the pow puzzle? if that's true it means the contract code gets to run many times unnecessarily?
Where do the values of contract variables store, I mean if we have a solidity mapping it can contain lots of key values, so where does this key, values stores? if they store in blockchain then they should be stored in every node that has a copy of blockchain which means a massive data gets to store over and over and over again, and that would be such a storage waste
When a contract Self-destructs what exactly happens, it mentioned that the code will be removed from blockchain, so does it mean a transaction make it unavailable for following transactions or it really really alter the blockchain and remove it coded from older blocks?


texts: How to create more test account when using Mocha to test Solidity smart contract?

texts:
By default there are only 10 test accounts being created, how do I create more when using Mocha to test smart contract?

I assume Mocha creates a testRPC instance somehow, there must be a way to modify that settings.


texts: Scalability of uPort for millions of users scenarios

texts:
I am currently working on a project using Ethereum, IPFS off-chain storage and uPort for identity management in a private Blockchain.
I fail to find any study/project that analyzes the scalability of uPort with data for scenarios when millions of people need to give some personnal information through uPort. How many servers would be required? How would it scale with data size? Time overhead? etc.
Thank you.


texts: Benchmarking energy usage of executing smart contracts

texts:
I'm working on a project that will allow for me to benchmark of the top ten most popular smart contracts which I'll take from EtherScan.

The idea of the project is to determine if the smart contract execution rewards are proportional to the cost incurred to the miners.

I understand the other overheads such as Transaction validation, Signature validation and POW computation. My idea is to perform execution in a single client EVM and simulate the other aspects as needed. But i'm not quite sure how to go about this.

Then there is the problem of measuring energy usage of execution. I was thinking a potential estimation, or I could use a device such as a Kill-A-Watt to measure output from the wall. Not sure if this is feasible also.

Then i'm looking for a way to continuously run these executions taking the energy usage over 50 executions and produce an average for reference.

I'm not sure where to start with this project and if it's even possible, any help would be appreciated.

If you have any questions I'll be happy to clarify.

Note: I am new to Ethereum so i'm sorry if some of my knowledge is wrong or incorrect


texts: What is wrong with this code, deployed but showing error while sending ether?

texts:
I have tried to compile this code for crowdsale and also have deployed the contract on Rinkeby Network. But each time I send a transaction, it says Warning! Error Encounter during Contract Execution [execution reverted]. Here's the code

pragma solidity ^0.4.18;

interface token {
function transfer(address receiver, uint amount) external;
}

contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;

event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);

/**
 * Constructor function
 *
 * Setup the owner
 */
function Crowdsale(
    address ifSuccessfulSendTo,
    uint fundingGoalInEthers,
    uint durationInMinutes,
    uint etherCostOfEachToken,
    address addressOfTokenUsedAsReward
) public {
    beneficiary = ifSuccessfulSendTo;
    fundingGoal = fundingGoalInEthers * 1 ether;
    deadline = now + durationInMinutes * 1 minutes;
    price = etherCostOfEachToken * 1 ether;
    tokenReward = token(addressOfTokenUsedAsReward);
}

/**
 * Fallback function
 *
 * The function without name is the default function that is called whenever anyone sends funds to a contract
 */
function () payable public {
    require(!crowdsaleClosed);
    uint amount = msg.value;
    balanceOf[msg.sender] += amount;
    amountRaised += amount;
    tokenReward.transfer(msg.sender, amount / price);
   emit FundTransfer(msg.sender, amount, true);
}

modifier afterDeadline() { if (now >= deadline) _; }

/**
 * Check if goal was reached
 *
 * Checks if the goal or time limit has been reached and ends the campaign
 */
function checkGoalReached() public afterDeadline {
    if (amountRaised >= fundingGoal){
        fundingGoalReached = true;
        emit GoalReached(beneficiary, amountRaised);
    }
    crowdsaleClosed = true;
}

/**
 * Withdraw the funds
 *
 * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
 * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
 * the amount they contributed.
 */
function safeWithdrawal() public afterDeadline {
    if (!fundingGoalReached) {
        uint amount = balanceOf[msg.sender];
        balanceOf[msg.sender] = 0;
        if (amount > 0) {
            if (msg.sender.send(amount)) {
               emit FundTransfer(msg.sender, amount, false);
            } else {
                balanceOf[msg.sender] = amount;
            }
        }
    }

    if (fundingGoalReached && beneficiary == msg.sender) {
        if (beneficiary.send(amountRaised)) {
           emit FundTransfer(beneficiary, amountRaised, false);
        } else {
            //If we fail to send the funds to beneficiary, unlock funders balance
            fundingGoalReached = false;
        }
    }
}

}

Here's the deployed contract address - 0xBa31314526372F57858EeF03381e5853ec20Ec30


texts:
Your build artifacts are saved within the ./build directory, along side the compiled deployed contract artifacts in ./build/contracts.

What exactly are these artifacts?


texts: Ubuntu 18.04: Error during compilation using Truffle: How to install the updated version

texts:
I am working on Ubuntu 18.04.  I have installed Truffle from the following site:

Truffle for Linux

I am trying to execute an application from the following site:

Petshop Tutorial

I am able to create the temporary file:

    @lc2530hz:~/pet-shop-tutorial$ truffle unbox pet-shop You can improve web3's peformance when     running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project

    Starting unbox...
    =================

    ✔ Preparing to download box ✔
      Downloading
      npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to     chokidar 3 with 15x less dependencies.
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.2.13
npm WARN pet-shop@1.0.0 No description
npm WARN pet-shop@1.0.0 No repository field.
✔ cleaning up temporary files
✔ Setting up box

    Unbox successful, sweet!

    Commands:

      Compile:        truffle compile
      Migrate:        truffle migrate
      Test contracts:   truffle test
      Run dev server: npm run dev

    @lc2530hz:~/pet-shop-tutorial$

However I am getting error in compilation

$ truffle compile
You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project

Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
✔ Downloading compiler. Attempt #1.
Error: Could not find __Truffle__NotFound.sol from any sources; imported from /home/zulfi/pet-shop-tutorial/contracts/adoption.sol
    at Resolver.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/resolver.js:53:1)
    at Generator.next (<anonymous>)
    at fulfilled (/usr/local/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/resolver.js:5:42)
    at <anonymous>
Truffle v5.1.27 (core: 5.1.27)
Node v8.10.0

@lc2530hz:~/pet-shop-tutorial$

Somebody please guide me.

Have I installed an older version? Please tell me how to install the updated version for Ubuntu 18.04?

Zulfi.


texts: Why are transaction tries in Ethereum not plain Merkle Tries?

texts:
I understand the Ethereum block header contains a Merkle Patricia Trie (MPT) root for the global state, one for receipts (which I don't understand but am not focussed on for now), and one for all the transactions in the block.

I also understand why an MPT might be more efficient to use for the state tree, namely because it makes it easier to secure data that is structured around accounts ids and referenced by account id.

However I don't understand why the transaction trie for the block needs to be an MPT instead of a plain Merkle Trie. Presumably you can just use the transactions list in a block to modify the state trie, and be assured that the transaction list is valid with a plain Merkle Trie root.

I can't see any benefit of structuring transactions as a Patricia Trie where transactions would presumably be organised by their hash which is unique and which points to data that will never change.

So why not just use a plain Merkle Trie for transactions? Is it just to keep consistency with the way Storage and State tries are structured (and in which the benefit of the MPT structure is clearer)?


texts:
I'm trying to save memory by storing a game's 8x8 board as a binary value but am having trouble:

Each square on the board can be either 10 (black), 11 (white), or 00 (empty) and there are 64 squares. That's 128 binary digits so this should be 16 bytes (128/8) right?

How do I handle that in solidity? Would I say bytes16 foo = 0b10111000...?

Anyone have a link or advice with working directly with bytes in solidity?

Ultimately I'd like to use them as keys in a mapping...


texts:
I have array of structures on-chain and need to sort it. I used one of that quicksort algorithms that easily can be found and adopted it to use structures instead of plain uints. But I dislike it because it requires "swap" operation - change places of 2 items is the array. With structures it is possible only by creating memory instance like MyStruct memory temp and copy one of swappables there, then replace it and put memory-stored one into copied place. It is expensive.

I though that I could use mapping like mapping (uint16 => MyStruct) list and then just "swap keys". But it seems that with mapping I have to to the same - copy values because I cannot change key values.

Am I missed something or mapping cannot helps me here?


texts:
The error pops up whenever I try to compile through truffle, not able to figure out a solution any help is highly appreciated.
Here is the error

Compiling your contracts...
===========================
> Compiling ./contracts/Migrations.sol
> Compiling ./contracts/OraclizeTest.sol

Error: CompileError: /root/Latest->querytransaction Working  GOLD/oraclize-test/contracts/OraclizeTest.sol:36:9: ParserError: Expected token Semicolon got 'Return'
        return true;
        ^

Here is the solidity file

 function deposit(uint team) public payable returns(bool success) {
        if(team == 1)
        {
        homeBet = msg.sender;
        amountStore[msg.sender] += msg.value;
        emit LogDeposit(msg.sender, msg.value, "Executed deposit HOME");
        oraclize_query("URL", "json(https://api.crowdscores.com/v1/matches/123945?api_key=93c4c515196741beaf5e4528b64ea511).outcome.winner");
        return true;
        }
        else if(team == 2)
        {
        awayBet = msg.sender;                //---->> LINE NUMBER 36
        amountStore[msg.sender] += msg.value;
        emit LogDeposit(msg.sender, msg.value, "Executed deposit AWAY");
        oraclize_query("URL", "json(https://api.crowdscores.com/v1/matches/123945?api_key=93c4c515196741beaf5e4528b64ea511).outcome.winner");
        return true;
        }
    }


texts: is it possible to get events from transactions that are in the `txpool`?

texts:
Is it possible to see the events that will be emitted in the txpool, or is only the transaction information available?

For example, can I search in either the queued or pending transactions and search each transaction for their respective event? If I find someone that is interacting with a DEX, can I see what the result of their transaction will be (the event), or can I just see the input params and associated transaction information?


texts: Struct and Mapping input value error of Invalid Opcode while calling setSeller() to store multiple seller's addresses

texts:
What dose the -1 means? Or why we should use -1 while pushing one element in array. What should I enter in sellerAccounts: field as input?

pragma solidity ^0.5.1;

contract Seller{

    struct Sellers{
        uint sellerId;
        address sellerAddress;
        string sellerName;
    }
    mapping (address => Sellers) sellerStruct;
    address[] public sellerAccounts;

   function setSeller(address _address, uint _seller_id, string memory _seller_name) public{
        Sellers memory sellerVar = sellerStruct[_address];
        sellerVar.sellerId = _seller_id;
        sellerVar.sellerName = _seller_name;
        sellerAccounts.push(_address) -1;
    }
}


texts: How fast is Ethereum blockchain growing and how big is it likely to get in the future? Is it still about 1 GB per month? Are there any data pruning or compression algorithms in place or planned to be used?


texts:
so i have completed step 5 i think but don't understand the rest of the steps, can anyone break them down further for me??? thank you:

5.Using git, check out cpp-ethereum. You’ll want to open a command prompt or PowerShell, find a directory you like, then type this command: git clone https://github.com/ethereum/cpp-ethereum

6.Next, you’ll want to switch to the “develop branch” of cpp-ethereum. To do this, in that same terminal, ‘cd’ into the /cpp-ethereum directory (the one created by the previous git command), and then type:
git checkout develop

7.Next, cd into /cpp-ethereum/extdep, and run:
getstuff.bat
This should download a bunch of stuff. You just gotta wait for it to finish.


texts: "[Errno 2] No such file or directory: 'solc' " Using py-solc and solidity

texts:
I installed py-solc and solidity:

solc, the solidity compiler commandline interface
Version: 0.4.16+commit.d7661dd9.Darwin.appleclang

and ran this code in python (with a contract source example):

from solc import compile_source, compile_files, link_code

    source = """
    pragma solidity ^0.4.2;
    contract Example {
        string s="Hello World!";
        function set_s(string new_s) {
            s = new_s;
        }
        function get_s() returns (string) {
            return s;
        }
    }"""

compiled = compile_source(source)

and the compile_source() function returned this error:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    compile_source("pragma solidity ^0.4.0;\n contract Foo {}", output_values=["bin", 'abi'])
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/solc/main.py", line 106, in compile_source
    stdoutdata, stderrdata, command, proc = solc_wrapper(**compiler_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/solc/utils/string.py", line 85, in inner
    return force_obj_to_text(fn(*args, **kwargs))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/solc/wrapper.py", line 155, in solc_wrapper
    stderr=subprocess.PIPE)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'solc'

how is it possible to fix this issue and compile using py-solc?


texts:
How does CryptoKitty implement scheduling functions such as give birth function or auction ending function.

I tried to track it through Eth Fiddle but didn't find how it was done. Is there a function that calls itself every block mined and makes all the necessary checks whether the birth time or auction time is up?

I wanted to know because I wanted to do something similar, I want to create an auction and after a certain duration, the object would go to its highest bidder automatically.

I looked into Ethereum Alarm Clock but it seems a little unstable at the moment and doesn't seem to be live on main net either.

Thanks in advance.


texts:
First of congrats for the great work in the forum! I´ve tried to avoid posting but I can´t find the solution to my problem, this is causing me lots of stress and I really don´t know what else to do now.

Recently I opened and account at myetherwallet.com, then I printed the Wallet and the private key. After this I installed MetaMask as you suggested but when I logged in using it, my address suddenly changed, the little picture also changed. It won´t allow me to download the Wallet and private key for this address, Im quite confused.
Now when I log in using metamask in Myetherwallet it takes me to this new address which is not the original one...

PD. I managed to open the original address account through the Keystore/JSON file method, but when accessing through Metamask it takes me to this other address...

I must have done something wrong in the process but can´t recall exactly what it is.
Kind Regads.


texts: I have only saved the UTC file generated from myetherwallet and after losing data from my laptop i lost the document where i had my password and private key. Can i recover my account now ?


texts: Why use anything but uint256/int256 outside of a struct?

texts:
I see how uint8 can save space within a struct, but outside of that I do not see any reason to use anything but uint256. The gas cost is slightly higher for uint8.  The only reason I can think of is that you want to ensure users do not generate large numbers, but then any internal checks to make sure you do not have an overflow will already do that.

Not a big deal, but if I'm wrong I suspect I am missing something important.


texts: Contract hash is not unique for each deploy?

texts:
I created a contract.

https://ropsten.etherscan.io/tx/0x74426948905cd6e70e8b9d64a660b3c179b7c8a224ca5cd0234842768eb501db

The contract hash is 0x692a70d2e424a56d2c6c27aa97d1a86395877b3a

etherscan shows the contract has many transactions. The latest three transactions are mine. But the other txes are sent by someone.

https://ropsten.etherscan.io/address/0x692a70d2e424a56d2c6c27aa97d1a86395877b3a

My contract was copied and pasted from tutorial page. I think this is the cause since data is same. Is this my understanding correct?

pragma solidity ^0.4.0;
contract Addition {
  int num = 0;
  function add(int a){
    num += a;
  }
  function get() returns(int){
    return num;
  }
}


texts: Is it possible to alter the msg.sender variable when calling another function in the contract?

texts:
I have the following contract:

pragma solidity >=0.4.24;

contract ERC20Interface {

    string public constant name = "Udacity Token";
    string public constant symbol = "UDC";
    uint8 public constant decimals = 18;  // 18 is the most common number of decimal places

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

    function totalSupply() public view returns (uint);
    function balanceOf(address tokenOwner) public view returns (uint balance);
    function transfer(address to, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function allowance(address tokenOwner, address spender) public view returns (uint remaining);

}

contract MyToken is ERC20Interface  {
    uint _totalSupply;
    mapping (address => uint) private balances;
    mapping (address => mapping (address => uint )) private approvedSpenders;

    constructor(uint amount) public {
        _totalSupply = amount;
        balances[msg.sender] = _totalSupply;
    }

    modifier onlyWithBalance(address from, uint tokens) {
        require(balances[from] >= tokens, "Not enough balance");
        _;
    }

    modifier onlyWithAllowance(address tokenOwner, address spender, uint tokens) {
        require(approvedSpenders[tokenOwner][spender] >= tokens, "Not enough allowance");
        _;
    }

    modifier onlyDifferentAddresses(address from, address to) {
        require(from != to, "Cannot send tokens to the same address");
        _;
    }

    modifier onlyWithValue(uint tokens) {
        require(tokens > 0, "Cannot send 0 tokens");
        _;
    }

    function totalSupply() public view returns (uint) {
        return  _totalSupply;
    }

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

    function transfer(address to, uint tokens)
        onlyDifferentAddresses(msg.sender, to)
        onlyWithValue(tokens)
        onlyWithBalance(msg.sender, tokens)
    public returns (bool) {
        balances[msg.sender] -= tokens;
        balances[to] += tokens;

        emit Transfer(msg.sender, to, tokens);

        return true;
    }

    function transferFrom(address from, address to, uint tokens)
        onlyDifferentAddresses(from, to)
        onlyWithValue(tokens)
        onlyWithAllowance(from, msg.sender, tokens)
        onlyWithBalance(from, tokens)
    public returns (bool) {
        balances[from] -= tokens;
        approvedSpenders[from][msg.sender] -= tokens;
        balances[to] += tokens;

        emit Transfer(from, to, tokens);

        return true;
    }

    function approve(address spender, uint tokens) public returns (bool) {
        approvedSpenders[msg.sender][spender] = tokens;

        emit Approval(msg.sender, spender, tokens);

        return true;
    }

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

The issue lies on transfer and transferFrom implementations. There is some code duplication that I'd like to remove.

How could I implement transferFrom in terms of transfer? In other words, how could I set the msg.sender variable from within transferFrom?


texts:
This is my code:

   function send() {
    Web3.providers.HttpProvider.prototype.sendAsync = Web3.providers.HttpProvider.prototype.send;
    var web3 = new Web3("http://localhost:8545");
    var data = web3.eth.getHashrate();
    alert(data);
}

when i run the send() function I am getting this error: "TypeError: this.provider.sendAsync is not a function"


texts: Will setting an uninitialized mapping value to 0 cost gas?

texts:
Say I have a mapping:

mapping (address => bytes32) public someMapping;

I then set someMapping[msg.sender] = 0

(let's say that address has never been set before). Will that cost gas, or will it figure out that no action is required?


texts: difference between button [publish] and [create] ? (Remix tool)

texts:
sorry,just ask a simple question...
what is difference between button [publish] and [create] ?
(on Remix Tool UI)

thanks a lot~
hippo


texts: WEB3.JS How do I configure a payable function front end with the input (DAPP)

texts:
I am trying add the front end part of a payable function using web3.js (And just vanilla JavaScript, no other libraries).

Here is the solidity function:

    function deposit() public payable {
        balance[msg.sender] += msg.value;
    }

Here is a picture of the front end:

I have created a contract for the withdrawal.

function withdraw() {
            amount = withdrawInput.value * 1000000000000000000;
            contract.withdraw(amount, function (err, result) {
                if (err) {
                    console.log('An error occured', err);
                    loadAccount();
                } else {
                    console.log('You have successfully withdrawn ' + amount / 1000000000000000000 +
                                ' ether to your wallet.');
                    loadAccount();
                };
            });
        };

But I am completely lost on how to set the transaction value to the amount set in the input.
Oh, if it helps the HTML element ID's important for the deposit function are "depositInput" (to set transaction value) and "depositButton" (To call the function).


texts: How is it determined if a passphrase has correctly decrypted the private key for a wallet address?

texts: When I load the JSON file of the wallet into MyEtherWallet, how does it determine if the passphrase is correct or incorrect? After I initially give a passphrase to encrypt my wallet's private key, is the mapping between the decrypted and encrypted private keys stored anywhere?


texts: Why use the Interface (IERC20), instead of the implementation contract (ERC20)?

texts:
I'm playing with a contract that uses an ERC20 token, and I can see basically 2 options to init the token:

Use the interface contract (IERC20)
Use the implemented contract (ERC20)

Interface version:
import "https://github.com/OpenZeppelin/openzeppelincontracts/blob/v3.4.0/contracts/token/ERC20/IERC20.sol";

    contract UseIERC2oToken {

      IERC20 itoken = IERC20(0x5Bd2a79Eb49920C645de715048e0EE571DB505E5);
      (...)
    }

Implementation version:
import "https://github.com/OpenZeppelin/openzeppelincontracts/blob/v3.4.0/contracts/token/ERC20/ERC20.sol";

contract UseERC2oToken {

    ERC20 token = ERC20(0x5Bd2a79Eb49920C645de715048e0EE571DB505E5);
(...)
}

I have seen that most of the times, developers use the interface but both options get the same result, but I'm not sure what option is more efficient. Any idea?
Thanks too much


texts: how ethereum smart contract is connected with ios app

texts: I want to implement ethereum smart contract with iOS app using webView . I tried so much but it didn't work. How to call smart contract with iOS app using swift


texts: Does each creator coin require a smart contract?

texts:
I'm trying to build an app where each user who signs up gets their own coin, similar to how users who sign up for BitClout are given their own, unique Creator Coin (continuous token w/ a Bancor bonding curve).
Would this require creating a new smart contract for each user? I've been poking around at the OpenZeppelin ERC20 contract templates and I've been wondering whether a new contract would have to be generated each time a user signs up, so each one could have a unique coin.


texts:
I receive this error when I'm trying to connect to the websocket

WebSocket connection to 'wss://ropsten.infura.io/ws' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

Code snippet

import web3 from 'web3';
var web3lib = new web3(
  new web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'),
);
console.log(
  'provider in web3 eth: ' + JSON.stringify(web3lib.currentProvider),
);
console.log('New block in web3 eth: ' + web3lib.blockNumber);
var subscription = web3lib.eth.subscribe('newBlockHeaders', function(
  error,
  result,
) {
   if (!error)
       console.log("output of web3 stream"+JSON.stringify(result));
       else
  console.log('Error of web3 stream ' + JSON.stringify(result));
});

What am I doing wrong here?


texts: Using contract to create Child contracts (web3j Java wrapper)

texts:
I have a simple Parent contract that creates child contracts and stores their address.

contract Parent {
    address[] public registry;

    function createChild () public {
        address newChild = address(new Child());
        registry.push(newRecord);
    }
 }

 contract Record {
    string public uid;
 }

Using web3j generated wrappers, I try to call this creation method:

contract.createChild().send();

contract being the Parent instance. However I get this error:

{
  "timestamp": "2019-07-05",
  "status": 500,
  "error": "Internal Server Error",
  "message": "org/bouncycastle/jcajce/provider/digest/Keccak$DigestKeccak",
  "path": "/api/deployRecord"
}

Can anyone tell me why? Or can I achieve this some other way using web3j? It seems like a really simple thing to do :/

Thanks


texts: Where can you check how much Ether has been exploited / stolen from theDAO?

texts: Is there a site where you can check how much Ether has been exploited/stolen from theDAO? So far I only know of the first attack, which was 3 million stolen, but I read more people are doing this same attack to drain theDAO. Where can one see the status of this drain?


texts: What does the bytes format “\xFF\xFF\xFF” mean and how it is interpreted?

texts: bytes sig =  hex"aca7da" and bytes sig = "\xac\xa7\xda" seem to be the same thing, ASCII interpreted as hex. Does the format "\xFF\xFF\xFF" somehow code that it should be read as hex?


texts: Does the ethereum ecosystem exist out of one or multiple blockchains?

texts:
Most of my knowledge is based on BTC which doesn't have the concept of (ERC-20) 'Tokens' so I have a question related to that:

Does the Ethereum 'ecosystem' with its hundreds or even thousands of tokens have one big Blockchain? Or does every token have its own Blockchain?


texts: How to have the contract check if the msg.sender currently owns a specific token. (erc721)

texts:
Assuming I have a contract to mint my own NFTs: (I'm thinking ERC-721, but not necessarily).
I want to create another smart contract that before doing anything, verifies that the address interacting with it (msg.sender) currently owns an NFT minted by that specific contract. Even better, if it could read an attribute, like the NFT id.
Is that even possible? I did some research on it, but apparently the address doesn't actually stores the balances/tokens, only eth. But I'm guessing it must be a way, given how those NFTs gallery works.
If it's possible, how could I do it?


texts: How to read the Ethereum Block header and check contract

texts:
I have downloaded some Ethereum block headers, such is one example (omitted some details for conciseness):
{"difficulty": 7314508281338, "extraData": "0xd583010203844765746885676f312e35856c696e7578", "gasLimit": 3141592, "gasUsed": 42000, "transactions": [{"blockHash": "0xfd3429fd7f80ab12cda16bdf057924ebef4a5598b0acf03cd9d8851b6d874dd1", "blockNumber": 461461, "from": "0x99181ED48C7c51532622dA23e20E2B38392476A7", "gas": 21000, "gasPrice": 50000000000, "hash": "0xa2818b5196faf44155d02b3dff32b56901c19ed42c89a19510f0ee423226fec4", "input": "0x", "nonce": 121, "r": "0xda0de222b5687c09d6637d5aa6f7535364508e8a015f429a9edb91adb71049f4", "s": "0x7504edc5e8434f5760eebd25876f53a9a00396aa063e816365f6f028bbbb4150", "to": "0x32Be343B94f860124dC4fEe278FDCBD38C102D88", "transactionIndex": 0, "v": 27, "value": 1793167180000000000}], "transactionsRoot": "0xf4c6fd4e82da8310c8cd0ddbee357ccc3bf1bd15e33ac481fd4298447c0a81ae", "uncles": []}
I was wondering if it was possible to see whether it is possible to figure out this transaction was from a particular contract or simple payment? I was thinking to check whether the "to" address is a contract address or not, but was wondering if I am understanding this correctly. TIA


texts:
I want to make a coin which can stake on Ethereum most of the functionality is done but I want to see some reference to see that if I'm missing anything. I can't find anything direct on google. Can anyone help me find any coin which can stake and has code for reference.
Thank you!!


texts: Is there anybody who has developed the Dapp using truffle framework and ethereum testnet ? I am getting some alien errors and i am not getting the solution on internet.So i need a person who has done it start to end? Your help will be precious to me.


texts:
My Code below ( Following an Online Course, absolute beginner here ^_^)

pragma solidity >=0.4.17 <0.7.0;

contract CampaignFactory{
    Campaign[] public deployedCampaigns;

    function createCampaign(uint minimum) public{
        Campaign newCampaign = new Campaign(minimum,msg.sender);
        deployedCampaigns.push(newCampaign);

    }

    function getDeployedCampaigns() public view returns ( Campaign[] memory) {
        return deployedCampaigns;
    }
}

contract Campaign{

    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping( address => bool ) approvals;

    }

 Request[]  public requests;
 address public manager;
 uint public minimumContribution;
 mapping( address => bool) public approvers;
 uint public contributersCount;

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

  // constructor************************************************
    constructor(uint minimum,address creator) public {
        manager = creator;
        minimumContribution = minimum;

    }

    function contribute() public payable{
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        contributersCount++;

    }

    function createRequest(string memory description, uint value, address recipient ) public restricted() {
        Request memory newRequest = Request({
            description: description,
            value: value,
            recipient: recipient,
            complete: false,
            approvalCount: 0

        });

        requests.push(newRequest);

    }

    function approveRequest( uint index) public{
        Request storage request_index = requests[index];

        require(approvers[msg.sender]);

        require(!request_index.approvals[msg.sender]);

        request_index.approvals[msg.sender] = true;

        request_index.approvalCount++;

    }

    function finalizeRequest(uint  index) public payable restricted {
        Request storage  request = requests[index];
        require(request.approvalCount > (contributersCount / 2));
        require(!request.complete);

        //address payable recipient = address(uint160(request.recipient));
        //recipient.transfer(request.value);
        // above is one of the ways i got to know for implementation but sticking to the course
        payable(request.recipient).transfer(request.value);
        request.complete = true;

    }

}

NO ERROR but NO transfer of ether (last two lines), tried in REMIX everything works fine, except no  ether is transferred

A Beginner here, following an online course, making a DApp , also after compiling the contract through Compile.js, no build=> .json file is build, which i guess is because of faulty solidity contract above, works fine for the course instructor, i guess its because the code is outdated?

is there a solution for this or i have to find a alternative for this?


texts:
As per the web3 doc, I'm using following code to watch the events from a contract:

contractInstance.eNonIssueDeposits({}, {fromBlock: 0, toBlock: 'latest'}, (error, result) => {
    if (!error) {
        console.log(result);
    } else {
        console.log(error);
    }
});

The Tx is successful and also logged an event but the function callback didn't initiated. What's wrong with the code?


texts: I flattened my pc and then reinstalled Mist it now asks me to open a "new" account. I want to reinstall my old one... how do I do it? I am currently downloading chsindata. I have my JSON files etc.


texts: How does Solidity handle insertion of duplicate keys in mapping?

texts:
I tried to insert two entries of identical keys into a map for testing.

The map seems to reject the later entry and preserves the original entry.

Is this just Solidity behaving normally? (If it is not, then it means something is wrong with my code.)

I read somewhere that HashMaps are meant to overwrite any entries when inserting a duplicate key.

Are hash maps in solidity designed to handle data differently? What is it meant to do when encountering a duplicate key entry?

Solidity documentation doesn't seem to dig too deep into this.


texts: transferFrom is not displaying DAI amount on MetaMask verification popup

texts:
I am using web3.min_1.36.js to send DAI to a contract. I already called "approve", so transferFrom is working correctly without error.

However, the Metamask verification popup does not display the DAI amount that will be transferred. It just shows "CONTRACT INTERACTION", and the gas fee.

This will confuse users of my app, because they will not know what DAI amount they are verifying.

How do I force the Metamask verification popup to show the DAI amount that will be transferred?

Here is the code that performs transferFrom:

var objOption = {from: gsMyEtherAddress};
var objContract = new gobjWeb3_metamask.eth.Contract(gsABI_ERC20, gsDaiContractAddress);

objContract.methods.transferFrom(
    gsMyEtherAddress, gsMyContractAddress, gobjWeb3_metamask.utils.toWei((.3).toString(), 'ether')
).send(objOption, async function(error,result){
    if (!error) {
        console.log(result)
    } else {
        alert("Error: " + error.message);
    }
});


texts: How can i create more that one node for test purposes?

texts:
I really need to have more than one node to test my smart contract. I'm using remix and i also installed ganache, however, ganache doesn't allow me to have more than one node as I hoped for...
I have this contract where I have two roles:
constructor() public{
    initiator = 0x9D565D6b14AfbCb57C8C833a9832c7c22879151C; //rentACar
    executor = msg.sender; //client

For testing purposes, I need to have one node representing the rentACar role an another representing the client role. How could I achieve this?
Will forking work? How to fork Ethereum from the current state?


texts: how to build Dapp for Android using react-native

texts:
I have a ethereum Dapp for web application and have metamask extension installed in my chrome browser to make transactions. Now i want the same application to be developed in android using react-native.

How to install some wallets like metamask in the devices and make transactions in mobile device without using Mainnet?

Is that possible to achieve this?If yes can any one please help me out on how to develop this app. Thanks in advance.


texts:
I can't get comparisons (==) of enum types compiling. The following example

contract Card
{
    enum Suit {Heart, Diamond, Shape, Club, Jocker}
    Suit public suit;

    enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, Jocker}
    Rank public rank;

    function equal(Card card) returns (bool)
    {
        return suit == card.suit && rank == card.rank;
    }
}

has the following compile errors

Card.sol:11:16: Error: Operator == not compatible with types enum Suit and function () returns (enum Suit)
        return suit == card.suit && rank == card.rank;
               ^---------------^
Card.sol:11:37: Error: Operator == not compatible with types enum Rank and function () returns (enum Rank)
        return suit == card.suit && rank == card.rank;

Any ideas on how variables of an enum type can be compared?

Thanks
Nick


texts: How to sign tx with privatekey in etherjs(nodejs)

texts:
How can i sign a transaction with etehrejs with a privatekey only?
The code i have requires mnemonic, which i dont want to use, i want to sign tx with privatekey
//const mnemonic = 'Mnemonic goes here';

const privateKey = 'Private key goes here'

const provider = new ethers.providers.WebSocketProvider('API goes here');
const wallet = new Wallet(walletMnemonic.privateKey);
//const walletPrivateKey =
//walletMnemonic.address === walletPrivateKey.address
const account = wallet.connect(provider);
const factory = new ethers.Contract(
  addresses.factory,
  ['event PairCreated(address indexed token0, address indexed token1, address pair, uint)'],
  account
);

So how can i sign the tx with the privateky?


texts:
I am getting this warning in remix. What does this mean? Am I missing something here?
Here is the simple code to demonstrate it:

pragma solidity ^0.4.20;

contract HelloWorld
{
string hello = "Hello World";
function sayHello() returns (string)
{
    return hello;
}
}

Now I am getting a warning:

browser/HelloWorld.sol:6:5: Warning: Function state mutability can be restricted to view
function sayHello() returns (string)
^ (Relevant source part starts here and spans across multiple lines).


texts:
I am currently working on building my own private network on Ethereum to build small apps. I am learning as I go so excuse me if this question is very obvious, but I have exhausted myself looking for solution over the internet and at geth docs, but nothing seems to work.
I am trying to make my private network with my own id, and make the nodes online so that they can see eachother. I have tried making two nodes on different laptops and different Internets, and also tried deploying a node on my AWS EC2 Instance of Linux Ubuntu (this is my final objective).
Here is what I have tried so far:

I am running geth with same genesis everywhere - 3x windows machines and 1x linux machine.
I have used --rpc, --rpcaddr, --rpcport, --rpccorsdomain, --http, --httpaddr, --httpport, --ws, --wsaddr, --wsport flags (in different iterations).
I have used --nat flag with extip as well.

When I run multiple nodes on multiple machines, the admin.nodeInfo.enode outputs my enode address with external IP, but when I add that IP to another machine using admin.addPeer it returns true (means the enode address is valid) but never reaches the node.
However, for what it's worth, I am able to add two nodes and communicate with eachother on local network only, but it does not work on remote IP. I am either missing something very basic or... I am missing something very basic. Any help will be appreciated!


texts: Using view modifer in solidity gives error in truffle compiler "ParserError: Expected token LBrace got 'View'"

texts:
I am running truffle test with the following simple test contract, however it seems that it doesn't understand the view modifier.

Contract

pragma solidity ^0.4.18;

contract MetaCoin {
    function getBlockNumber()
    public
    view
    returns (uint)
    {
        return block.number;
    }
}

The output looks like:

$ truffle test
Compiling ./contracts/MetaCoin.sol...
Compiling ./test/TestMetacoin.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...

/contracts/MetaCoin.sol:7:5: ParserError: Expected token LBrace got 'View'
    view
    ^

The view works in Remix, what is missing in my truffle environment that is throwing this error?

The Remix compilation version is (0.4.18+commit.9cf6e910.Emscripten.clang)


texts: How do I specify a lower gas price in the Ethereum Wallet when creating a wallet contract?

texts:
I'm trying out the Ethereum Wallet Dapp (which may or may not also be called Mist, I'm a little confused about the naming. But the About screen says "Ethereum Wallet 0.8.10").

This wallet app seems to be geared towards using a "wallet contract", required to display transaction history. When I try to create one the wallet suggests a gas price which would amount to about $14 (0.02265 ether per million gas, expecting to use 2M gas). That feels like quite a lot for what it is.

Checking http://ethgasstation.info it seems clear that a much lower gas price would work. I'm fine with creation running more slowly.

How do I set a lower gas price in the Ethereum Wallet?


texts:
I am working windows 10 and have both

  truffle.js

&

  truffle-config.js

I am using command

  truffle migrate --reset --networks rinkeby

  Error produced: Unknown network "ganache". See your Truffle
  configuration file for available networks. Truffle v5.0.19 (core:
  5.0.19)

Here's my truffle configuration:

 networks: {

      development: {
        host: "127.0.0.1",
        port: 7545,
        network_id: "5777", // Match any network id
        from: "0x55690752ed06B1d37510D20B3516b2D12F007f6d"
      },

      rinkeby: {
        provider: () => new HDWalletProvider(mnemonic, infura),
        network_id: 4,
        gas: 6700000,
        gasPrice : 10000000000
      }
  },

The configurations are same for both truffle.js & truffle-config.js


texts: Creating a contract that pays out 1 Ether every 1000 blocks until I pay out 10 Ether. What happens if I have less than 9 ether in my account?

texts:
I want to create a contract asset that pays out 1 Ether every 1000 blocks, but only pay out up to 10 Ethers. I want to pay the asset holder. So that means the asset can be transferred to someone else and the contract will be paying to that person.

My questions are:

What happens if I have less than 10 ether's in my account when this contract first runs? Does it still run?
Will the contract run itself when it reaches 1000 blocks each time? Or do you have to run it manually?


texts:
I am using JavaScript to run some tests on my solidity contract. Since solidity ^0.4.22 you can have a message in require such as:

function Hello {
    require(msg.sender == 0x001234, "msg.sender MUST BE 0x001234");
}

When writing tests in javascript I can use the contractName.methods.function to access functions from within the solidity contract. Any idea how I could access the message from require or to implement to test that this message is shown correctly?