texts: How can I verify a secp256r1 signature using solidity

texts:
Sorry if you find these questions are basic, but I am new to encryption. As far as I know, Solidity have ecrecover  function for this purpose, but it use secp256k1 signature. which I am intend to use secp256r1. I used the following steps in this gist to get r,s, an v values.

Then I applied all secp256r1 verification from WIKIpedia as follow

 1. getting r,s, and v values.
 2. verify that r, s are integers in [1,n-1].
 3. calculate the hashing of the message.
 4. calculate w = s^-1 mod n
 5. calculate the curve point (x1,y1) = u1 x G + u2 x Q

Hint: ecadd is adding point function I wrote. ecmul is a multiplication function, isPoint: check if the point is in the curve or not.

My questions are,

1- do I wrote the five steps of the equation correctly; I am not of the 4th and 5th steps. You can check the code of the verification function for further details.

2- if I want to check the verification. I should send a message and a signature. do I need to return more than True/False for verification.

// testing signature function
// getting r, s, and v values from signature.
// steps would be as follows
// 1. getting r,s, and v values.
function ectest(bytes32 hash, bytes sig) returns (bool) {
    bytes32 r;
    bytes32 s;
    uint8 v;

    if (sig.length != 65)
      return (false, 0);

    // The signature format is a compact form of:
    //   {bytes32 r}{bytes32 s}{uint8 v}
    // Compact means, uint8 is not padded to 32 bytes.
assembly {
    r := mload(add(sig, 32))
    s := mload(add(sig, 64))

    // Here we are loading the last 32 bytes. We exploit the fact that
    // 'mload' will pad with zeroes if we overread.
    // There is no 'mload8' to do this, but that would be nicer.
    v := byte(0, mload(add(sig, 96)))

    // Alternative solution:
    // 'byte' is not working due to the Solidity parser, so lets
    // use the second best option, 'and'
    // v := and(mload(add(sig, 65)), 255)
}

// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]

if (v < 27)
  v += 27;

if (v != 27 && v != 28)
    return (false, 0);

// 2. verify that r, s are integers in [1,n-1] using isPoint function
if(isPoint(r,s) == false)
{
  return (false, 0);
}

//3. calculate the hashing of the message
e = sha3(msg);

//4. let v be the leftmost bits of msg
// calculate above in the assembly code
// v

      //5. calculate w = s^-1 mod n
      w  = invmod(s,n);
      // u1 = v * w mod n
      u1 = (v * w) % n ;
      // u2 = r * w mod n
      u2 = (r * w) % n;

      //6. calculate the curve point (x1,y1) = u1 x G + u2 x Q
      (x3,y3)=  ecmul(gx,gy,u1);
      (x4,y4)= ecmul(gx,gy,u2);

      (x1,y1) = ecadd(x3,y3,x4,y4);
      //7. check the validation
      if (r == x1)
      {
        return (true);
      }
    }// end function

}


texts:
I made a setup for a private PoA network with geth. Everything works fine, regarding mining, making transactions, connecting through http and websockets. Now I need to optimize transaction time, I need to make it as fast as possible. As already known, difficulty is one of the most important things which can cause blocks to be mined slowly. They have their very important purpose, but for me is more important to have fast transactions.

Therefore I tried to change difficulty in genesis.json file, but of course difficulty keeps increasing, and mining is slower and slower. I want to make difficulty completely static(not changeable). I already tried:

How to make Ethereum mining difficulty static for a private chain?
How to reduce block difficulty in ethereum private testnet

The thing is that difficulty keeps increasing, much slower but keeps increasing. For me I need a network where there is no delay because of this thing at all.

Any ideas how to solve this problem?


texts: What is the {from: account_one} third parameter in metacoin.js test example

texts:
When working through the MetaCoin sample project; within the MetaCoin.sol file we have this method:

function sendCoin(address receiver, uint amount) returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    Transfer(msg.sender, receiver, amount);
    return true;
}

Inside the test script; when calling the sendCoin method; the code is passing a third parameter: {from: account_one}

return meta.sendCoin(account_two, amount, {from: account_one});

I can understand the code needs to know from what account to send the coin from; but I am not understanding how this is working as the sendCoin method signature has two parameters.


texts: How to convert transaction's inputs to readable values?


texts: web3.js to receive payment from auction or sell

texts:
I would like to receive payments on my contract and be able to withdraw it to my address from my website.

I know how to do basic apps like create a token or transferring a token to an address in the browser,

However I do not know how to create the interaction for the web3.js to launch metamask with the right amount and the right address when clicking the "purchase" button.

I know there is a Open Zeppelin PullPayment.sol, but I do not know how to connect it


texts: Callback error when contract is mined successfully

texts:
I am getting an error today, when tried to mine a contract to ethereum testnet. Even after the transaction is mined successfully (I can check that in the Testnet), the call back is executing the code inside the error.

The callback function in my java script as follows:

function mine_pContract(byteCode, abi, estimatedGas) {
console.log(abi);
var MyContract = web3.eth.contract(JSON.parse(abi));

var myContractReturned = MyContract.new({
    from: web3.eth.accounts[0],
    data: byteCode,
    gas:estimatedGas}, function(err, myContract) {
    if (err) {
        console.log("Error while mining the contract" + err)
    }
    else {
        if (!myContract) {
            console.log("Contract transaction sent. Transaction Hash" + myContract.transactionHash + "waiting to be mined");
        }
        else {
            if (myContract.address === undefined) {
                console.log("still mining. Transaction Hash= " + myContract.transactionHash)
            }
            else {
                console.log("Contract mined. Address" + myContract.address);
            }
        }
    }
  });
}

The output is:
still mining. Transaction Hash= 0x859cbff73bf7da136f1b5402f1d9a7948608d6ef82c9e5f956db3e576fa5d720
main.js:262

Error while mining the contractError: The contract code couldn't be stored, please check your gas amount.

But it was supposed to showthe following message
Contract mined. Address: 0xxxxxxxx.

Any one can point out where is the problem?


texts: Access to a Dapp on a private network from mobile

texts: Is it possible to speak with a Dapp (or with a smart contract) stored on my private network from mobile?


texts: What exactly gets stored when referencing external contracts?

texts:
Imagine two contracts, A and B

contract A{
    ...
}

contract B{
  A a;
  function B(address aAddr){
     a = A(aAddr);
  }
}

What exactly is B storing about contract A? Does it store function hashes? Does it store A's bytecode?


texts: What is the expected behavior of L2 systems under a chainsplit?

texts:
Assuming that there is both a optimistic rollup L2 and a zkrollup L2 system functioning nominally (i.e. they are both publishing their rollups to L1).
Assume that a chain split happens at block 10000 resulting in chain ethA and ethB
Assume that all L2 chains choose chain ethA.
Given that the L2 system is functioning nominally on ethA it should be trivial for users to recover their funds on L1.
How do the users recover their funds on the ethB side of the chain split?


texts:
If one imports another contract and instantiates it with 'new', then I assume the binary of that imported contract must be fully included in my contract (increasing its deployment size accordingly).

If I instantiate the imported contract using an already deployed address however, does that also include that binary data into my contract when I deploy it?

How about if I don't instantiate it at all, but only use a enum or struct definition from that contract. Will the entire binary of the imported contract be added to my contract's binary?


texts:
How can we see transactions in a particular block of Bitcoin, if they are encrypted and only Merkle root of transactions is stored on the blockchain. I think in that way we should be having an immutable ledger with private info protected (since we cannot reverse engineer the Merkle root hash to know the transaction info).
But I've read that blockchain is facing scalability and privacy issues.
Why can't we just encrypt the data in the block and let it be decrypted only with the private key of an individual?


texts: Solidity: How are multiple return values returned?

texts:
Working in truffle with TDD testing and am getting some errors when evaluating the return values of some functions.

If a function is returning multiple values in Solidity, how are they presented? Is it in an array or an object?

    it('can put the star on sale if ownership passes', async function() {
        await this.contract.putOnSale(1,50000, {from: accounts[0]});
        assert.equal(await this.contract.isOnSale(1), {true, 50000});
    });

Errors I am getting are as such:

AssertionError: expected { Object (0, 1, ...) } to equal { Object (identifier, code, ...) }
  + expected - actual

   {
  -  "0": "Barcode"
  -  "1": "1234567890-abcde"
  -  "2": "This is asset #1. There is not much to say about this asset given that it is fictional."
     "code": "1234567890-abcde"
     "description": "This is asset #1. There is not much to say about this asset given that it is fictional."
     "identifier": "Barcode"
   }

Thanks in advance and take care.


texts: How can I know how much a contract deployment will cost?

texts:
I'm trying to deploy a contract into ethereum, but I keep getting "out of gas" error.

How can I know in advance how much ethers I need to deploy a contract?


texts: No Events After Deploying Another Contract in Remix

texts:
I am trying to write an upgradable smart contract in Remix. This involves a Proxy contract, a Logic_0_1_0 contract, and a Logic_0_2_0 contract.

I uploaded Proxy and Logic_0_1_0 only, and the delegatecall in magicFunction worked fine, giving the event of a = 7. However, when I deployed Logic_0_2_0, without even calling updateLogic() in Proxy, the magicFunction stopped giving events. Even after remapping Proxy to point to Logic_0_2_0, I was unable to get any event in the transaction logs at all.

This is my code, across the 3 files.

//proxy.sol
pragma solidity ^0.5.0;

contract Proxy {
    // Sets the position in memory of the logicAddress to a high
    // number. This prevents potential overwriting of memory when
    // using delegatecall on Logic contracts.
    bytes32 private constant logicPosition = keccak256("ucot.logic.address");

    constructor (address logicAddress) public {
        updateLogic(logicAddress);
    }

    //Updates the address
    function updateLogic(address newLogicAddress) public {
        _setLogic(newLogicAddress);
        // (bool ok,) = newLogicAddress.delegatecall(
        //     abi.encodeWithSignature("initialise()"));
        // if (!ok) revert();
    }

    // Sets the logic contract address
    function _setLogic(address _logicAddress) internal {
        bytes32 position = logicPosition;
        assembly {
            sstore(position, _logicAddress)
        }
    }
    // Returns the logic contract address
    function _getLogic() public view returns (address logic) {
        bytes32 position = logicPosition;
        assembly {
            logic := sload(position)
        }
    }

    // Passes on the call of magic function to Logic.
    function magicFunction() public {
        address logicAddress = _getLogic();
        assembly {
            let ptr := mload(0x40)
            calldatacopy(ptr, 0x0, calldatasize)
            let ok := delegatecall(gas, logicAddress, ptr, calldatasize, 0x0, 0)
        }

    }
}

//logic.sol
pragma solidity ^0.5.0;

contract Logic_0_1_0 {

    uint a;

    // Set a to 7, and then emit an event
    event result(uint val);
    function magicFunction() public returns (uint) {
        a = 7;
        emit result(a);
    }
}

//logic2.sol
pragma solidity ^0.5.0;

import "./logic.sol";

contract Logic_0_2_0 is Logic_0_1_0 {

    // Set a to 9, and then emit an event
    // Should overload the previous magicFunction
    function magicFunction() public returns (uint) {
        a = 9;
        emit result(a);
    }
}

And here is a screenshot of the transaction I get in the Remix console

I am still relatively new to smart contract coding, and blockchain in general, so any advice is appreciated.


texts: How to listen to inter-node communications regarding transactions

texts:
If I run a full node (say geth) in the Ethereum network, then the way things work out is that every node releases/ announces new transactions as they receive new ones. I'm assuming that my node must also be receiving a lot of unconfirmed transactions. My objective is to attach an IP address (of the node from which I received the transaction details) to the actual transaction message itself.

How can this be achieved? I'm vaguely aware that ÐΞVp2p is used for communication between nodes, but is it also used for actual transaction detail transmission or just peer discovery? Also, will I have to run my geth client as a miner (to actually make sure that I receive the transaction messages from other nodes in the network).


texts: Track owner and price in Ethereum Pet Shop

texts:
I've been following along with the Ethereum Pet Shop tutorial, and I'm fascinated by how all of this works.

I have a few questions, though.

Before I get into it, here's the code:

pragma solidity ^0.4.17;

contract Adoption {
    Pet[16] pets;

    struct Pet {
        address owner;
        uint256 price;
    }

    function returnEth() public payable {
    msg.sender.transfer(msg.value);
    }
    // Adopting a pet
    function adopt(uint petId) public payable returns (uint) {
        require(petId >= 0 && petId <= 15);
        require(msg.value >= pets[petId]['price'] * 0.5);
        pets[petId] = Pet({owner: msg.sender, price: 100});
        return petId;
        //return value;
    }
    // Retrieving the adopters
    function getAdopters() public view returns (Pet[16]) {
        return pets;
    }

}

I understand that there are 16 total pets, with numeric IDs ranging from 0-15, inclusive. I also understand that only one person is able to "own" a pet at one time.

Is the current owner of a pet immutable? If so, how do I change this property?

Let's say that after a user "buys" a pet, I want to change the price of the pet to .5 * initialPrice, where initalPrice does not currently exist. The remaining balance in eth in the contract is then returned to the first buyer. What would that logic look like?

I assume I'd declare some variable initialPrice somewhere in my contract, such that initialPrice is equal to some arbitrary value in wei, and then add something similar to the following line:

require(msg.value == initialPrice * .5);

How would I then return the remaining eth to the previous owner?

Please let me know if any of this is unclear.

Edit: I've been trying to use the code from the first, answer, but am unable to compile the contract. The error I'm getting is below:

Adoption.sol:19:17: TypeError: Type address is not implicitly convertible to expected type struct Adoption.Pet storage ref.
        pets[petId] = msg.sender;
                      ^--------^


texts: Is it Safe to Share the Wallet Keystore File Without Password?

texts:
There is an ICO that asks for ethereum keystore file, which is unusual for me as far as ICOs go. Even though it does not looks like it contains private key and password it still feels unsettling.
Is it not private, can it be shared safely?


texts: Ethereum Web3 Asynchronous Calls/Promises/Callbacks

texts:
I'm a newcomer to Ethereum, working on a project that requires a certain piece of data from a contract, in order to populate a list in my HTML frontend. However, as you might expect, the calls to the Contracts, not being instantaneous, aren't finishing before the rest of the code is executed, resulting in the relevant values being filled in with UNDEFINED. From the Console, I know that these values come through eventually - it's just that they're out of order. I'm well aware that something like this requires Promises, or Callbacks, or some variant of such, but I am simply having no luck getting any such thing to work, and I'm not sure how they work with Ethereum. I've scoured for tutorials, guides, etc, but I've still not had any joy. I've got a few calls but since they're all pretty much the same (just calling different methods and getting slightly different response variables), I'll just post one:

try{
RegionalContract.areYouInList(codeInput.value, function(error, res){
if(!error) {
var areWeAllowed = res
console.log("Are we allowed to vote? : " + areWeAllowed)
}
});
}catch  (err) {
console.log(err)
}

How would I go about setting up a Promise, et al, to make the page wait until this method had returned? Thanks a bunch.


texts: Public smart contract that calls Private contract API

texts:
In a private blockchain (e.g, quorum), assume that I have a peer X and peer Y. X has a private smart contract (A) and Y has a public smart contract B.

Assume that A provides an API for Y in order to invoke a view function Fa from his private smart contract (Fa takes an address as a parameter and return true if the address exists is a table internal to the private smart contract (A)).

Assume that Y invokes a function Fb from his public smart contract that calls the provided API to get the returned value (true or false) for a given address.

I want to know if such a scenario is possible and if possible the details of how such a transaction is made (transaction lifecycle and how and when the function Fa is invoked)


texts: How to make Meteor + Geth working together?

texts:
I want to integrate a server side web server with a blockchain as a distributed database.
What patterns are available to do so?


texts: How to have a client be agnostic in cluster nodes?

texts:
I have been wondering for some time how to handle the situation where the client application of Ethereum blockchain can remain connected when the nodes he connects to via API is down for maintenance.

Say I have 2 or 3 local nodes in my infrastructure and I need to maintain one of them (upgrade to new version, reboot the host ...). If my client app is connected to it, its connection will be lost.


texts:
I have the following:

pragma solidity ^0.4.0;
contract MyContract {

struct FooFighter {
    bool foo;
    uint fighters;
}
mapping(bytes32 => FooFighter) public fooFighters;

If i want the initial value of uint fighters to be a predefined number instead of 0 for all fooFighters. how would i do that?


texts: ENS: Guessing bids amounts and protecting bid anonymity

texts:
Regarding adding ETH for extra anonymity on an ENS bid, @Arachnid said:

  Disguising the exact amount makes it more difficult for people who have guessed what name you are bidding on to also guess how much you're bidding.

How would one go about guessing the bid amount given the .eth name?

How does addding extra "protection money" make that process harder?

Is the difficulty correlated to the amount of extra ETH added? Or is using a random amount better?


texts: Is there something like bitcore for Ethereum?

texts: In Bitcoin there is a library named Bitcore.  It helps abstract away a number of details, including using direct RPC commands.  Is there something like Bitcore for Ethereum?  Or do I need to use JSON-RPC?


texts: Modify the state using returned variable (Array.push)

texts:
In my contact I want to have one place where I find an existing object(struct) and then use it in multiple places to read and modify it - but seems like it's not possible?

contract A
{
    struct Prop
    {
    }

    struct App
    {
        Prop[] props;
    }

    App[] apps;

    function AddProp(string memory name) public
    {
        App memory a = FindApp(name);

        if(bytes(a.name).length > 0)
            a.props.push(Prop()); // TypeError: Data location must be "memory" for return parameter in function, but "storage" was given.

        else
            revert('Application not found');
    }

    function FindApp(string memory name) public returns (App memory) // can't return 'storage'
    {
        for(uint256 i = 0; i < apps.length; i++)
        {
            if(apps[i].name == name)
            {
                return apps[i];
            }
        }

        return App();
    }

}


texts: What was the first coin to offer "reflex" and auto-adding liquidity?

texts:
Who was first?
I see these features being forked on a massive scale.
I would like to know who was first and where to find GitHub repo (ideally with tests) so I can play with it.
SafeMoon
SafeMoon maybe? Massively successful...

https://safemoon.net/
https://bscscan.com/address/0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3#code

Pangea
I see these features being recreated in other places:

https://pangeamovement.com/pages/pangea-coin
https://www.bscscan.com/address/0x123f92226c626adc919ad122d6cc3c20a6c25666#code


texts:
I have read EIP-1967 and i have study how work proxy contracts.
There is something i do not understand in EIP-1967.
Here is what i have understood:

Logic contract's storage variables are stored in proxy contract's memory.
Proxy contract contains his own storage variables
We can have a big problem if a logic contract variable has the same address than a proxy contract variable address.
For this reason, proxy contract variables are stored at 3 specific addresses (we have only 3 storage variables in proxy contract)
The goal of this EIP is to specify 3 addresses and to say to all compilers and EVM they should NEVER store a variable at this addresses.

In my opinion, people who wrote this EIP can choose any address. The important thing is that everyone agrees with this address choice (compilers, evm, ...). They choose this Addresses:

0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
(obtained as
bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1))
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50
(obtained as bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1))
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103
(obtained as bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1))

That's fine but i am wondering something: Why did they put a -1 in the address calcuation ?
The EIP says:

Furthermore, a -1 offset is added so the preimage of the hash cannot
be known, further reducing the chances of a possible attack

I do not understand how this -1 offset can reduce any chance of possible attack... The hash is known by everybody. Can anyone explain which kind of attack is protected by this -1 ?
I have looked at an openzepplin implementation (TransparentUpgradeableProxy.sol) and here is what i saw:
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

constructor(...)
{
     assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
     ...
}

My question is: How this assertion can be false ? What is the goal of this assertion in the constructor ?
Thanks a lot


texts: I've been mining with my several GPUs on https://ethermine.org and while doing a research on how to increase mining efficiency, I've found ethproxy project on GitHub (https://github.com/Atrides/eth-proxy) which boast an increase of 20% of hashrate. Could someone please explain what ethproxy is/does and if it is still a thing because project is abandoned since 2016. Was its functionality replaced by Stratum V2? As I understand, while mining in a pool, my GPUs mine independent of each other, while proxy allows them to work in tandem on a chunk of calculations? Sorry, still learning the ropes and obviously have a basic understanding about mining.


texts: How to parse internal transactions in order to find the transactions values

texts:
I would like to parse the transactions with the following transaction hash:

0xcad1183ecf7f278713858d92c06f00934f79a75eb5c852352a3ac35de07e151c

More specifically, I'm interested to find out that 5 + 1 Ether have been transferred.

Following information are given in the blockchain:

As you can see, it is not hard to find out that 5 Ether has been transferred. However, in order to calculate 1 Ether, 5 - 4 needs to be subtracted. Where can I find those rules and how can I generalise this to find all internal transactions?


texts: Ledger Nano S Google Ether wallet does not recognize device

texts:
I want to connect my Ledger Nano S to the Chrome Ethereum Wallet App, but it is unrecognized.

I setup a Ledger Nano S with Pin and Passphrase.
I downloaded the Chrome Bitcoin, Ethereum, and Manager apps.
First I opened the Chrome App Ethereum Wallet.
I connected the device; entered the PIN; navigated to Ethereum icon; and selected it by pushing both button simultaneously.
The Chrome Ethereum wallet still says, "Connect your device."

I read on the ledger site that the firmware needs to be up-to-date. I checked my firmware version it is 1.3.1.  I opened the Ledger Manager app, and noticed that the latest version of the Ethereum app is 1.0.17. The version currently installed on the Nano S is 1.0.8.

I tried to install the latest version of Ethereum app on my device.  I get an "Unable to install application" error.

So I tried to uninstall the current version by clicking the trash can icon.  I get an "Unable to remove application" error.

FYI The Chrome Bitcoin App seems to work just fine.

I contacted technical support, but it says the wait could be 24-48 hours...


texts:
What is the difference between Casper and Algorand?

Casper -- Proof of Stake-Based Finality System overlaying an existing proof of work blockchain

Algorand -- Byzantine Consensus Based Protocol and?


texts: Is it possible to get the current transaction's transactionIndex from within a Solidity function call?

texts: Is it somehow possible to get the current transaction's index in the block from within Solidity? or to derive this in some indirect way?


texts: Member X is not available in struct Y memory outside of storage

texts:
I've been coding in solidity and got this error "Member "betsOnBitcoinGoesUp" is not available in struct BetOnBitcoinNew.BettingObject memory outside of storage." What does this mean?

The function that produced error looks like this.

function getUserBetsfromBettingObject(uint index, address callerAddress) constant returns (uint) {
BettingObject memory currentBettingObject = arrayOfBettingObjects[index];
if (currentBettingObject.currentState == GameState.bitcoinUpWon) {
  return currentBettingObject.betsOnBitcoinGoesUp[callerAddress];
} else if (currentBettingObject.currentState == GameState.bitcoinDownWon) {
  return currentBettingObject.betsOnBitcoinGoesDown[callerAddress];
} else {
  return 0;
}

}


texts: Setting array.length to 0 triggers an error on solidity 0.5.0

texts:
Why setting array.length to 0 triggers an error ?

I have a function that deletes an element from a dynamic array of structs within a mapping as follows:

mapping(address => MyStruct[]) public structs;

My problem is that if I try to set the length to 0 it triggers this error: VM Exception while processing transaction: invalid opcode

structs[_user].length = 0; // will trigger an error !

But:
structs[_user].length = 1; will work fine.

It is inside a function like this one:

function _burn(uint index) internal {

  require(index < array.length);

  array[index] = array[array.length-1];
  delete array[array.length-1];

  // when array.length is set to 0 it doesn't work:

  array.length = array.length - 1; // doesn't work if array.length = 1

  array.length = 0;  // doesn't work

  // when array.length is set to a value > 0 it works:

  array.length = 1;  // works

  array.length = 2; //  works

}

I tried at least for 45 hours without findnig any idea why it happens! If you have encontered this issue or know how to handle it, help would be really appreciated.

P.S: I am using solidity 0.5.2

Here is the whole code:

// ----  Redeem a Stake ------  //

function stakeclmidx (uint _stakeidx) public {
require(_stakeidx >= 0);

Stake storage _stake = stakes[msg.sender][_stakeidx];

// See if the stake is over
require(block.number > _stake.endBlock);

require(_stake.amount > 0);

// transfer back token from contract to staker:
balances[address(this)] = balances[address(this)].sub(_stake.amount);

balances[msg.sender] = balances[msg.sender].add(_stake.amount);

emit Transfer(address(this), msg.sender, _stake.amount);
emit StakeClaimed(_stakeidx);

// deletes the stake
_deletestake(msg.sender, _stakeidx);

}

function _deletestake(address _staker,uint _index) internal {
require(_index < stakes[_staker].length);
stakes[_staker][_index] = stakes[_staker][stakes[_staker].length-1];
delete stakes[_staker][stakes[_staker].length-1];
stakes[_staker].length = stakes[_staker].length - 1;
// this last line is the one triggering the error
// it seems it triggers the error only when length value is set to 0
// stakes[_staker].length = 1; works !
// stakes[_staker].length = 2; works !
// stakes[_staker].length = 0; doesn't work !
}
// ----  Redeem a Stake ------  //

Best Regards


texts: Testnet chaindata folder size huge (26.9 GBs)

texts:
How come my testnet chaindata folder is so big?
I'm running Ethereum Wallet 0.8.7. Deploying little test smart contracts.
Actual chaindata size is 9.4 GBs.


texts:
I need ether to make transactions. Actually I'm working on the testnet Ropsten network then it's easy to get ether with a miner. But if I mine blocks on the main network this will take more than one year to get just one ether. And I see we can buy ether.

I want to know if it's worth it to buy ether ? What is the best way to get some ether to use ethereum in production ?

Thanks for your suggestions.


texts: How to change Geth PoA Clique block sealing time?

texts: I have used puppeth to generate genesis file in which I set sealing time to 30 seconds. I have set up one miner. Now, I want to change the sealing time to 5 seconds. How can I do that on same blockchain? I am using geth as my node.


texts: Truffle migrations error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent

texts:
My env

Truffle v5.3.1 (core: 5.3.1)
Solidity - ^0.8.0 (solc-js)
Node v15.11.0
infura (Rinkeby test network)
Rinkeby Test wallet has 21 ether

my truffle-config file
const HDWalletProvider = require('@truffle/hdwallet-provider');
require('dotenv').config();
const mnemonic = process.env["MNEMONIC"];

module.exports = {
 networks:{
        rinkeby: {
         provider: () => new HDWalletProvider(mnemonic, `wss://rinkeby.infura.io/ws/v3/APIKEY`,0,1 ),
         network_id: 4, //rinkeby
         skipDryRun: true,
         gas: 8500000,
    },
 }
}

I run
truffle migrate --network rinkeby --reset

It takes forever for the migrations to take place, runs through 50 blocks before it stops and throws an error.

Error:  *** Deployment Failed ***

"Migrations" -- Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!.

Could this be a gas issue or is something possibly not connecting right like my wallet? Infura shows me all the API calls it's getting too.


texts: How to write a smart contract for RPi sensor?

texts:
I have a PC with two nodes running on it, and a Raspberry Pi which also has Geth running. Problem is how to write a smart contract so that sensor to send the measurements to the blockchain periodically, and also is it possible to access this chain from anywhere, given that I know the private key of the account?

Thank you


texts: Contract deployment won't confirm in mist wallet

texts:
I'm trying to deploy a contract on the mainnet, and I'm using Solidity 0.4.24

I can only deploy the contract as byte code because I can't figure out how to upgrade the solidity compiler in mist (the question is not about that).

Deploying the contract as byte code works fine on Ropsten. However, on the mainnet I tried at least 20 times and I always get 0 confirmations. I even increased the FEE slider to the maximum.

My question:

Does the mainnet not yet accept this version of solidity?
Do I have to increase the fee even more?
Is it because I'm deploying it as byte code directly?


texts: If you want to simulate repsonse time of your smart contract, how realisitc is it to use ganache? I'm thinking that in a live network, ropsten for example, there would be a lot more transactions waiting in the pool compared to the ganache simulated blockchain, which would only contain my transactions. Is it realistic enough by just increasing block time? Especially when measuring the response time from multiple transactions from multiple addresses


texts: What method can I use instead of delegatecall?

texts:
I see the warning security/no-low-level-calls: Avoid using low-level function 'delegatecall' when I use delegatecall function in my code.

I understand why it's not a good way, but I still need that functionality.

What method can I use instead of delegatecall when I need to keep my context and use storage in the called contract? Is there a safer way for this?


texts:
address[] twitteruser;

function twitterhandles(address _address,string _twitterhandle)  public  {

    for(uint i=0;i<=twitteruser.length;i++){

        if(twitteruser[i] ==_address)
        throw;
    }

    handles[_address].twitterhandle = _twitterhandle;
    twitteruser.push(_address);
}

Why is the output is getting thrown? Any help is appreciated. Thanks in advance.


texts: Integrate more then one user with one ethereum account

texts: I have many users inside the organization and I want to use same ethereum account for all the users , but with different usernames, so it there anyway to do that ?


texts: Do I have to create a custom ERC20 to test transfers in Truffle?

texts: I have a smart contract that escrows and transfers a specific ERC20 token to and from users (with their approval). I'm a bit confused as to how to test transfers of existing tokens. Do I have to copy+paste the token contract into a dummy contract, migrate it, and use the deployed address in my contract? Or is there another feature of Truffle migrations and tests that I'm missing?


texts: Sent ETC to ETH and need to know how to recover please!

texts:
I traded ETC from project.github.io/etherwallet to ETH at BTC-e and didn't realise the difference in blockchains.

How can I access this? I did this in June.
All help appreciated.
I have the API keys in WEX.
Thanks.


texts:
I don't know much about GAS usage in contracts, so I'm bothered with a question: Is it ok to store all tokens and owners in the contract storage?
contract Token
{
    // ... token code ...
}

contract TokenCreator
{
    Token token;
    mapping (address => address) token_owner;
    address [] tokens;

    constructor ()
    {
        token = new Token();
        token_owner[address(token)] = msg.sender;
        tokens.push(address(token));
    }

    // ... code ...
}

What if I have 10 Bil tokens in my system? i mean, this way, is one operation with my TokenCreator gonna cost me thousands of dollars since it requires a tons of GAS to handle those HUGE "mapping token_owner" and "tokens []" which are storing all the 10 Bil addresses?


texts: Assert and require response error message

texts:
I have one sentence in my code that is evaluating a condition. If the evaluation fail´s I throw a execption with assert and require. In my case I think that require is the indicated election for a boolean condition.

The exception is collected but testing between assert anf require the EVM return me two cain of message.

My problem is that I cant understand why return me this message.

It´s some mechanism to return a simple string with a error message?

**Assert response

**Require response


texts: Is there a quicker way than geth --fast to download the Ethereum blockchain?

texts: I had the Mist client installed, but it hadn't been updated in a few weeks so I tried renaming the chaindata folder (instead of deleting it) and downloading the blockchain with geth --fast as that is supposedly faster. I started the download about three days ago, on a capped internet connection that is very slow, and now I still only have 188 MB of data in the chaindata folder. Is there another, faster way to download the blockchain? Should I just restore the Mist chaindata folder and try syncing via the Mist Client, since I already had a large part of the blockchain?


texts: Security review checklist for a smart contract

texts:
Is there a tool, checklist of methodology to help reviewing smart contract security?

E.g. for each of function you review

Is there re-entry possibility and how it behaves on re-entry
How it behaves if loops run out of gas
How it behaves if stack limit is reaches

... and so on.

If no such tool is available is there a good source or list for all known failure modes of Ethereum smart contract security?


texts:
Some time ago, me and a friend created a Ethereum Wallet and purchased some ETH. We created the wallet on my Computer but because of some issues, I needed to reinstall windows. I thought I copied all of the Ethereum files for a backup but I think I missed some.
Can I recreate my wallet and if so, what do I have to do for this?
I hope someone can help me.
Greetings


texts: I am working with a kovan validator set for a POA network. When I try to add validator, I make the Initiate Change call and it goes through. Validator goes to pending state. When I make the Finalize Change call, it is stuck in pending. Does any one know what I am doing wrong


texts: Is there a way to get the logs for all transactions in a block?

texts:
I am building a system that monitors ERC20 token deposits to a large number of ethereum addresses (1-4 million). While I have not tried, I do not think that the parity clients would be able to support such a large amount of filters. I intend to build a customised data structure in order to achieve this task. Therefore, I would like to acquire the logs of all transactions in a block. Is there a way to do so?

This question is related to How to programmatically detect and accept ETH and ERC20 deposits

However, answers to the above post have not adequately addressed my concern about scalability.

What I have tried:

I am currently scanning the whole block for transaction hashes and then using eth_getTransactionReceipt to acquire the logs for each transaction. The pseudocode is as follows:

@parallel
for block in all blocks:
  all_tx = get_all_txs(block);
  for tx in all_tx:
    save_in_db(eth_getTransactionReceipt(tx).getlogs())

I am wondering if there is a better way to retrieve the logs, perhaps retrieving all logs at once?


texts: Interacting with a complex deployed contract from my other contract

texts:
For example, I want to call a create market function from augur in my contract. I'm using the recommended pattern, but there are additional contracts that this function brings in, ex ICash, IMarket and afterInitialized modifier.

Is there a simpler way besides importing every single dependent contract?

pragma solidity ^0.4.25;

contract Augur {
     function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public afterInitialized payable returns (IMarket _newMarket);
}

contract AugurWrapper {
    Augur universe;
    constructor(address _address) public {
        universe = Augur(_address);
    }
    function myCreateMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public {
        return universe.createYesNoMarket(_endTime,_feePerEthInWei,_denominationToken,_designatedReporterAddress, _topic, _description, _extraInfo);
    }
}


texts: Testing requestRandomness with a unit testing plugin by Remix

texts:
when I test rollDice which executes requestRandomness
function rollDice(uint256 userProvidedSeed, address roller) public onlyOwner returns (bytes32) {
    require(wagered.get(roller) > 0, "Need money to make money yo!");
    require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK to pay fee");
    bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
    rollers.set(requestId, roller);
    assert(rollers.get(requestId) == roller);
    emit DiceRolled(requestId, roller);
    return requestId;
}

Test Case
/// #sender: account-0
function play() public {
    game.rollDice(45, acc2);
}

I get this????
"Transaction has been reverted by the EVM: { "transactionHash": "0xbcfea3fd3d45efca90b9b7a73de47ccd105c872a297deb5a849b4f622384f20e", "transactionIndex": 0, "blockHash": "0x935d9441827fc1dddb34db8591a7d4ceb456826913458c8808850696acd2230c", "blockNumber": 120, "gasUsed": 5000000, "cumulativeGasUsed": 5000000, "status": false, "to": "0x703879Ca741c310b92A39D72B34C6D73D13420E0", "events": {} }"


texts:
Im trying to send a raw transaction using web3 to ropsten testnet and Im getting this error:

  replacement transaction underpriced

where sometimes my tx works and sometimes I get this error.

my tx parameters:

const nonce = web3.eth.getTransactionCount(ethereumConfig.contract.account)
const block = web3.eth.getBlock("latest")
const gasLimit = block.gasLimit
const gasPrice = web3.eth.gasPrice.toNumber() * 1.40

note I'm already adding 40% to gasPrice


texts: how does DAG affect the NONCE finding？what about fix the DAG size to 1G？


texts: What is the easiest way to convert mnemonic phrase into keystore file?

texts:
I have an account created with Metamask - there is 12 words backup phrase.

I'd like to import that account into Ethereum Wallet.

I believe that in order to do so, I need to put a keystore file into a special directory.

What is the easier / most convenient way to convert 12 words mnemonic phrase into keystore?

Some Google search: https://www.reddit.com/r/ethereum/comments/5zzwh0/can_mnemonics_currently_be_used_to_create_a_utf/

It would be nice to have a crypto test suite allowing guys like me to experiment / better understand / play with the keys.

Related: Export Metamask account to JSON file


texts: Warning on Finalizable Crowdsale of OpenZeppelin

texts:
I'm trying to create a crowdsale contract based on OpenZeppeline. The complete code can be found here. However, in remix, it's throwing the following warning:

browser/crowdsale.sol:262:3: Warning: Function state mutability can be restricted to pure
  function finalization() internal {
  ^
Spanning multiple lines.

The code that's creating the problem here is:

function finalization() internal {}

Can anyone suggest what is wrong here and how I can rewrite this finalization code so that there is no warning?


texts:
I'm new to smart contracts and still learning some solidity basics. The contract I created, should give the sender custom tokens for Ether.
I have trouble in calculating tokens and also decrease the token amount.

Here are my initial values

   uint8 public constant decimals = 18;
   uint256 _totalSupply = 1000000;
   uint128 constant RATE = 2;

For example, if I pay 1 ETH I should get 2 Tokens.

For some reason, it doesn't work here properly:

When I pay 1 Ether to this contract, I'm getting 2000 tokens but instead, it should be 2 tokens

uint256 tokens = msg.value * RATE;

Here is also something weird, I'm getting this value for balances[owner] and _totalSupply
115792089237316195423570985008687907853269984665640564039455.584

balances[owner] = balances[owner] - tokens;
_totalSupply = _totalSupply - tokens;

here the function:

 function createTokens() payable
 {
    require(msg.value > 0);

    uint256 tokens = msg.value * RATE;
    balances[msg.sender] = balances[msg.sender] + tokens; //add tokens to senders balance
    balances[owner] = balances[owner] - tokens;           //subtract tokens from owners balance

    owner.transfer(msg.value);                            // transfer amount of ether to cotract owner
    Transfer(owner, msg.sender, tokens);                  // Broadcast a message to the blockchain

   _totalSupply = _totalSupply - tokens ;
 }


texts: Can I redeploy a previous self-destructed smart contract?

texts: If I deploy a smart contract, and then self destruct it. Then later send it ether by mistake, can I re-deploy it and be able to access that "lost" ether through the smart contract?


texts:
In windows 10 I tried to go mod tidy for installing go_etherum but got this error:
go: finding module for package github.com/ethereum/collector
github.com/ethereum/go-ethereum/cmd/pluginManage imports
github.com/ethereum/collector: cannot find module providing package github.com/ethereum/collector: module github.com/ethereum/collector: git ls-remote -q origin in C:\Users\maryam\go\bin\pkg\mod\cache\vcs\b319a38dd5543ac682edf2661e5569419b8e6c1f7cec452b0d3f052adf6d4efe: exit status 128:
remote: Repository not found.
fatal: repository 'https://github.com/ethereum/collector/' not found
Can anyone help? What is the problem


texts: Why is solidity throwing "Note: The constructor should be payable if you send value. ", when clearly the issue is elsewhere?

texts:
I'm writing a contract on Remix that is able to deploy and track child contracts.

Here are the 2 contracts:

pragma solidity ^0.5.0;

Contract Factory

contract ContractFactory{
    ChildContract[] public createdContracts;
    ChildContract public activeChild;

    function createChild() public{
        ChildContract newChild = new ChildContract();
        createdContracts.push(newChild);
        // if (address(activeChild) != address(0)){
            activeChild.activate(false);
        // }
        activeChild = newChild;
    }
}

Child Contract

contract ChildContract{
    bool isActive;

    constructor() public{
        isActive = true;
    }

    function activate(bool status) public{
        isActive = status;
    }
}

I deployed the ContractFactory and it was successful. Then I tried calling the createChild function. Then I got the following error:

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

As evident from the code, if I un-comment the commented out if condition inside the createChild function, the function will run without issues. My question is - Why is solidity throwing this misleading error, as the issue was with an unset variable?


texts: When creating an account with the Mist wallet, is the password a key for encrypting my wallet file or is it for something else?

texts:
In the book "Introducing Ethereum and Solidity", there is a paragraph that says:

  "There is no Forgot Password functionality in the Ethereum network. That’s
  because your password is only for this local instance of the Mist wallet; it’s not saved on
  the Ethereum blockchain. In fact, your private key is all you need to re-create this account
  on any other computer running Mist. The password you create merely protects you from
  an interloper sitting down at your computer and spending your money through the Mist
  interface. It does not stop anyone from stealing your private keys from your computer’s file
  system, if it’s left unprotected."

Does this mean that Mist doesn't encrypt my wallet file/private keys?


texts: Custom token transfer, what am I doing wrong?

texts:
I am trying to hash an address then send tokens to a mapping of the hash in the token contract, then be able to withdraw those tokens using a hash of the address. It compiles but cannot make it work. What am I doing wrong?

Also I don't think I need the 'payable', and not sure what to put after 'dreceive' as this function shouldn't need any input.

contract BasicToken is ERC20Basic {
  using SafeMath for uint256;
  bytes32 hashed;

  mapping(address => uint256) balances;
  mapping(bytes32 => uint256) dks;

  function transfer(address _to, uint256 _value) returns (bool) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

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

  function dsend(address _sendto, uint256 _amount) payable returns (bool) {
    hashed = keccak256(_sendto);
    balances[msg.sender] = balances[msg.sender].sub(_amount);
    dks[hashed] = dks[hashed].add(_amount);
    Dtransfer(msg.sender, _amount);
    return true;
  }

  function dreceive(amount) payable returns (bool) {
    hashed = keccak256(msg.sender);
    dks[hashed] = dks[hashed].sub(amount);
    balances[msg.sender] = balances[msg.sender].add(amount);
    Drec(this, amount);
    return true;
  }

}


texts: How can I view all the tokens and contracts associated with an ethereum address in Javascript using Web3.js?

texts:
Is there an example js code that uses web3.js to query the Ethereum blockchain to see all the tokens and contracts associated with an Ethereum address? I'm looking to make an ethereum wallet and want to know how to pull in this data.

How do I connect to a public ethereum node to make this query?
Which web3.js functions are required to pull in what tokens an address holds?
Contracts associated with and address?


texts: Filter Pancakeswap transactions in block using Web3

texts: With the web.eth.getblock i'm able to get all the transactions off a given block. Is it possible set a filter that shows only pancakeswap transactions?


texts:
Before Parity I used Geth, and made requests like:

echo '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", false],"id":1}' | nc -NU geth.ipc

and It worked!
In Parity v2.7.2 and Ubuntu 18.06 i tried to do it in the same way:

echo '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", false],"id":1}' | nc -NU jsonrpc.ipc

But has no stdout. I tried several methods, but no one was success.
in config.toml I has this:

[ipc]
disable = false
path = "$HOME/.local/share/io.parity.ethereum/jsonrpc.ipc"
apis = ["web3", "eth", "pubsub", "net", "parity", "parity_pubsub", "parity_accounts", "traces", "rpc", "shh", "shh_pubsub"]

Why I have silent stdout?


texts: Can you add input data with a token transfer?

texts: I was successfully able to send eth with some message here: 0x4ea3d0ae060aeb08f41fb8ff3e468b7e44092a251ccef118b386136fe6427a64 (little tackier though). I did this from MEW, but saw that it is not possible to send input data with a token transfer. I know the token transfer has instructions for the token smart contract in the same input data field. So does that mean we cannot send a message (input data) with a token transfer and it is only possible on ETH transfer? Not familiar enough with web3 to figure this out on my own. Really appreciate if anyone can share their know-how


texts: Different address with single mnemonic phrase

texts:
I'm trying to implement ethereumjs-wallet library to my code.
But when I decided to compare generated accounts with accounts generated with the same mnemonic here, I got absolutely different accounts, even when seed was identical to mine. What am I missing?

I do it like this:

Web3 = require('web3');
bip39 = require('bip39')
etherHDkey = require('ethereumjs-wallet/hdkey')
ethUtil = require('ethereumjs-util')

mnemonic = bip39.generateMnemonic()
seedHex = bip39.mnemonicToSeedHex(mnemonic)
HDwallet = etherHDkey.fromMasterSeed(seedHex)
zeroWallet = HDwallet.derivePath("m/44'/60'/0'/0/0").getWallet();
console.log(mnemonic)
console.log(seedHex)
console.log(`Address: ${zeroWallet.getAddressString()}`);
console.log(`Private Key: ${zeroWallet.getPrivateKeyString()}`);

And here is the output:

slogan east ugly dish enable remove economy faint senior pause mention where
db90f73b1f23d449b021739c6c3aa85e47e8e26aa95b1ff6e883773536e6b126e15c34876070bd37befead1fc74057dfce2c6b045e8d4de6146584c96940486f
Address: 0xf298302699395cb4472b74e41427733c0ce6bcff
Private Key: 0x5b1b539ca7edd8e78f2c33fc6d9f1ef0d35db3490de9ed04f92c20bde54fbf48

Then when I insert this mnemonic slogan east ugly dish enable remove economy faint senior pause mention where to corresponding field here, I get the same seed BUT absolutely different addresses.

e.g. I get 0x7C373bAD5cF89b5c2730486eF2c1b8E803eD11d5 from m/44'/60'/0'/0/0' instead of expected 0xf298302699395cb4472b74e41427733c0ce6bcff using the same path m/44'/60'/0'/0/0'

What could be wrong here? Thank you.


texts: How were gas costs chosen for the Ethereum Virtual Machine instructions?

texts:
Different instructions of the EVM have different associated gas costs -- you can look at the list of the gas-prices in the appendix G of the yellow paper.

While the rough magnitudes of those numbers look quite reasonable, the exact values still look like they were chosen somewhat arbitrarily. On the other hand some values look strangely specific.  Is there any deeper reason for choosing those exact values?


texts: must be a lvalue, what's this error mean, precisely?

texts:
I am writing a few contracts and I'm all good to go until I migrate and hit this bump in the road, it has tormented me for 3 days I can't seem to figure out the issue I am thinking it is a camel case but I change it and try to fix the more I mess the code up, can anyone indicate to me what to do to correct this error in my contract I will post it attached to here. the error reads as follows "the type error: Type contract MOOREToken is not implicitly convertible to expected type (contract MOOREToken).
lvalue`
       ``` MOOREToken = _MOOREToken;
       ^--------^
,/C/Users/Noahm/Lastchance3/src/contracts/TokenFarm.sol:18:22: TypeError: Type contract MOOREToken is not implicitly convertible to expected type type(contract MOOREToken).
        MOOREToken = _MOOREToken;
                     ^---------^
,/C/Users/Noahm/Lastchance3/src/contracts/TokenFarm.sol:71:17: TypeError: Member "transfer" not found or not visible after argument-dependent lookup in type(contract MOOREToken).
                MOOREToken.transfer(recipient, balance);
                ^-----------------^

    fixed and now my error is this:
    truffle(development)> truffle migrate

    Compiling your contracts...
    ===========================
    > Compiling .\src\contracts\DaiToken.sol
    > Compiling .\src\contracts\MOOREToken.sol
    > Compiling .\src\contracts\Migrations.sol
    > Compiling .\src\contracts\TokenFarm.sol
    > Compiling .\src\contracts\DaiToken.sol
    > Compiling .\src\contracts\MOOREToken.sol

    /C/Users/Nmlm99/MOORETokenFarm/src/contracts/TokenFarm.sol:9:5: DeclarationError: Identifier not found or not unique.
        ERC20 public MOOREToken;
        ^---^
    ,/C/Users/Nmlm99/MOORETokenFarm/src/contracts/TokenFarm.sol:10:5: DeclarationError: Identifier not found or not unique.
        ERC20 public daiToken;
        ^---^


texts: If you are a miner can you accept your own transactions at no cost?

texts:
Let us say I am a miner. Can I accept my transactions into the blockchain at no fee to myself? And what do I lose?
Let us assume someone is running a dapp. Can they mine transactions of that dapp to make them free? Are there any dangers of doing so?


texts: Ganache stuck when loading truffle project

texts:
I am not sure what can be wrong. When I try to load a truffle project (by adding the truffle-config.js file to the workspace config), ganache gets stuck at the loading icon and I get this lines at the terminal:
 ./ganache-2.4.0-linux-x86_64.AppImage
17:59:30.635 › Checking for update
listen to truffle
17:59:42.911 › Update for version 2.4.0 is not available (latest version: 2.4.0, downgrade is disallowed).

If I go for the "quickstart" it works correctly. Also, if I create a new workspace but don't add a truffle config file it works correctly as well. What can be wrong? The truffle-config.js is created automatically when running truffle init.


texts: Metamask not returning current account address with web3js and ganache

texts:
How to return the address of my current account from Metamask? I have tried with web3.eth.getCoinbase() but this and metamask has two different address.

web3.eth.getCoinbase() returns me the first account from the list of accounts provided by Ganache.

What I need to do to resolve this?

Thanks

P.S.:

I am following the tutorial from here and 2019 updated Github code is here.

The below code is the problem:

web3.eth.getCoinbase(function(err, account) {
      if (err === null) {
        App.account = account;
        $("#accountAddress").html("Your Account: " + account);
      }
    });

It returns null even if I have address of my account in metamask and yes I have imported an account given by Ganache onto Metamask.


texts: What are the parameters for the approveAndCall function in tokens?

texts:
Can somebody please explain what the paramters are in the function approveAndCall that is used in some ERC-20 tokens?

function approveAndCall(address spender, uint tokens, bytes32 data) public returns (bool success) {
    allowed[msg.sender][spender] = tokens;
    emit Approval(msg.sender, spender, tokens);
    ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
    return true;
}


texts: Tracking contracts and transactions associated with an account address

texts:
The base set up is a geth based private test-net and a mist wallet is interfacing the node on a local host machine. A few contracts have been deployed through the wallet from 2 different accounts on the same node. I am trying to build a tracker that tracks contracts deployed and associated with contracts of which an account has transacted with in either-direction (from/to). The objective is to build a webpage with the following tabulated lists:
a. List of accounts and the corresponding contract tokens deployed from the accounts on the node. This can be obtained since the node has the contract ABI and the contract address and accordingly, the contract details (attributes).
b. List of contracts associated with an account - contract tokens that are incoming/outgoing from the account on the node
Questions:
 1. Within Mist, upon interacting with the contract which has a transfer of tokens native to the contract to another account on the node, I am able to get the remaining tokens balance. At this point, at either of the account views, Mist is able to retrieve the contract name and address at the second account's view. How to track contracts and retrieve address and ABI of the contract in case above second account was at a different node, using API?
 2. With ref to list b, above, how to get the list of all contracts - ABI and addresses and associated accounts?
 3. The contract has event filters to track for transactions, some of which transactions have been made several days ago from either of the accounts on the node. These exist on the Mist wallet - is it possible to retrieve past transactions using the API? Is there a way to filter the blocks which contain transactions and those associated with contract tokens?


texts:
I am working with Truffle on a payroll smart contract that handles payments, employee addresses, etc. Right now my structure looks something like this:

Payroll.sol

pragma solidity ^0.4.19;

import './InterfacePayroll.sol';
import './EmployeeStorage.sol';
import './Token.sol';

contract Payroll is InterfacePayroll, Ownable {
using SafeMath for uint256;

//set employeeStorage to inherit methods of InterfaceEmployeeStorage
InterfaceEmployeeStorage public employeeStorage;

//set employeeToken to Token
Token public employeeToken;

//=======Modifiers
modifier validAddress(address _address){
    require (_address != 0x0);
    _;
}

modifier higherThanZero(uint256 _uint){
    require(_uint > 0);
    _;
}

//=======Initialize
//contructor initializes an instance of EmployeeStorage
//Gas limit has to be raised manually
//TODO set gas limit internally
function Payroll() public{
    setEmployeeStorage(new EmployeeStorage());
    setEmployeeToken(new Token());
}

//set employeeStorage to contract EmployeeStorage
function setEmployeeStorage(address _newEmployeeStorage)
internal
onlyOwner validAddress(_newEmployeeStorage){
    employeeStorage = InterfaceEmployeeStorage(_newEmployeeStorage);
}

//set employeeToken to Token contract
function setEmployeeToken(address _newEmployeetoken)
internal
onlyOwner validAddress(_newEmployeetoken){
    employeeToken = Token(_newEmployeetoken);
}

//Accept ETH payments
function () payable public { }

//========================= Functions
//=======Add functions
//Add employee to employee storage
function addEmployee(address _address, uint256 _monthlySalary, uint256 _startDate)
public
onlyOwner
validAddress(_address)
higherThanZero(_monthlySalary){
    employeeStorage.add(_address, _monthlySalary, _startDate);
}

...
..
.

}

So you can see that Payroll uses an instance of Employeestorage and Token. I have tested it on Remix and it seems to be working fine. My question is, how would my 2_deploy_contracts.js look like? Seems like it would simply be:

2_deploy_contracts.js

var payroll = artifacts.require("./Payroll");

module.exports = function(deployer) {
  deployer.deploy(payroll);
}

Here is my Gist with all the code.


texts: Checking if an address is encoded on the end of a bytes array

texts:
I have a bytes array. Within the last 20 bytes, there is an address stored.

I am trying to compare the address at the end of this array to the address of a msg.sender, and am wondering if there is a hyper-efficient way of doing so (code golf people, I'm looking at you).

So far, here is the solution I have come up with.

function toBytes(address a) constant returns (bytes b){
  assembly {
      let m := mload(0x40)
      mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
      mstore(0x40, add(m, 52))
      b := m
  }
}

function checkAddress(bytes data, address toCheck) constant returns (bool){
    bytes memory addBytes = toBytes(toCheck);
    for(uint i = data.length - 20; i < data.length; i++) {
        if (data[i] != addBytes[i - data.length + 20]) {
            return false;
        }
    }
    return true;
  }

checkAddress takes the byte array, and the address to compare it to, converts the address to a bytes array, and then compares it, byte by byte, to the last 20 bytes of the byte array. As of now, this works.

(As a side note, the toBytes function was taken from the stack exchange here: How to convert an address to bytes in Solidity?)

However, I feel like there should be a significantly more efficient way of doing this check, possibly using assembly. Something like casting the address to a uint, maybe using Nick Johnson's string library to grab the last 20 bytes of the array, and converting that to a uint also, and then comparing.

Any directions/tips would be greatly appreciated. Thanks for the help!


texts:
I'm trying to understand open zepplins crowd sale contract code: https://github.com/OpenZeppelin/zeppelin-solidity

I understand that if someone sends ether to the contract address that it responds with:

   // fallback function can be used to buy tokens
  function () public payable {
    proxyPayment(msg.sender);
  }

But I'm a little confused about how "payable" works. Can only one function per contract be "payable"? And is that function basically just an event listener for when the contract receives ether?

Thanks


texts: I want to remove the timed aspect of this crowdsale contract and make it finalizable manually

texts:
Which lines do I remove and what do I replace them with to change this from a timed crowdsale contract into one I can end manually?

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;
            }
        }
    }
}


texts: State tree diagram with real world ethereum transaction

texts:
Newbee here. Just getting used to StackExchange interface and protocol. Apologies up front for any feeling of misgiving.

Would anyone be able to provide an ethereum state trie diagram depicting how an ethereum transaction gets stored in the state trie?

@atom33ls provided an example in the question thread Ethereum Block Architecture, but I'm still a little confused. The diagram provided has a Simplified World State key-value mapping table, top right corner. This is a great diagram but I'm confused by the table. I don't quite understand how the keys are derived? Any insight would be appreciated.


texts: Is it possible to access MetaMask functionality for integration testing?

texts:
I'd like to be able to access MetaMask to test potential user actions.  I doubt it's possible to directly simulate sending transactions, but what I hope I can at least confirm is that transactions are being correctly fed to the plugin.  I've never had to test a plugin so I'm not sure if this is possible for any kind of plugin.

Since I should be able to trust MetaMask's ability to interact with networks, I can just mock the sending of the transaction with web3 so it's just confirming that transactions in MetaMask before they are submitted.

I'm planning to use Jest, Chromium, and Ganache.  Any help is appreciated.


texts: Transactions not getting mined (Web3.js)

texts:
I'm trying to make a simple ether transaction with web3.js. Most times I try to execute the transaction, I get the following error: Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined! Further, these transactions don't seem to get mined even after checking on them on Etherscan. Here is my current code:
request-mock.js
const atmosphere = require('./package-mock')
... other imports here ...

atmosphere.request({
    from: account1,
    to: account2,
    value: '0.8',
    privateKey: PRIVATE_KEY_1,
    network: 'ropsten'
}).then(response => {
    console.log('atmosphere.request response', response)
})

package-mock.js
const Web3 = require('web3')
let web3
const axios = require('axios')
const compiler = require('solc')
const Tx = require('ethereumjs-tx')
const fs = require('fs')

module.exports = {

    getCurrentGasPrices: async function() {
        let response = await axios.get('https://data-api.defipulse.com/api/v1/egs/api/ethgasAPI.json?api-key=API_KEY_HERE')
        let prices = {
          low: response.data.safeLow / 10,
          medium: response.data.average / 10,
          high: response.data.fast / 10
        }
        return prices
    },

    sendTransaction: function(raw) {
        return new Promise(function(resolve, reject) {
            let txHash
            web3.eth.sendSignedTransaction(raw)
            .once('transactionHash', function(hash){
                console.log('Transaction Hash:', hash)
                txHash = hash
            })
            .on('confirmation', function(confNumber, receipt, latestBlockHash){
                const array = [confNumber, receipt, latestBlockHash, txHash]
                resolve(array)
            })
            .on('error', function(error){
                resolve(error)
            })
        })
    },

    signTransaction: async function(txObject, privateKey) {
        const tx = new Tx(txObject)
        tx.sign(Buffer.from(privateKey, 'hex'))
        const serializedTransaction = tx.serialize()
        const raw = '0x' + serializedTransaction.toString('hex')
        const response = await this.sendTransaction(raw)
        return new Promise(function(resolve, reject) {
            resolve(response)
        })
    },

    getCurrencyTxObject: async function(params) {
        const gasPrices = await this.getCurrentGasPrices()
        let parameters = params
        parameters.nonce = web3.utils.toHex(web3.eth.getTransactionCount(params.from, (error, txCount) => txCount))
        parameters.gasPrice = web3.utils.toHex(web3.utils.toWei(gasPrices.high.toString(), 'gwei'))
        parameters.gasLimit = web3.utils.toHex(21000)
        parameters.value = web3.utils.toHex(web3.utils.toWei(params.value, 'ether'))
        return parameters
    },

    returnTxObject: function(params) {
        web3 = new Web3(`https://${params.network}.infura.io/v3/KEY_HERE`)
        delete params.network
        return this.getCurrencyTxObject(params)
    },

    request: async function(params) {
        const pk = params.privateKey
        let txParams = params.value ? params : this.formatContractParams(params)
        delete txParams.privateKey
        const txObject = this.returnTxObject(txParams)
        const response = await this.signTransaction(txObject, pk)
        return new Promise(function(resolve, reject) {
            resolve(response)
        })
    },

}

In addition to what I've tried in the above code, I've also tried the following:

Increasing the gas price. I've tried gas prices all the way up to 1000 wei.
Tried different test networks such as Ropsten and Goerli.
Created additional accounts and tried a transaction with those.
Created another Infura project to use another endpoint.
Tried spacing out the time between transactions.
Add 1 to the calculated nonce.
Increased gas limit.
Despite trying the above changes, I still get the same error and the transaction is never mined. How can I get a successful transaction


texts: Check if node is running in private network

texts:
Is there a command in the geth javascript console to check if node is running in private net or if it is public?

For now I always had to check it in the left hand corner in mist if it's private or public:


texts: How to let Dapp connect to network from Mist browser (ver 0.8) without starting geth with rpc options manually?

texts:
After Mist 0.8, I made the following change on my Dapp so that it uses existing web3 connection if connected via Mist.

https://github.com/makoto/blockparty/commit/cbea6e2990e5699532acecd5aedcf4b0180faf7d

However, the dapp is failing to connect to network (eg web3.currentProvider.isConnected() is returning false) when opened it from Mist.

It can be connected if I kill geth process opened by Mist, and launch geth manually with --rpc rpccorsdomain=* options enabled, but that defeats the purpose of having Mist browser.

Am I missing anything to make my Dapp "Mist ready"?


texts:
Isn't it possible to define modifiers in libraries? I'm really asking myself why, because thats some functionality you would need over and over again.

If I would like to hypothetically implement some ownable modifier and let that be used in many of my contracts, I would have to implement it in every of my contracts or use another contract (no library), that provides the modifier.

I've seen https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol and they implement the functionality also as a contract rather than a function as, I guess, modifiers cannot be accessed from Solidity libraries?

My question: should I now implement my modifiers in my abstract contracts or define modifiers in a contract on its own like the Zeppelin guys did? Whats the up/downsides?


texts: Assembly call instruction address as single integer

texts:
The following function is a function of a library (The code is written in Solidity). It has an assembly instruction that I do not understand. Specifically at line call(sub(gas, 2000), 6, 0, input, 0xc0, r, 0x60).

From the docs:

  call(g, a, v, in, insize, out, outsize)

  call contract at address a with input mem[in..(in+insize)) providing g
  gas and v wei and output area mem[out..(out+outsize)) returning 0 on
  error (eg. out of gas) and 1 on success

function addition(G1Point p1, G1Point p2) internal returns (G1Point r) {
        uint[4] memory input;
        input[0] = p1.X;
        input[1] = p1.Y;
        input[2] = p2.X;
        input[3] = p2.Y;
        bool success;
        assembly {
            success := call(sub(gas, 2000), 6, 0, input, 0xc0, r, 0x60)
            // Use "invalid" to make gas estimation work
            switch success case 0 { invalid() }
        }
        require(success);
    }

Why the address field a is a simple integer ? Is it referring to an internal library function ? If yes how is the numbering defined ?

Tell me ff you want me to provide the full code of the library.

EDIT

I think I found it. Is the address of the a precompiled contract ?


texts: ethereumjs-tx : sign transaction using unlocked account

texts:
Web3js has the following method :

web3.eth.signTransaction(transactionObject, address [, callback])

to sign a transaction using an unlocked account.

Can we sign a transaction in a similar way, without explicitly providing the private key, with ethereumjs-tx ?


texts: Understanding different network for ether transactions

texts:
I have just started learning about ethereum and trying to toy around different use-cases.
I tried sending an ethereum to my wallet using ropsten ethereum faucet.
Now, my understanding is this is some kind of a dummy ethereum value and don't hold any monetory value which means I can't sell it.
Then I tried to register ENS Domain using the same ether which I got from faucet and I managed to register it.
Now, I am really confused that how I can register a domain name using a dummy ethereum value(I am assuming my above assumption is correct).
Also, how different transaction networks are different from each other.


texts: Function "is not a function" in Truffle dev

texts:
I am not sure why I am being told my function is not a function.

I am doing calls as I always do from the Truffle console.

pragma solidity >=0.4.22 <0.6.0;

contract store {
    string public storage_;

    function store_it(string memory s) public {
        storage_=s;
    }
}

stor = store.at(store.address)

stor.store_it("string")

TypeError: stor.store_it is not a function

What is going wrong?


texts: Insufficient funds despite positive balance

texts:
I have already scrolled through similar questions, but the solutions provided didn't work.

As per title, I get the error insufficient funds for gas * price + value

BACKGROUND:

I am creating a webapp for a smart contract token. Once a user signs up, a new wallet is created for him in geth keystore using web3.personal.newAccount()
As the newly generated address is retrieved, the miner sends 777 ETHER to this new adddress with web3.eth.sendTransaction() in order to be able to execute transactions. Afterwards, this new address sends a transaction to the smart contract contractDeployed.createWallet(). This is the transaction where sometimes I get the error insufficient funds for gas * price + value. It doesn't always happen, but 20% of the time is quite noticeable.

I can't get my head around it as I have set on the miner --gasprice "1" and all transactions are executed with predefined gasLimit and gasPrice (as shown in the attached code).

I have tried to nest the web3js calls with callbacks and with batch, no changes. I think I am waiting for the confirmation of the previous transaction before sending the new one.

Notes: I am using web3 0.20.6

CODE:

// Initialization Skipped

const bank = "0x49b36fa1772bdb4d9249f43179832ccdb3732ffc";
const defaultGasPrice = web3.toHex(4);
const defaultGasLimit = 3700000;
const topUpWei = 777;

// Sign up
router.post('/api/v1/address', function(req, res){
  const data = { name: req.body.name.replace(" ", ""), passphrase: req.body.passphrase };

  let address;

  return Promise.resolve()
    .then(function() {
      address = web3.personal.newAccount(data.passphrase);
    })
    .then(function() {
      return web3.personal.unlockAccount(bank, "");
    })
    .then(function(ret) {
      if (ret) {
        return web3.eth.sendTransaction({ from: bank, to: address, value: topUpWei, gas: defaultGasLimit, gasPrice: defaultGasPrice });
      }
      throw ({ message: 'unable to decrypt mint wallet' });
    })
    .then(function(ret) {
      if (ret) {
        return web3.personal.unlockAccount(address, data.passphrase);
      }
      throw ({ message: 'unable to send initial Ethers' });
    })
    .then(function(ret) {
      if (ret) {
        return contractDeployed.createWallet(data.name, 2, { from: address, gas: defaultGasLimit, gasPrice: defaultGasPrice });
      }
      throw ({ message: 'unable to decrypt ' + data.name + ' wallet' });
    })
    .then(function(ret) {
      if (!ret) {
        throw ({ message: 'unable to create wallet ' + data.name });
      }
    })
    .then(function() {
      return res.status(200).json({ address: address });
    })
    .catch(function(err) {
      console.log(err.message);
      return res.status(500).json({error: err.message});
    });

  return Promise.resolve(null);
});

module.exports = router;


texts:
I'm implementing a back end with different Ethereum features. I need to be able to create raw transactions. I've successfully did it using Web3 sendRawTransaction from Node.JS, but I wonder how should I calculate the first transaction Nonce when the address didn't send any.
If there is a previous transaction I calculate previous + 1 (as it's established in the paper) but when there isn't previous my understanding was that I should put 1, but I see that they start on 0x100000 for some reason I don't get.

Anyone know the answer?


texts: testrpc throwing 'out of gas' if same number of parameters passed while deploying as constructor

texts:
When I'm trying to deploy my contract on testrpc with correct parameters, it's throwing 'VM Exception while processing transaction: out of gas' exception. I deployed same contract on Ropsten and it worked fine.

/** Constructor */
    function Hotel(
            bytes32 _name,
            string _description,
            bytes16 _locationLatitude,
            bytes16 _locationLongitude,
            int _hotelTimeZone
        ) {
            name = _name;
            description = _description;
            locationLatitude = _locationLatitude;
            locationLongitude = _locationLongitude;
            timezone = _hotelTimeZone;
            owner = msg.sender;
        }

I'm deploying like given below on testrpc and it fails.

deployer.deploy(Hotel, 'Hotel', 'ABCDEF', '10.1231', '77.5946', 19800, {gas: 17000000});

But if I remove or add an extra parameter it works.

deployer.deploy(Hotel, 'Hotel', 'ABCDEF', '10.1231', '77.5946', 19800, 1,
 {gas: 17000000});
 or
deployer.deploy(Hotel, 'Hotel', 'ABCDEF', '10.1231', '77.5946' {gas: 17000000});

I increased the block gas size of testrpc and supplied quite an amount of gas but still, it didn't work. I even reduced the constructor parameters to just one and still it fails if I just pass one input. It works if I pass more than that or nothing at all.


texts: How DAI stablecoin is able to be decentralised or how the CDP(Collateralized Debt Position ) process works?

texts:
I am reading about stablecoins in order to understand which one would be best suitable for my need( let users of my app be payed or rewarded by a crypto and at the same time lowering the effect of volatility.

I am considering the main to:

USDT

DAI

They both have benefits, the promising thing about DAI is that it claim to be decentralised and this is achieved though the process of Collateralized Debt Position, that is not that so clear to me.

Any one could explain that process?


texts: How to transfer ERC20 token from one account to another account but paying the transaction fee from third account?

texts:
I want to transfer token from account A to account B by paying transaction fee from account C.I have tried the following logic but token transfer from contract to contract mean contract transfer token to itself.

tell me is it possible or not ?
if it is not possible then what would be alternative to achieve this goal.

  account address from which token has to transfer = TA

  account address from which transaction fee has to pay = PA

  account address to which token has to transfer = RA

var contract = new web3.eth.Contract(abiArray,contractAddress,{from:TA})

var rawTransaction = {"from":PA, "gasPrice":data.result,"gasLimit":web3.utils.toHex(100000),"to":contractAddress,"value":"0x0","data":contract.methods.transfer(RA, amount).encodeABI(),"nonce":web3.utils.toHex(count)}

var transaction = new Tx(rawTransaction,{ chain: transactionNetwork})

transaction.sign(privateKey of PA)


texts: Transactions not syncing among nodes in private network when volume is high

texts:
I have 3 nodes are all of them are mining. I called sendTransaction 150k times at a time on node 1. In the txpool of node 1 I see all 150k in pending but in node 2 and node 3 I can see only 50-100 txns. After those are mined it says 0 in both the nodes.

So why is it not syncing properly? Is 150k above capacity.


texts:
This post What was the second vulnerability used in The DAO attack on 17 June 2016? say :

  And from the Q&A [...], each of the transactions (the first and second
  at least from my manual counting) called splitDAO(...) 29
  times. But the 29 x splitDAO(...) calls were repeatedly called, creating > 27996 internal transactions, 13996 were non-zero internal transfers.
  Calculation: 13996 transactions x 258.05656476 ETH = 3,611,759.68038
  ethers, which is approximately the 3,641,694.241898506 Ether
  ($59,578,117.80) was moved to the account
  0x304a554a310c7e546dfe434669c62820b7d83490.

But isn't the call depth size max size of Ethereum's call stack capped at 1024 ?
Most blog posts says this recursive can only be done ~ 30 times...


texts: call function from truffle console (newbie)

texts:
This should be fairly simple, but I'm still trying to wrap my mind around a lot of things.
What is the easiest way of testing the function addEntity by hand? What command do I type into the truffle console to execute addEntity?
Thanks
 pragma solidity ^0.4.18;

 contract MetaCoin {
      struct  Entity {
               string name;
               string nickname;
               string streetaddress;
      }
      mapping (uint => Entity) entities;
      uint entitiesCount;
      event EntityAdded(address indexed _senderAddress, uint _entityId);

      function addEntity(string _name, string _nickname, string _streetaddress) returns(uint entityId) {
            entityId=entitiesCount ++;
            entities[entityId]=Entity(_name,_nickname,_streetaddress);
            EntityAdded(msg.sender,entityId);
      }
 }


texts: Retrieving block hash of current block vs previous block

texts: What is the formula for retrieving the blockhash of 1) previous block and of 2) current block?


texts: For pool mining, what exactly is a share?

texts:
Can someone please explain exactly what a share is in the context of pool mining? I have a superficial understanding of testing random nonces to find a hash under the current difficulty. I also understand that mining pools set a custom easier difficulty to target a relatively easy to attain share difficulty (~10 minutes).

What I don't understand is how those shares translate to finding real blocks. Say one out of a thousand shares is a valid real new block. Why wouldn't miners just submit that hash themselves, and send the rest of the easier shares to the pool?

I'm sure I have a fundamental misunderstanding, but can't figure out what it is. I guess somehow the pool has some secret that it can combine w/ the submitted shares to see if that share matches a block, but that is a guess.

Any help would be greatly appreciated.


texts: error message ParserError: Expected ',' but got 'memory'

texts:
I have this error but I do not know what is wrong?

browser/arry.sol:6:58: ParserError: Expected ',' but got 'memory'
    function addScore(unit24 s) public returens(unit24 []memory){
                                                         ^----^

this is my code

pragma solidity^0.5.0;

contract Score {
    unit24[]score;

    function addScore(unit24 s) public returens(unit24 []memory){
        score.push(s);
        return score;
    }

    function getLength()view public returens(unit){
        return score.length;
    }

    function clearArray() public returens(unit24 [] memory){
        delete score;
        return score;
    }
}


texts: How to safely and quickly identify a privileged transaction within a smart contract?

texts:
I'm running a crowdsale for dogs and cats. If you're a dog, you can earn my token (TKN) at 1 ETH per TKN. But, if you prove you're a cat, you can earn TKN at a rate of 0.1 ETH per TKN (meaning you get a better rate) in the crowdsale.

As the owner of the crowsdale's smart contract, I'll dynamically add to a list of who is a cat and who isn't a cat using a smart contract. Each time a user proves to me they are a cat, I'll post encrypted evidence (think zero-knowledge proof) that they are a cat. Using an address they give me, I'll add them to a list of cats within the smart contract. When  a user sends ETH from that address, they should be identified as a cat. But, this only works if my transaction adding them to the list of cats has already been executed by the time they send it.

Is the best solution to ask a cat to wait for 5-10 confirmations to ensure the privileged address is added to the smart contract? I.e. is this how long to wait to be sure the smart contract knows the address they are sending from belongs to a cat not a dog. What number of confirmations is considered secure in Ethereum?

It would be great to not make the cats wait like this -- you could do it if Ethereum were capable of verifying signed messages on its platform. But the fees associated with verifying a signed message would be too high.

Something like child-pays-for-parent could work? If the cat sent me their donation transaction, or if I sent them a privilege-enabling transaction to send first, the donation transaction could be conditionally executed upon the accurate execution of the privilege-enabling transaction. But I'm not sure I've seen anything like this in Ethereum, only in bitcoin.

Another option would be to have the user to send a donation in ETH, and not issue tokens until they are confirmed to be or not to be a cat. This would require locking their tokens indefinitely. It would make it risky to run a capped crowdsale, as you'd have to assume that every donation had the better conversion rate, even if it were later proven not to have had one. Asking users to suggest a conversion rate for themselves might temporarily alleviate the cap problems.

A last thing to use might be nonces? I could ask the user to provide me with two signed transactions, each with the same nonce, with a different amount of Ether depending on the conversion rate. Depending on whether they are a cat or not, I will broadcast one of the transactions. While technically possible, this would probably scare the user into thinking I am somehow robbing them twice, and also is a very inconvenient user experience (especially if there are more than two possible conversion rates).


texts: Who is providing the syncing and bootstraping services on ETH? Do they get paid?

texts:
I understand that a node can request synchronization from the network. But who is fulfilling those requests?

How are these requests sent out? Are they sent to the entire network or 1 specific node?
Who answers these requests? Full nodes?
If one full node is providing the download, how do the other full nodes know that this request has been "served"?
Does whoever providing the download get paid? How do they get paid?

Thanks!


texts: Are Parity/author and Geth/coinbase the same?

texts: Am I right that what geth calls the coinbase is the same thing that parity calls the author?


texts:
I'm running a batch script that would create up to hundreds of concurrent transactions and wait for their completion

truffle exec scripts/....js --network rinkeby ...

everything works but after certain amount of time when the script is still running just fine, the process is terminated with error message ETIMEDOUT

no stack trace, no further explanation. I'm using Truffle v5.0.9, thought there is some sort of timeout option for truffle exec but can't find any, did not find relevant resources either.

I'm confident this is not an issue in my code as the script catches all errors and report them with callback(errs).
any ideas?


texts: Do i need miners for my own cryprocurrency which is based on ethereum?

texts: I have a question. Do i need to find miners for my own cryprocurrency which is based on ethereum or ethereum will provide them for their fee to let transactions with my currency be accepted?


texts: How does Ethereum know who called a function first?

texts:
Scenerio 1

Say I have a function f().

Whoever calls the function first gets a reward.

Persons A, B, and C all call the function at roughly the same time.

Who will receive the reward?

Scenerio 2

Say I have a function f()

Whoever calls the function first gets a reward and function f() is no longer callable.

Persons A, B, and C all call the function at roughly the same time.

In actuality Person A calls function f() first.

Will persons B and C still be able to call the function?

For Clarity

I'm building a smart contract where if someone calls a certain function f(), that person and ONLY that person will receive a unique reward. And because that person called the function first, the contract will be paused (function f() will be uncallable) until that block has been mined.

So basically are the two scenarios mentioned possible?

Or am I misunderstanding anything when it comes to the mechanics of the Ethereum blockchain?

I've tested my contract within a private network and the contract is paused immediately once I call the function, and then is unpaused once the block has been mined.


texts:
The Truffle documentation says that the new() contract method deploys a new instance to the network.

I have the following code:

const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const contract = require('truffle-contract');
const MyContractJSON = require('./contracts/MyContract.json');

const MyContract = contract(MyContractJSON);

MyContract.setProvider(provider);

MyContract.new().then(instance => {
    console.log('it worked');
}).catch(err => {
    console.log('error', err);
});

Why does the promise returned by new() throw an error that says "Invalid address"? It does this regardless of whether or not I've deployed a contract to the network using truffle deploy. Am I using new() incorrectly?

EDIT: several days later I still haven't figured it out, but I've observed that any methods having to do with addresses throw an "Invalid address" error. I'm using truffle-contract@2.0.5 and web3@0.20.0.

If I have a contract that looks like this

import "./OtherContract.sol";

contract MyContract {
    function createNewInstance() returns (OtherContract) {
        return new OtherContract();
    }
}

and in the JS I do something like the JS above except with instance I call
instance.createNewInstance() I get an "invalid address" error.


texts: Why is it important to declare functions as view or pure in solidity?

texts:
Accordingly to the solidity documentations, functions can be declared as view:

  in which case they promise not to modify the state.

or they can be declared as pure

  in which case they promise not to read from or modify the state.

But what is the importance of declaring functions with one of this two states and why not just omit it?


texts: Are contract calls asynchronous in web3.js?

texts:
Suppose we have a contract:

contract C {

    uint256 a;
    uint256 b;

    function setA(uint256 aval) {
        a = aval;
    }

    function setB(uint256 bval) {
        b = bval;
    }

    function getA() constant returns (uint256) {
        return a;
    }

    function getB() constant returns (uint256) {
        return b;
    }
}

and we try to set values, get them and store them into an array using web3.js:

var ABI = [{"constant":false,"inputs":[{"name":"bval","type":"uint256"}],"name":"setB","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"getB","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"getA","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"aval","type":"uint256"}],"name":"setA","outputs":[],"type":"function"}];
var contractAddress = "0x11111222222222222222";
var contract = web3.eth.contract(contractAddress, ABI);
var numbers = [];

// Set the values
contract.call().setA(100);
contract.call().setB(200);

// Get them and add them to the array
var a = contract.call().getA();
numbers.push(a);
var b = contract.call().getB();
numbers.push(b);

Can b be added to the array before a? I know that web is asynchronous for most methods but does this apply to contract method invocation as well?


texts: Unable to define greeterContract in the Greeter tutorial. Breaking change in Solidity 0.4.9!