texts: If Wallet and address generated using EthHDWallet, can we get its recovery using ethereumjs-utils/hdkey getWallet() method by provideing seed?

texts:
Generated wallet address using:

let mnemonic = request.body.seed;
const wallet = EthHdWallet.fromMnemonic(mnemonic);
let address = wallet.generateAddresses(1);
console.log(wallet, address);

How can I recover wallet address using mnemonic?


texts: How can I use the payable function to transfer fixed ether in a transaction?

texts:
contract MyContract {

    address payable[] recipients;

    function sendEther(address payable recipient) external payable {
        recipient.transfer(1 ether);
    }
}

Error- transact to MyContract.sendEther errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance.


texts: Why do compiler version and version in the source code not fit together for some verified contracts on Etherscan?

texts:
I found this verified contract on Etherscan: https://etherscan.io/address/0xd7a27d8d58f0c9e378fb3cb2816bde94c5e34059#code

Etherscan says, it was compiled with solc version v0.4.14+commit.c2215d46, but the first line in the source code says pragma solidity ^0.4.18;. Therefore, the contract doesn't even compile with compiler version 0.4.14. How it still possible that this contract was verified with that compiler version on Etherscan?


texts: How to specify eip100 in Parity chain spec?

texts:
In a Parity chain spec file, how can I include EIP100?

I do not see it in the default file here to copy:
https://github.com/paritytech/parity/blob/master/ethcore/res/ethereum/foundation.json

I think I simply add:

  "eip100Transition":

Or is it eip100dTransition?  with a "d"?

Can someone confirm?


texts: Execute contract function with raw transaction

texts:
I am trying to build a light interface which can broadcast a raw transaction and execute an Ethereum contract's function. While I am able to build a simple transaction there is little guidance on how to execute a contract's function.

I have the following code to build the transaction:

function createRawTransacton(){
var privateKey = new Buffer('d3780dd620ef80b3918dfcdb9105f76147fc55a3775ff71805ccec09a89063ed', 'hex')
 var rawTx = {
   nonce: 'CX350',
   gasPrice: 'C350',
   gasLimit: '0x09184e72a000',
   to: '0xc5622be5861b7200cbace14e28b98c4ab77bd9b4',
   value: 'CX350',
   data:    '0x19dacbf83c5de6658e14cbf7bcae5c15eca2eedecf1c66fbca928e4d351bea0f'
}
var tx = new Tx(rawTx)
tx.sign(privateKey)
var serializedTx = tx.serialize()
console.log(serializedTx.toString('hex'))
broadCastTx(serializedTx.toString('hex'))
}


texts: Gas used for the same deterministic operation is different

texts:
standard ICO function which exchanges Ether to ERC20 token balance.

Call 1, used 49431:
https://ropsten.etherscan.io/tx/0x6671c8fd39d195b09868d914d80f0e884e42259c7346b69afb483f2e18fae263

Call 2, used 34431: https://ropsten.etherscan.io/tx/0x990f9eebf09968cdfc29a4d2b4f0090b96e4cdff196fb2a0a10ea1a1d7f02164

Same code, same wallets.

Does it mean that gas consumption of working with mapping structure isn't deterministic? it's because it's hashmap?


texts:
I'm using web3J library in my java app.
I got an address of a deployed contract and would like to get it's binary or abi from the blockchain using my java app, how can I do that?


texts: Combining two 32 byte values (bytes32) into a 64 byte value

texts:
I am passing 64 byte public keys into my solidity function as two 32 byte parts, high 32 bytes and low 32 bytes. How do I combine them back to a 64 byte value in Solidity (cost efficiently)? Looping and adding byte by byte would be quite expensive, but I suspect there should be a solution that involves loading values into memory and reading them from there using assembly, but so far I can't figure out how to.

function generateAddress(bytes32 pubKeyHigh, bytes32 pubKeyLow) returns (address) {
    bytes pubKey = ..... combine pubKeyHigh and pubKeyLow .....
    return address(keccak256(pubKey));
}


texts: What advantages and disadvantages does Ripple have over Ethereum?


texts: Are there any EIP to speed up block times to stay competitive with other blockchains like EOS with .5 second block times?

texts:
Doing some research on EOS and it "seems" impressive or its just hyped up marketing.

They have .5 second block times which I can see to be very beneficial for dapp development response times. Are there any plans for Ethereum to reduce block times to under 1 second to stay competitive? The 15 second blocktimes are too slow for certain types of dapps like gaming related ones, but are ok for dapps don't require the immediate feedback.


texts:
I want to design my dApp on Ethereum but i want to explain the application logic (smart contracts) through BPMN to explicit my decentralized exchange.. Can someone help to design my decentralized exchange or just tell me where can i find ressources to do that..

Thx in advance


texts: I am running a test which involves sending transactions to a smart contract from multiple nodes. Right now, I have seperate truffle folders in each node, with a test file that sends the transactions to the right contract. In addition, the first node's test file includes additional logic (apart from sending the transactions) that monitors the generated events from all transactions and makes calculations. From my understanding, there is no way to implement this logic in a single test file as truffle uses the config file to open only 1 connection and it is not possible to have multiple connections in 1 truffle instance?


texts: After compiling contract, there is no build directory inside project directory?

texts: After writing 'truffle compile' in terminal , it just give the message i.e. compiling your contracts...and exit, no build directory is formed in Project directory. What is the issue?


texts: Create a contract that safely swaps one token for another?

texts:
If I mint a token and the contract doesn't have all the features I needed from the offset, is there a way I could develop a new contract for a new token and create a way in which people can send the Old token and be returned the new one?

I had a client who was eager to mint coins to distribute to early private investors but the actual way the token will be used or interacted with will change over time, so I'm not too sure how to go about this.

Or perhaps I'm missing something and we can extend the contract.


texts:
solc 0.8.4
I'm trying to save the value of msg.value in my constructor. If I assign it to one of the state variables, it gets reverted by the EVM when I try to deploy the contract. However, if I assign that state variable a non-zero value (either before or after setting it to msg.value), then it works.
State variables:
address payable contract_owner;
uint256 wei_received;

Constructor version 1
The wei_received state variable is set to 1 before it is set to msg.value.
Success: The contract deploys and the value of wei_received is set correctly.
constructor () payable
{
    contract_owner = payable (msg.sender);
    wei_received = 1;
    wei_received = msg.value;
}

Constructor version 2
The wei_received state variable is not being set to 1.
Failure: Reverted by the EVM at time of deployment.
constructor () payable
{
    contract_owner = payable (msg.sender);
    wei_received = msg.value;
}

Constructor version 3
The wei_received state variable is set to 1 after it is set to msg.value.
Failure: The contract deploys but the value of wei_received is set incorrectly.
constructor () payable
{
    contract_owner = payable (msg.sender);
    wei_received = msg.value;
    wei_received = 1;
}

Is that by design for some reason? Is it a bug in this version of solidity? The workaround is simple, but I'm wondering if anyone else has noticed this and if there is a reason for it.


texts:
I will try keep it short.
I am having a curious case here. In etherscan I see all coins available in my address. All except one shit coin is available on my old windows machine, that I was using some 3 years ago to manage my crypto via Ledger live app.
Now the fun part :) I tried to connect this wallet to MEW, metamask or mycrypto, so I can send this coin. Unfortunately due to different derivation paths I get different addresses. I've tried custom dPath without any success. I am taking the path from Ledger Live, as I see it in "advanced".  Then I installed ledger live on my Linux machine and to my surprise I got same addresses as MEW or Metamask. What has changed in the derivation path in those 3 years remains a mystery to me. At the moment I cannot access this coin in any possible way.
Out of desperation, this coin is still worth some money, I used an offline machine to connect to MEW using the mnemonic. To my surprise, I did not access the address with tokens but some other random address.
So, is it possible for whatever reason to have different addresses on the same mnemonic? I don't have any other recovery words and I used them recently to reinitialize my ledger nano s and I got access to my eth address but again only on the old windows 7 machine. I am really confused :) Please share your 2c that might help me understand the issue and perhaps find a solutions.Thanks!


texts: Getting TX is not defined when trying to send signed transaction

texts:
I am trying to learn how to send a signed transaction using web3 1.0 and Infura.io. I have node.js running locally for testing. I can successfully create an address and check balances but am getting TX not defined when I run the sendSignedTransaction.

const Web3 = require('web3');

web3 = new Web3(new
Web3.providers.HttpProvider("https://mainnet.infura.io/v3/My API Key"));

// Get Contract ABI
var abi = JSON.parse('[{"MY ABI"}]')

// Define Variable for Contract ABI
var AK = new web3.eth.Contract(abi);

// Buffer PK
var privateKey = new Buffer('Private Key')

// create transaction - to address, amount
var data = AK.methods.transfer("To Address", 10).encodeABI();

// object to hold the transaction data From Address
web3.eth.getTransactionCount('From Address').then(count => {

var txData = {

nonce: web3.utils.toHex(count),

gasLimit: web3.utils.toHex(25000),

gasPrice: web3.utils.toHex(web3.eth.gasPrice),

to: "To Address",

from: "From Address",

data: data

}

var transaction = new TX(txData);

transaction.sign(privateKey);

var serialisedTransaction = transaction.serialize().toString('hex');

web3.eth.sendSignedTransaction('0x' + serialisedTransaction);

});

I get the following error -

(node:16077) UnhandledPromiseRejectionWarning: ReferenceError: TX is not defined
at web3.eth.getTransactionCount.then.count
(/Users/ryan/Documents/KapAction/public/send.js:39:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:16077) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not
handled with .catch(). (rejection id: 1)
(node:16077) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.

I am really new to this and am trying to learn but am not sure where I am going wrong.


texts: Is it possible to have ERC20 token (A) own other ERC20 tokens (X, Y, Z)

texts:
I'm building a DAPP, where a user has one 'parent' ERC20 token and several other 'child' ERC20 tokens.

So what I want is .... To have a parent token A, and that token owns the tokens X, Y and Z.

In my DAPP, the parent does not always own the same child tokens. Child tokens are dynamic in size and type.

The reason being, I want to be able transfer 'ownership' of all the tokens in 1 transaction, by simply transferring token A from one address to another.

Is this possible?

I have been looking into Proxy Contracts, but I'm not sure if this would work. I was wondering if anybody has done something similar.


texts: Does anyone know how many full archiving nodes are there in Ethereum network. I know this site https://www.ethernodes.org, but there is no way to discover which node is full node and wich one is full archiving node.


texts: Can I access my account using some http request?

texts: I am accessing my accounts and everything using Ethereum Wallet (Mist) but I was wondering is there any possible way to access my account using some http request?


texts:
"getPastLogs" can get past event log. I check the web3 documentation：

fromBlock - Number|String: The number of the earliest block ("latest" may be given to mean the most recent and "pending" currently mining, block). By default "latest".
toBlock - Number|String: The number of the latest block ("latest" may be given to mean the most recent and "pending" currently mining, block). By default "latest".
address - String|Array: An address or a list of addresses to only get logs from particular account(s).
topics - Array: An array of values which must each appear in the log entries. The order is important, if you want to leave topics out use null, e.g. [null, '0x12...']. You can also pass an array for each topic with options for that topic e.g. [null, ['option1', 'option2']]

Q1：What does 'address' means?Is it the contract's address or default account ?

Q2：What do 'topics' mean? How do I setup the array?
Thanks~~


texts:
Can someone tell me what the #[$] or [$] in the remix assembly output means? I assume it's a placeholder for something yet to be determined but am unable to confirm if and what.

For example:

PUSH #[$] 0000000000000000000000000000000000000000000000000000000000000000

(note: push only takes 1 parameter)


texts: I cant get the value of a state variable public

texts:
I am developing a smart contract which I have two contracts(A and B). I have an array variable in A and fill it with values but when I get that variable from B, the array address is empty.

pragma solidity ^0.4.10;

contract Censo{

struct Persona{
    string name;
    uint age;
    uint weight;
    uint number;
    uint position;
    address[] propuestasVotadas;
}

address personaAutorizada;

mapping(address => Persona) public personas;
address[] public personasList;

function Censo(){
    personaAutorizada = msg.sender;
}

function existePersona(address _address) public constant returns(bool){

    if(personasList.length == 0) return false;
    return (personasList[personas[_address].position] == _address);
}

function addPersona(address _address, string _name, uint _age, uint _weight, uint _number) public{

    require(!existePersona(_address));

    personas[_address].name = _name;
    personas[_address].age = _age;
    personas[_address].weight = _weight;
    personas[_address].number = _number;
    personas[_address].position = personasList.push(_address) - 1;

}

function getNumPersonas() public returns(uint){

    return personasList.length;
}

}

contract MinisterioInterior{

struct Propuesta{
    string nombre;
    string descripcion;
    uint numVotos;
    uint position;
}

event PropuestaAdded(address _address, uint now);
event PersonaVotePropuesta(address _addressPropuesta, address _addressPersona, uint now);

mapping(address => Propuesta) propuestas;
address[] propuestasList;

address personaAutorizadaMinisterio;

function MinisterioInterior(){
    personaAutorizadaMinisterio = msg.sender;
}

function existePropuesta(address _address) returns(bool){

    if(propuestasList.length == 0) return false;
    return (propuestasList[propuestas[_address].position] == _address);
}

function crearPropuesta(address _address, string _nombre, string _descripcion) returns(bool){

    require(!existePersona(_address));
    propuestas[_address].nombre = _nombre;
    propuestas[_address].descripcion = _descripcion;
    propuestas[_address].numVotos = 0;
    propuestas[_address].position = propuestasList.push(_address) - 1;
    return true;
}

}


texts:
I am creating blockchain application in django with 6 main entities .By entities I mean to say these 6 entities will replicate data or you can say consensus mechanism will evolve around these entities . Now my question is how can I integrate ethereum in my django app.

I only need ethereum for distributed database storage and my consensus mechanism or proof of work is entirely different as compared to ethereum. Should I use ethereum in my project or completely create it from scratch in sqlite?
I am really confused how to built database for my blockchain application.


texts: TypeError: "send" and "transfer" are only available for objects of type "address payable", not "address". owner.transfer(msg.value); ^------------^

texts:
pragma solidity ^0.5.0;

/**
 * The Hotel contract does this and that...
 */
contract Hotel {

    struct Room {

        uint id;
        string name;
        string hotel_name;
        uint price;
        string status;
    }

    // mapping acts as a associative array of key => value , here key is unsigned
    // int and value is structure
    mapping (uint => Room) public rooms;

    // Store hotel count - we cannot iterate or find size in mapping
    uint public roomsCount;

    // Amount is send to owners address , owner will auto set to the deployed one
    address owner;
    // Constructor called when contract is deployed or migrated
    function Hotelc () public {

        // Set the contract creater as the owner
        owner = msg.sender;

        addRoom("Room 1");
        addRoom("Room 2");
        addRoom("Room 3");
    }

    function addRoom(string memory _name) private {

        roomsCount++;
        rooms[roomsCount] = Room(roomsCount,_name,'Hotel 1',1 ether,'available');
    }

    function bookRoom(uint _roomId) payable public {

        // Check that the room is a valid
        require (_roomId > 0 && _roomId <= roomsCount);

        // Check if room is available
        require (compareStrings(rooms[_roomId].status,"available"));

        // Check if amount is equal to the price of the room
        if(msg.value != 1000000000000000000)
        {
            // Throw exception
            revert();

        }
        owner.transfer(msg.value);
        // change the status of the room
        rooms[_roomId].status = "Not available";

    }

    function compareStrings (string memory a, string memory b) public view returns (bool){
       return keccak256(a) == keccak256(b);
   }
}


texts: How to get the miner address of a block with infura Rinkeby endpoint?

texts:
I've read some docs online that to get the miner/sealer/signer address of a particular block that runs with the Ethereum PoA/Clique consensus (the Rinkeby testnet for example), I need to call the clique_getSnapshot RPC interface. However when I tried it with a infura Rinkeby endpoint, it returns "The method clique_getSnapshot does not exist/is not available" error.

So is there any way where I can get the miner/sealer/signer address of a particular block on the Rinkeby testnet with an infura Rinkeby endpoint? For example on etherscan it shows that block 4753195 is mined by 0x7ffC57839B00206D1ad20c69A1981b489f772031

https://rinkeby.etherscan.io/block/4753195

How may I get that info?

======

Thanks to @Ha ĐANG , I've now come to this stage:

Web3 = require("web3");
web3 = new Web3("https://rinkeby.infura.io/v3/xxxxxxxxx"); // my infura Rinkeby endpoint
ejutils = require("ethereumjs-utils");

(async () => {
  blk = await web3.eth.getBlock(4753195);

  blkhash = blk.hash;
  console.log(blkhash);
  // 0xdfd0a441a76d0f54bea2b61963871a61bca5eb4adf76f15d60e2d3c7b19cf191 Correct!!

  extdat = blk.extraData;
  console.log(extdat);
  // 0xd883010900846765746888676f312e31322e34856c696e7578000000000000009e4d991ca30e6ff6782058da4b958eb180e54f3af99f00afa9d42ea01c08b1134664c21f408d79c87d93a6ce83354a68d8f0d3fea99bc796029875563acceef801 Correct!!

  msg = ejutils.toBuffer(blkhash);
  sig = extdat.slice(-130);
  r = "0x" + sig.slice(0, 64);
  s = '0x' + sig.slice(64, 128);
  v = '0x' + sig.slice(128, 130);
  v = parseInt(v) + 27;
  pub = ejutils.ecrecover(msg, v, r, s);
  addr = ejutils.pubToAddress(pub);
  addr = ejutils.bufferToHex(addr);
  console.log(addr);
  // 0xe2877298e8cf1046ae9f3231e17f73fe85282590 Wrong :(

})();

So any idea what went wrong in the above code? Thanks.


texts: Transaction not being mined within 750 seconds

texts:
On the main net, after getting the error from the title, by making sure it's not in pending pool, how long should I wait until I can safely retry a transaction?
Thanks


texts: Ethereum wallet 0.9.0 slow sync (deleting block chain works but problem eventually comes back)

texts:
Windows 8.1 with 8GB RAM, 400GB spare, i7 CPU. 100Mb fibre broadband. Bitcoin and Litecoin wallet syncs no problems.

So had an issue a few weeks back where block around 4 million was syncing at a rate of 2 blocks per second. Uninstalled client, deleted block chain data, reinstalled and allowed fast sync to kick in. Fast sync no problems. Launched client every day and allowed sync to happen. No issues. Now a few days later it's doing the same thing as before.

This seems to be a recurring issue that creeps in after the client has not been opened for a few days. Back to 2 blocks a second. I'm having to wait an 1hr 20 mins for syncing about 3 days worth of blockchain data. Any ideas?


texts: MetaMask displaying wrong value when making RPC sendTransaction call

texts:
I have been trying to send a transaction using an RPC call  with MetaMask's window.ethereum.request injected method.
I have successfully sent a transaction before, by using the web3js method web3.eth.sendTransaction with MetaMask displaying the intended amount of ether. For the conversion from ether to wei I'm using web3.utils.toWei("3", "ether).
However, when I try to send a transaction using an RPC call, the MetaMask pop-up displays an incorrect amount of ether to be sent. The accounts used below are provided by Ganache. The sender address belongs to the account I have successfully connected to my app using MetaMask.
I am using Ganache as a local network and Firefox on Ubuntu. This is the code used to make the call:
 const myParameters = {
    from: "0x5c0bC92f7d26F7AD821408e2B1774FC96858C691",
    to: "0x6cC5550509CC3a66Df97Efa42B866A058e12ADE2",
    value: web3.utils.toWei("3", "ether")
    };

let results = await window.ethereum.request({method:"eth_sendTransaction", params: [myParameters]});

I have also tried converting the value to string, but I get the same wrong amount. Here's the pop-up I get for the above code:


texts: Adding Recent EIP's to Custom Blockchain

texts:
I have a custom blockchain running on Parity 2.3.8.  My question is do the recent EIP additions (https://coinswitch.co/news/ethereum-hard-fork-jan-19-know-everything-about-3-upcoming-eth-hard-forks) automatically become part of my new blockchain or is it necessary to manually add them each?

Related question: do they all get added under the params section of my chain specificaion?


texts:
I want to give users a private key so they can Easily get address..

Why? So a single series of digits enables them to have both public address and private key.

Of course this is for temporary use not for holding ether.

So the question is: how does one derive public address from private key?


texts: How to find the address of the contract owner?

texts:
I'm under the impression that the owner of the contract is simply referred to as accounts[0] in Truffle's testing environment, but I'm getting the error by the modifier that the caller of a certain function is not the owner.

I have instantiated contract A and contract B and the following code is in contract B:

    modifier requireContractOwner() {
        require(msg.sender == contractOwner, "Caller is not contract owner");
        _;
    }

    function _authorizeCaller(address addr)
        external
        requireContractOwner
    {
        authorizedCaller[addr] = true;
    }

And I'm calling the functions from contract A:

    function authorizeCaller(address addr) public {
        B._authorizeCaller(addr);
    }

The way I instantiated A is:

    constructor(address dataContract) public {
        contractOwner = msg.sender;
        B = B(dataContract);
    }

and B:

   constructor() public {
        contractOwner = msg.sender;
        authorizedCaller[msg.sender] = true;
    }

Following is how I deploy them:

module.exports = function (deployer, network, accounts) {
  deployer.deploy(B).then(() => {
    return deployer
      .deploy(A, B.address)
      .then(() => {
       // configuration
      });
  });
};

The problem is, when I test calling the function with the owner of the contract:

      let B = await B.new();
      let A = await A.new(B.address);
      await A.authorizeCaller(accounts[1], {
        from: accounts[0],
        gasPrice: 0,
      });

the testing fails saying that accounts[0] is not the owner of the contract by the modifier requireContractOwner().


texts: How shoud I properly initialize DApp and get account address?

texts:
I am writing DApp in react, and basically I want to initialize web3, unlock account, and display it. Having web3 in my package.json In the onload I've tried to go following:

let Web3 = require('web3');
let instance = new Web3(window.web3.currentProvider);

First of all, I am completely missing the point of such a step. What do we do here? What is the difference between window.web3 and instance now?

Second, what line should I use and why?

console.log(window.web3.eth.accounts[0]); // this?
console.log(instance.eth.accounts[0]); // or that?

I want to figure out browser-agnostic scheme, that would work on Metamask, Opera, and on mobile browsers like Cipher.
I've tried a bunch of schemes, on some platforms I'm missing web3.eth.accounts[0], but accounts can be availble via web3.eth.getAccounts()

I've looked at following, but still can't generalize:

Better pattern to detect web3 default account when using metamask
New web3 method to request account access from dapp browser, no request

I run into a problem that it's neither straightforward, nor documented process. To face such a problem, lets create a place with answer, detailing basics of init and unlock procedure, that should work in any browser, for any web3.


texts: Why won't remix finish launching all of my libraries?

texts:
I've run into an issue.  I have a contract with a hierarchy of libraries (some lower level libraries import higher level libraries).  All libraries are ultimately imported by our main contract.  Previously, I could deploy the libraries and contract without issue (ie. metamask would pop-up after each library is deployed, allowing me to confirm the next library's transaction).  Starting yesterday, metamask will only pop-up for the first two libraries.  After the second library's transaction has succeeded, Remix just sits and does nothing (metamask does not open and does not have any transactions in que).

All libraries compile fine.  I checked the transactions on etherscan and both library transactions were successful.  I tried deploying each library one-by-one, and all of them succeeded.  As far as I know, I can't deploy my main contract without first deploying all of the libraries.  I'm not sure what the issue is.  Any help?


texts: Converting bytes32 to uint256 in solidity

texts:
How to go about converting a bytes32 variable to an uint256 variable in solidity? A straight forward conversion is not possible since when I converted the bytes32 variable which has a value of 99 to uint256.
uint256(0x3939000000000000000000000000000000000000000000000000000000000000)
I get the result
25882542651938552044065725088383013338356811605330942117523409242735587098624


texts: Find an ethereum address with a given balance of an ERC-20 token

texts:
I know it is easy to lookup the token balance of a particular Ethereum address (e.g. etherscan or via code such as this stackexchange question).
If I want to find a wallet with a particular ERC-20 token balance at a particular point in time is there a way to do this?  In other words, is it possible to find a wallet that either currently has (a more simple case perhaps) or at a point in time that can be specified had a certain ERC-20 balance.
For example can I identify an address (or list of addresses) that has/have had:
KNC 100.01
Either currently or at a particular point in time?
And just to be clear, the unknown would be the address.  The balance would be known for a particular token.


texts: Truffle react box onChange error: cannot read property 'setState' of undefined

texts:
these are the functions that fail:
Error:
Uncaught TypeError: Cannot read property 'setState' of undefined
    at createOrgSchoolAddress (App.js:187)

when I pasted the address in (third function was called)

createOrgShortNameChange(event){
    this.setState({createCredentialOrgShortName: event.target.value});
}
createOrgOfficialNameChange(event){
    this.setState({createCredentialOrgOfficialSchoolName: event.target.value});
}
createOrgSchoolAddress(event){
    this.setState({createCredentialOrgSchoolAddress: event.target.value});
}

GitHug Link

School Short Name	<input type="text" maxLength="30" size="32" value={this.state.createCredentialOrgShortName} onChange={this.createOrgShortNameChange} />

School Official Name	<input type="text" maxLength="70" size="72" value={this.state.createCredentialOrgOfficialSchoolName} onChange={this.createOrgOfficialNameChange} />

School Address	<input type="text" maxLength="42"  size="50" value={this.state.createCredentialOrgSchoolAddress} onChange={this.createOrgSchoolAddress} />

I expect it's something simple, but am stuck at the moment.


texts: Cancelling an ETH transaction in pending state

texts:
I accidentally sent ETH to the wrong address and need to cancel the transaction before it hits the blockchain.  I am not sure how to do this. Can I have someone please help provide steps as it is being sent from binance.  I am uncertain as to what steps to atually perform to get my ETH back.

I went to MyEtherWallet.com and went to Send Offlilne

What should I set the values to:

The from address: should this be the original address that came from Binance?  If so how do I find out what was used?
The To address: I assume this is the incorrect address where this was sent
Value/amount to send: The actual amount of ETH sent in the previous transaction
Gas Limit: What value should i put
Gas Price: waht value
Nonce: what Nonce should I leave it at?

What option do I choose on how i would like to access my wallet?  I am coming from none of the options

What do i need to put in the publish transaction space for the signed transaction?


texts: How can I set the gas price while deploying a contract with web3.js?

texts:
I set up a Geth node on the Rinkeby network recently.  And while I can send ordinary transactions in seconds without a problem, I can't seem to get a contract creation to happen in less than an hour.  When I compile a simple contract in Remix and then paste the web3.js deployment code it generates into the Geth console--it submits the transaction onto the network, but then it just sits there for over an hour without any of the authorized nodes ever accepting it into a block.  Although eventually it gets accepted.

I am wondering if the issue here may be the gas price.  Based on etherscan, it looks like web3.js decided to set the gas price for the transaction to 4 gwei. I have verified that the average for the network is currently only 2 gwei, but still--I'd like to eliminate this as a possibility.  (The gas limit is definitely not a problem--set to 4700000 and the estimated gas for the contract creation code according to Remix is only 80924.)

If anyone reads this and suspects what I'm seeing is due to something other than the gas price being too low, then feel free to view the transaction  here and make suggestions:

https://rinkeby.etherscan.io/tx/0xe134c193cead33031e3348ebb1db42115fdf156cb5e1a1d43d5c4ecfdf026413

Anyway, my specific question is:  where is this default gas price of 4gwei coming from, and how can I override it with something higher?

For some reason in the documentation for web3.js there is no mention of any way to specify the gas price for a contract creation, even though it does provide a way to specify it for an ordinary transaction:

https://github.com/ethereum/wiki/wiki/JavaScript-API

Can I just pass an additional option to web3.eth.contract() of gasPrice= , or perhaps to myContract.new()?


texts: How to protect a private Ethereum chain?

texts:
I have a private Ethereum P2P Network with a custom networkId and a custom genesis block. I would like to allow only invited peers.

If I have a custom networkId and a custom genesis block, will someone not having these two informations be able to connect to the network and sync with my private chain? Moreover, could someone query the node to obtain these informations?


texts: Once a transaction is committed to the blockchain is there a way to let an entity outside the blockchain (i.e. An entity that is not a node in the blockchain) know that a particular transaction has been committed?


texts: zk-SNARKs vs. Zk-STARKs vs. BulletProofs? (Updated)

texts:
zk-SNARKs, Zk-STARKs and BulletProofs are three major zero knowledge proofs to provide privacy for the blockchain technology.
If we can compare them,

(1)  Bulletproofs and Zk-STARKs require no trusted setup.

Unlike zk-SNARKs that requires a trusted setup that creates an uncomfortable situation for it.

(2) Zcash using zk-SNARKs can hide amount address along with sender and recipient.

It is not yet clear to me if it is possible to hide sender and recipient by Bulletproofs and Zk-STARKs.

(3) Apparently, Zk-STARKs is faster than zk-SNARKs is
faster than Bulletproofs.
(4) Bulletproofs is shorter than zk-SNARKs and
Zk-STARKs.

In general, what are the main differences (advantages and disadvantages) between these 3 main zero knowledge proofs techniques ?
Note: The references are used for the above comparisons:
https://crypto.stanford.edu/bulletproofs/
https://blockonomi.com/bullet-proofs/
https://nulltx.com/mit-review-acclaims-zk-snarks-but-zk-starks-may-steal-the-show/
Note 1: The following article compares SNARKs with STARKs:
https://medium.com/coinmonks/zk-starks-create-verifiable-trust-even-against-quantum-computers-dd9c6a2bb13d
Note 2: I compared zk-SNARKs vs. Zk-STARKs vs. BulletProofs in following figure. Any comment on this comparison is appreciated:


texts:
TL,DR: Is anyone also experiencing problems with the Web3JS documentation?

I am very confused by the API documentation of Web3Js because of its behaviour.

(1)

var myContract = new web3.eth.Contract(abi, address);

Error: VM4943:1 Uncaught TypeError: web3.eth.Contract is not a function at :1:10

But when I use...

var myContract = new web3.eth.contract(abi, address);    // Minor c

it is working just fine.

(2)

var contract2 = contract1.clone();

Error: VM5261:1 Uncaught TypeError: contract3.clone is not a function
    at :1:11

(3)

My aim is to create a default contract (already done), clone/copy it. But I am stuck where it comes to receiving the contractAddress from the newly created contract:

var SampleContract = eth.contract(abi);

var contractInstance = new SampleContract.new(30, {data: byteCode, from: firstAccount, gas: estimate, gasPrice: estimate});

...

Thank you in advance!


texts:
I happened to deposit a new token "POWR" on bittrex exchange and when clicked to generate a new address i got a 0xa217f4c09ff1a27be0724f1efaf0fc5e87ca3031
When i checked the address in Etherscan the i found it aas a smart contract address, so i got confused that why did i got a smart contract address to deposit my funds to.

I asked some of my developers and then they told me that it is a multisignature address.
So my question is how can we identify if a specific address is smart contract or a multisignature address.


texts:
I have code like this and I want to set my name, surname and age in my struct so I want to set them and get them using with my functions

here's my code :

pragma solidity >=0.4.0 <0.7.0;

contract NewHello{
    address owner;

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

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

struct user{
    string name;
    string surname;
    uint age;
}

user[] new_user;
mapping(address => string) public users; // contains a name for every address

function updateUser(address _address, string memory name,string memory surname,uint age) public onlyOwner {
    user memory new_user = user(name,surname,age);
    users[_address] = user(name,surname,age);

}
function getUser(address _address) public view returns(string memory name ,string memory surname,uint age) {
    //if(users[_address].age == 0) throw;
    return (users[_address].name,users[_address].surname,users[_address].age);
}

}

I get 2 errors first one is :

TypeError: Type struct NewHello.user memory is not implicitly convertible to expected type string storage ref. users[_address] = user(name,surname,age); ^--------------------^

TypeError: Member "name" not found or not visible after argument-dependent lookup in string storage ref.

anyone can help me please ?


texts: Usage of light node through the HTTP API

texts:
Am I correctly understanding that all I have to do to use a ethereum light node (started with a syncmode=light) is to call regular ethereum api as described in https://github.com/ethereum/wiki/wiki/JSON-RPC ? So that I just call of those functions with eth_ prefix and I don't have to call the functions like GetBlockHeaders as described in LES specification:https://github.com/zsfelfoldi/go-ethereum/wiki/Light-Ethereum-Subprotocol-%28LES%29 ?
So that geth will do everything w/o my help.  Right?


texts: Must I add WETH conversion descritpion in a contract and how?

texts:
I'm confused about how I write a contract about WETH conversion.
When we write a smartcontract depositing user funds into a contract, should we necessarily write some codes of converting eth into weth before depositing? Or is it automatically converted without doing anything?
I've found descriptions about WETH on the uniswap's router contract( function addLiquidityETH) which is called when users provide the liquidity for the uniswap pool.
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));

*https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/UniswapV2Router02.sol
On the other hand, for example, join.sol(function join) on MakerDAO's vault contract and CEther.sol(function doTransferIn) on Compound's Ctoken contract, I can't see anything about weth even though they seem the functions to deposit eth into a contract.
*https://etherscan.io/address/0x2f0b23f53734252bda2277357e97e1517d6b042a#code
function join(address usr) external payable note {
require(live == 1, "ETHJoin/not-live");
require(int(msg.value) >= 0, "ETHJoin/overflow");
vat.slip(ilk, usr, int(msg.value));

*https://github.com/compound-finance/compound-protocol/blob/master/contracts/CEther.sol
function doTransferIn(address from, uint amount) internal returns (uint) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount; }

And what I want to do after I make sure above problem is write a contract where user can deposit ETH into another contract by interecting with this contract. I know if a user has WETH, it's easy bc all i have to do is write function transferfrom but I don't know how to do it with ETH itself.


texts: Unable to mine blocks in private Blockchain in VM

texts:
I am trying to run a test Ethereum blockchain and I was following this tutorial How to create local multi-node private Ethereum network. At around 25 minutes, the tutor shows how to mine. Till now, I have exactly followed his steps and have successfully replicated them on my system. However, at this stage, when I run the command miner.start(1), it returns null instead of true.

Even on running eth.mining command, it shows false, indicating mining has not started yet. Neither is any DAG being created. I posed this same question to the tutor on his channel, but there doesn't seem to be any solution.

I am running geth CLI on a Ubuntu 16.04 VM allocating a 1 core CPU with RAM of 1 GB. I am not using the Mist Wallet to track ether or accounts. The JS console seems powerful enough for that. Is mining not taking place because of running of the instance on VM? Kindly help me out ASAP.

This is the genesis.json file content, just for reference.

  { "config": {

  "chainId": 0,
   "homesteadBlock": 0,
       "eip155Block": 0,
        "eip158Block": 0
    },

  "nonce": "0x0000000000000042",

  "timestamp": "0x00",

  "parentHash": "0x000000000000000000000000000000000000000000000000000000000000$

  "extraData": "0x00",

  "gasLimit": "0x08000000",

  "difficulty": "0x0400",

  "mixhash": "0x000000000000000000000000000000000000000000000000000000000000000$

  "coinbase": "0x3333333333333333333333333333333333333333",

  "alloc" :
     {

  }

  }

Edit 1: Added JSON file content.

Edit 2 : Added RAM allocation in VM


texts:
How to get transactions history details of specific account using Ethereum API

currently i am using Ethereum API got get list of transactions based on ontract address, but i need full details of each transaction as well to populate on my dashboard.
this is the example which i am using for to populate list of transactions:

https://api-ropsten.etherscan.io/api?module=account&action=txlist&address=0x39659330d4a4f25743569e58c11d4f838d4ce68b&sort=asc

please help me if any endpoint to get individual transaction details using Ethereum API?

Thanks


texts: How to get the creator of a contract (was: the owner)

texts:
How to get the creator of a contract  from the code of another contract? I tried to look at the functions coming with type address but no luck

edit: I know you can with tools like etherscan, however the question is how to do from code.


texts: eth_getLogs was only return erc20 tokens

texts:
i have used below command to get every logs on the special blocks but its only return erc20 token logs and ethereum transactions was not listed.

my geth command:

curl --data '{"method":"eth_getLogs","params":[{"fromBlock": "0x9C98BE", "toBlock": "0x9C98BE"}],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:25545

my command just return 147 transactions:

https://pastebin.com/ybYz1k4q

etherscan was return 170 transactions:

https://etherscan.io/txs?block=10262718

Anyone can explain where is the etherum transactions (Not ERC20 Transactions) on eth_getLogs?


texts:
I am calling contract's method from javascript.

It throws error as:

Error: gas required exceeds allowance or always failing transaction

 &nbsp; &nbsp;at Object.InvalidResponse (/home/serverpro/Blockchain/healthcare/node_modules/web3/lib/web3/errors.js:38:16)

 &nbsp; &nbsp;at RequestManager.send (/home/serverpro/Blockchain/healthcare/node_modules/web3/lib/web3/requestmanager.js:61:22)

 &nbsp; &nbsp;at Eth.send [as estimateGas] (/home/serverpro/Blockchain/healthcare/node_modules/web3/lib/web3/method.js:145:58)

 &nbsp; &nbsp;at SolidityFunction.estimateGas (/home/serverpro/Blockchain/healthcare/node_modules/web3/lib/web3/function.js:187:26)

 &nbsp; &nbsp;at /home/serverpro/Blockchain/healthcare/api/routes/insurance.js:86:60

 &nbsp; &nbsp;at Layer.handle [as handle_request] (/home/serverpro/Blockchain/healthcare/node_modules/express/lib/router/layer.js:95:5)

 &nbsp; &nbsp;at next (/home/serverpro/Blockchain/healthcare/node_modules/express/lib/router/route.js:137:13)

 &nbsp; &nbsp;at Route.dispatch (/home/serverpro/Blockchain/healthcare/node_modules/express/lib/router/route.js:112:3)

 &nbsp; &nbsp;at Layer.handle [as handle_request] (/home/serverpro/Blockchain/healthcare/node_modules/express/lib/router/layer.js:95:5)

 &nbsp; &nbsp;at /home/serverpro/Blockchain/healthcare/node_modules/express/lib/router/index.js:281:22

At below line.

var gasamount = insuranceInstance.addInsurance.estimateGas(insuranceId,company,plan,price,details);

solidity function is:

function addInsurance(uint _insuranceId,string _comapany,string _plan,uint _price,string _details) public {
    insuranceDetail[_insuranceId].company = _comapany;
    insuranceDetail[_insuranceId].plan = _plan;
    insuranceDetail[_insuranceId].price = _price;
    insuranceDetail[_insuranceId].details = _details;
    totalInsuranceCount++;
    InsuranceAdded (owner,_insuranceId);
}

What is could be?


texts: How do I develope a QR code for a 64 character hex string generated ethereum address?

texts:
I am learning about how the 64 character hex string generated Eth Address is formed.
Is there a program for this?


texts: Ganache forked mainnet impersonate account transaction error

texts: I am trying to impersonate my contract using forked mainnet on ganache whenever the account send a transaction I dryrun the transaction first on forked mainnet but it always give me Error: Returned error: VM Exception while processing transaction: revert UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT error even the transaction is success on mainnet, the account impersonated is already unlocked through evm_unlocked_accounts Why is this happening and how do I resolve this issue?


texts: Deploying multiple instances of contract, no error but no deployment

texts:
I am trying to deploy the same contract code to create multiple instance:

const contract = require('truffle-contract')

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

module.exports = function(deployer) {

  contract("Greeter3", async (accounts) => {
    it("should be initialized twice", async () => {
      let instance1 = await Greeter3.new();
      let instance2 = await Greeter3.new();
      assert.notEqual(instance1.address, instance2.address);

      deployer.deploy(instance1);
      deployer.deploy(instance2);
    });
  });

};

No error message is returned, but the deployment fails:

6_multi.js
==========

   > Saving migration to chain.
   -------------------------------------
   > Total cost:                   0 ETH

What does this response mean?


texts:
How to solve the following problem?

 $ truffle migrate
    Error: No network specified. Cannot determine current network.
        at Object.detect (C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\environment.js:31:1)
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\commands\migrate.js:91:1
        at finished (C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-workflow-compile\index.js:53:1)
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-compile\index.js:314:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:158:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:3888:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:473:1
        at replenish (C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:1006:1)
        at iterateeCallback (C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:995:1)
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:969:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:3885:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:154:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:1140:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:473:1
        at iteratorCallback (C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:1064:1)
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:969:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\async\dist\async.js:1137:1
        at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:133:1
        at FSReqWrap.oncomplete (fs.js:153:5)


texts: The state tree uses the Merkel-Patrica (MPT) tree, while the transaction tree and state tree use the Merkel tree?

texts:
In some blogs, I have read the theory such as this:
The state tree uses the Merkel-Patrica (MPT) tree, while the transaction tree and state tree use the Merkel tree.
I want to be sure that this view is correct?


texts: Web3: Perform contract function but only receive transaction hash or incorrect value

texts:
I am trying to demo a function on my own geth testnet. I deployed a sample contract I found at http://solidity.readthedocs.io/en/develop/types.html?highlight=crowdfunding.

pragma solidity ^0.4.11;

contract CrowdFunding {
    // Defines a new type with two fields.
    struct Funder {
        address addr;
        uint amount;
    }

    struct Campaign {
        address beneficiary;
        uint fundingGoal;
        uint numFunders;
        uint amount;
        mapping (uint => Funder) funders;
    }

    uint numCampaigns;
    mapping (uint => Campaign) campaigns;

    function newCampaign(address beneficiary, uint goal) returns (uint campaignID) {
        campaignID = numCampaigns++; // campaignID is return variable
        // Creates new struct and saves in storage. We leave out the mapping type.
        campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0);
    }

    function contribute(uint campaignID) payable {
        Campaign storage c = campaigns[campaignID];
        // Creates a new temporary memory struct, initialised with the given values
        // and copies it over to storage.
        // Note that you can also use Funder(msg.sender, msg.value) to initialise.
        c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value});
        c.amount += msg.value;
    }

    function checkGoalReached(uint campaignID) returns (bool reached) {
        Campaign storage c = campaigns[campaignID];
        if (c.amount < c.fundingGoal)
            return false;
        uint amount = c.amount;
        c.amount = 0;
        c.beneficiary.transfer(amount);
        return true;
    }
}

"contract" references the deployed contract.
I setup my default account and performed the newCampaign function:

> contract.newCampaign(eth.accounts[0], 100)
"0x0122973cbcb7df227e8d625c6ee4a831d716b8b69398e4431ec14f89951fdc25"

So I have the transactionHash. And a new campaign should have been created for the address associated with my account. But when I try to call the "checkGoalReached" function I always get "true", although for my campaign it should return false given that no one has contributed.

(I tried both 0 and 1 because it is based off the id)

> contract.checkGoalReached.call(0)
true
> contract.checkGoalReached.call(1)
true

Then I tried sending the transaction and logging the result for this function:

> contract.checkGoalReached(0, function(e, result) {console.log(result)})
0xe1bf7a275a62fb3bc2cdd12ff280cde5e9064ddbfeb51ba6713a713cd356c8cc
undefined
> contract.checkGoalReached(1, function(e, result){console.log(result)})
0x613c5973733cde57d4b7325bbab2d841d2fa6c95e371e77ca24a2f5a54768fd3
undefined

"false" should be returned, so I must be doing something wrong in the web3 console. What is the correct way to test these functions in the console?


texts: Assign keys to a multisig wallet within a contract?

texts:
This is tangentially related to this question: Can I Make A Contract A Keyholder to a Multisig Wallet?

Is it possible to setup a multisignature wallet from directly within a contract?
My intuition says no, because any generated private keys to be assigned to the key holders would be visible on the public chain.

If it were possible, the basic idea seems like it could be extremely useful for contracts facilitating crowdfunding or situations where large amounts of ether need to be managed decentrally but with enough flexibility that it would be infeasible to attempt to enforce every possible future use of the funds via explicit contracts.

As far as I know, nothing like this currently exists in Solidity. But does anyone have an idea of how this could be implemented? I was thinking something along the lines of a function that could generate a keypair without saving the private key in the state of the contract.


texts:
I am a total Solidity noob, and I want to know if I can use my set function to initialize my struct members as well as assign a value to a state variable:

pragma solidity ^0.4.21;
contract Govtcontract {

    uint256 public allocbudget;
    uint256 public rembudget;

    struct transaction{
        uint  expend;
        uint dept;
        string item;
        uint date;
        string location;
    }

 transaction public trx;

constructor (uint256 initbudget) public {
    allocbudget = initbudget;
    rembudget = initbudget;
}

function settx(uint amt, uint dep, string thing, uint date, string loc) public {
    trx.expend=amt;
    trx.dept=dep;
    trx.item=thing;
    trx.date=date;
    trx.location=loc;
    rembudget = rembudget - trx.expend;
}

function get() public constant returns (uint) {
    return rembudget;

    }
}

Also, how do I write the web3.js file to take multiple inputs for set()? I can't seem to find any resources online. TIA!


texts: What are the steps to convert ETH in a Ledger wallet to cash?

texts:
I recently bought a Ledger Nano S wallet and moved my ETH from Coinbase to the wallet's address.

I have no plans to move any of the ETH to cash anytime soon, but I realized that I'm not sure how to go about doing so.

I understand how to move ETH from the Ledger wallet to another wallet address, such as one created on MyEtherWallet, but it also is advised that one should never send ETH to an address that they "own" in an exchange such as Coinbase, since it's not an individual address that you have access to.

So, how does one convert ETH from a private wallet into cash? Or, more simply, how do I get ETH from my wallet to my bank account?


texts: Short of running one's own node, how can I see the code of suicided contracts?

texts: I'm interested in looking at the code in instances of the Parity Multisig wallet attacks, but the contracts have self-destructed. How can I get ahold of the exact bytecode that was executed in a given transaction once the contract has self-destructed?


texts: What is the "pre-commit" scheme to defeat frontrunning attack?

texts:
I am writing to inquire feasible strategies to defeat Transaction Ordering Dependence (TOD) bugs.

I learned from the best practice guideline such that we can use a so-called "pre-committed" scheme to defeat TOD attacks: https://consensys.github.io/smart-contract-best-practices/known_attacks/#front-running-aka-transaction-ordering-dependence

However, it is still unclear to me how does the "pre-committed" scheme is implemented. Could anyone shed some lights or some code fragment of such implementations? Also, besides such "pre-committed" scheme, what else can be done to defeat TOD attacks?

======== update ====================

contract TransactionOrdering {
 uint256 price; address owner;

 function buy(uint256 amount) {
   cost = price * amount
   return cost;
 }

  function setPrice(uint256 _price) {
    // owner can set the price.
    if (msg.sender == owner)
      price = _price;
  }
}

Let's suppose when the contract owner see a transaction of buy from the user, then the owner front runs a setPrice transaction to raise the price. Can the pre-committed pattern be used to defeat such attacks? Thanks a lot.


texts: Query each struct of a Mapping vs looping getter function for front-end?

texts:
I have a mapping of structs and a counter variable to keep track of how many structs are stored in the mapping.

For front-end development would you recommend to query each struct using the auto-generated getter mymapping[mystruct_index]. Or is it better to create a specific getter function to loop through X structs and retrieve structs in arrays of 50 for instance.
Also if I use the getter function to get just few rows of the struct instead of the whole struct, is it going to lead to better efficiency than simply making one query for one struct ?
Do you have some experience regarding front-end interaction with smart contracts, what do you think is the best design for efficiency and long term viability of the smart contract ?
Best regards


texts:
The voting on ethereum analysis by Dominik Schiener calculated that it would take 40 days to hold the UK general elections on the ethereum blockchain due to the transaction and gas limits.

I redid his math with some more current figures, here is what I calculated:

the gas limit is 3,141,592 (pi million)
transaction costs 21,000 gas (let's assume nothing else is attached)
that's 149.5996 transactions per block
with a blocktime of around 17.43 seconds
that's 4956.971 blocks per day

The result is the network allows for this use cas only 741560.9 votes (transactions) per day. But what if we require a volume of let's say 10x or 100x the transaction rate? How does the ethereum network scale? How fast can gas limits be adjusted? How many transactions can the network handle?


texts: computer configuration for connecting eth 50 or more nodes

texts: I'd like to rent a server to run eth client ,but I am not sure what the computer configuration should be?In my local pc ,I can only connect  less than 10 nodes and failed in sync.If I want to connect 50 or more nodes ,what the computer configuration should be ?8vCPu,500G SSD? Could you  please tell me your computer configuration and how many peers you connect,with synchronization time ? Thanks.,very much.


texts: Why Ropsten etherscan and local Ropsten are not showing the same data?

texts:
I am running geth to sync to ropsten testnet. I verified that block 0 are identical. However, seems like the local geth doesnt sync as high as the ropsten.etherscan.io site claims and checking individual blocks showing different transaction. I am a bit confused on what is going on here. Any insights would be appreciated.
Chris


texts:
I have set up a private network. Is there a way to be notified when node joins the network?
I connect all the nodes using a bootnode. I know that I can check all the nodes that are peers using admin.peers but is there a way to be notified when any node joins.


texts: Does Vyper have an equivalent CHAINID assembly function?

texts:
Since v0.5.12, Solidity provides a CHAINID OPCODE in assembly:

function getChainID() external view returns (uint256) {
    uint256 id;
    assembly {
        id := chainid()
    }
    return id;
}

Is there an equivalent in Vyper?


texts:
contract Test {
  ERC721Token public tokenAddress;

  constructor(address _address) public {
    tokenAddress = ERC721Token(_address);
  }
}

In this example, I just tested tokenAddress returns the address of a ERC721Token contract. If it's just returning an address, how come the state variable tokenAddress's type is ERC721Token and not address?

and the line here,
tokenAddress = ERC721Token(_address);
What does ERC721Token(_address) mean? Does it mean it's searching a specific ERC721Token contract from the network?


texts:
On Ethereum, I understand that one can create a contract and deploy it onto the blockchain. But I am not clear how this contract gets verified by miners before being deployed onto the chain. For example, it can be a voting contract as shown here or some other contract for my purpose.

Also, is there any tutorial for programming a miner to verify a specific behaviour, like if there is any infinite loop in the contract deployed.


texts: Smart contract interaction (with another contract) example for solidity version 0.4.24 that works on Remix

texts:
I was going through this code and I decided to test it on RemixIDE...
Creating a function that calls another contract

I kept getting "VM Exception while processing transaction: revert" when I ran a function from the caller contract. I googled the error, tried all suggestions of getting rid of the problem but none has worked.

I had earlier tried running the code from this tutorial (still about smart contract interaction) https://www.youtube.com/watch?v=zjUbLC21avw&t=425s got errors, then after research noticed the code was outdated syntax, thus the errors.

So my question is... Is it that the code from Creating a function that calls another contract , outdated, or is it a bug in Remix/Solidity... If it's a bug, how do you get rid of it? Is there a currently working example of contract interaction for version 0.4.24?

The code I am running on remix IDE is...

pragma solidity ^0.4.24;

contract Caller {

    Called public called_address;

    function set_address(address _addy) public {
        called_address = Called(_addy);
    }

    function set(uint256 _var) public {
        called_address.set(_var);
    }

    function set_call(address _called, uint256 _var) public {
        require(_called.call(bytes4(keccak256("set(uint256)")), _var));
    }
}

interface Called{
    function set(uint) external;
    function get() external view returns (uint);
}

Code for the called contract

pragma solidity ^0.4.24;

contract Called{
    uint public myuint;

    function myuint() public view returns(uint _myuint) {
        _myuint = myuint;
    }

    function set(uint _var) public {
        myuint = _var;
    }

    function get() public view returns (uint){
        return myuint;
    }
}

Also to note is that I had to define a getter function myself as the IDE was giving me an error saying some functions are not defined/used... Thank you for your help.

I am using web3 provider with an local instance of the blockchain via Genache


texts: Parity Ethereum Node database size limit

texts:
I'm running my own Parity Ethereum Node. The problem I'm facing is how to limit the size of database. Is it even possible?

The feature I'm looking for is to keep X last blocks and specify X size as a disk space.


texts: Can you use Metamask to deploy a contract with Truffle?

texts:
I've given up on deploying to mainNet with Truffle, the user experience sucks.
Is there a way to deploy using Metamask, where I can see upfront what the price will be to deploy, no suprises?


texts: User login in ethereum based voting dapp

texts: I am trying to build an ethereum based voting DAPP for my university project. My proposed system is for the university club and society elections. I am using ganache cli, truffle framework and node js for my project. The voting will be done in a client side website where the voters will select their favorite voters and approve their transaction using their private keys (using metamask). My question here is that, is there any ways for me to restrict the people/ the public addresses that will be participating in the voting process. I want to ensure that so one other than the particular club members to cast their votes in an election. How can i do this authentication process to ensure no one else except for the club members are using the system to vote?


texts: Send transaction with locked contract -> Error: insufficient funds for gas * price + value

texts:
I'm trying to send a transaction for a token with a locked contract. I'm doing this to find out when this contract will be open. So I'm expecting to get some kind of error like "ERC-20 Token Transfer Error (Unable to locate corresponding Transfer Event Logs), Check with Sender" or something, but I get this instead:

Error: insufficient funds for gas * price + value

I saw a lot of articles about this and tried everything, but everything leads to the same error. Is it even possible to make an app check whenever contract will be open? My code:

const main = async () => {
  console.log(`web3 version: ${web3.version}`);

  const myAddress = '0x...';
  const destAddress = '0x...';
  const transferAmount = 1;

  const count = await web3.eth.getTransactionCount(myAddress);
  console.log(`num transactions so far: ${count}`);

  const abiArray = JSON.parse(fs.readFileSync(path.resolve(__dirname, './contract.json'), 'utf-8'));

  const contractAddress = '0x...';
  const contract = new web3.eth.Contract(abiArray, contractAddress, { from: myAddress });

  const balance = await contract.methods.balanceOf(myAddress).call();
  console.log(`Balance before send: ${balance}`);

  const rawTransaction = {
    'from': myAddress,
    'nonce': '0x' + count.toString(16),
    'gasPrice': '0x09184e72a000',
    'gasLimit': '0x2710',
    'to': contractAddress,
    'value': '0x0',
    'data': contract.methods.transfer(destAddress, transferAmount).encodeABI(),
    'chainId': 0x01
  };

  try {
    const privKey = new Buffer.from(WALLET_PRIVATE_KEY, 'hex');
    const tx = new Tx.Transaction(rawTransaction);
    tx.sign(privKey);
    const serializedTx = tx.serialize();

    console.log(`Attempting to send signed tx:  ${serializedTx.toString('hex')}`);
    const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
    console.log(`Receipt info:  ${JSON.stringify(receipt, null, '\t')}`);
  }
  catch (e) {
    console.error('Failed to send transaction');
    console.log(e.message);
  }
};

my wallet private key is in this format (example):
7effd90c52ebcf6ff916a26e3053300ac10d4fecbcd0e46ae2ae861b120d8587

P.S. I use ethereumjs-tx to make traction.


texts:
Hi I am trying to make a call to the Dai contract in the Kovan testnet using web3.js and have to set the value of web3.eth.defaultChain to 'kovan'. The docs state that the default value for web3.eth.defaultChain is 'mainnet' but it is giving me 'undefined'. I think this is also why I am getting the wrong result on querying the balanceOf method. Could someone please tell me why this is happening? Here is my code :

const Web3 = require("web3");
if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
console.log(web3.eth.defaultChain); //This returns 'undefined'
web3.eth.defaultChain = 'kovan';
var DaiContract = web3.eth.contract('ABI_HERE');
var dai = DaiContract.at('0xC4375B7De8af5a38a93548eb8453a498222C4fF2');
console.log(dai.balanceOf('0x3B1b198FE3Ee0428164a2fD38529CE958e63a0BD'));


texts: Quorum Minimum Number of Nodes for Raft Consensus and Istanbul BFT

texts: A Quorum Raft cluster of 3 nodes can tolerate a single node failure, while a Quorum cluster of 5 can tolerate 2 node failures. What is the equivalent if one uses Istanbul BFT?


texts: Contract with a method to send received erc20 token to two different owner addresses

texts:
Was wondering if there is already an open source solidity code with method to sweep erc20 tokens received in contract address to destination address by calling an in-contract method such as "sweep()".

The objective is to sweep received erc20 tokens in the contract to two pre-defined wallet addresses, by calling the method in the contract.

Thanks!


texts: Image attached to Ethereum contract (off-chain)

texts: What I am trying to do is make some smart contracts that I am going to sell to my clients giving them ownership of those contracts. A web service using web3 will be available to retrieve some information about these contracts. I would like to give my client to link their contract to an image, that I will retrieve using my web service. Since there is no need of consensus needed for the image data, I prefer to have it stored off-chain using some kind of p2p network. This will avoid fees to store/Modify those images as well. It would be interesting if I can somehow link the client contract in Ethereum with his image in the other network. Is there any tool that I can build this kind of logic with ?


texts: Do the Ethereum clients store 'historic state' or just 'current state.'

texts:
I assume, given the recent state clearing, that the Ethereum clients must only store the current state of each account as opposed to all historic state. (Otherwise, if it stored a record of all past states for each account, wouldn't it still be storing the 20,000,000 empty accounts?)

But, if the clients only store the current state, how do they efficiently report on past balances as they do under this RPC call (https://github.com/ethereum/wiki/blob/master/JSON-RPC.md#eth_getbalance) which takes an optional block height?

Do the clients spin through the list of all transactions to build past balances or do the clients actually store past balances? If they store past balances, do they store any other history per account?


texts:
I'm reading through the documentation here https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html

and it says "In order to listen for this event, you would use..."

Coin.Sent().watch({}, '', function(error, result) {
     if (!error) {
        console.log("Coin transfer: " + result.args.amount +
        " coins were sent from " + result.args.from +
        " to " + result.args.to + ".");
        console.log("Balances now:\n" +
        "Sender: " + Coin.balances.call(result.args.from) +
        "Receiver: " + Coin.balances.call(result.args.to));
     }
})

Now, this is not part of the contract itself, so where would I run this code?


texts: How to check current status of state variables

texts:
I have deployed my contract locally into Ganache (GUI) and then send/call lot of transactions. After these transactions, now I want to check the current status of all state variables. Is there any way/API to get to know the current status of all state variables of a contract at run time (through program ).

My solution toward this is that I am using web3/javascript/nodejs and i have written a program which extract all getter functions from contract ABI. Because, i think these getters later will be utilized to know the status of all state variables of contract (I think this logic may not be true to fulfill my objectives...). I am not sure about it.

Here is my logic for getters

if(item.type === "function"  && item.stateMutability==='view')
    getters[i].push({
    contract: i,
    func: item.name,
    input: item.inputs
}

Later i write a function to to get the status of state variables.

async function getStatus(receipt, key, statusArr) {
  var myFunc;
  var  myContAddr = receipt.contractAddress;
  var myContractAbiDefenition = sources[key].abi;
  var myContractInstance = new web3.eth.Contract(myContractAbiDefenition, myContAddr);

  for(j=0; j < getters[key].length; j++){
      myFunc = getters[key][j].func;

      try {
        res = await myContractInstance.methods[myFunc](...getters[key][j].input).call({from: account1})
        console.log("Getter output", res);

      } catch (error) {
        console.log("Getter output: ERROR !");

      }
  }
}

Updated1:
my actual code of getters for maping of item.input.length > = 0 is as follow. In this code, i just give some dummy values as per input type...

if(item.type === "function"  && item.stateMutability==='view'){
                      // console.log(item.name)
                      getterFunctionsNameObject[i].push({
                        contract: i,
                        func: item.name,
                        input: item.inputs.map(({ type }) => {
                          switch(type) {
                            case 'address': {
                              return "0x2cAe18ac37d85CccdE2ebB63D0c391Fe1ac7c36f"
                            }
                            case 'address[]': {
                              return ['0x2cAe18ac37d85CccdE2ebB63D0c391Fe1ac7c36f', '0xc4ae9984fbbf2416205e81e725e92496ad1eb087']
                            }
                            case 'string': {
                              return 'ABC'
                            }
                            case 'uint8': {
                              return 126
                            }
                            case 'uint256': {
                              return 3546546
                            }
                            case 'uint256[]': {
                              return [546546, 546546]
                            }
                            case 'bool': {
                              return true
                            }
                            case 'bytes': {
                              return "0x3333"
                            }
                            case 'bytes32': {
                              return "0x564b25c8fcd6766f672d43252c8ee2597ad6c7a35315cf13e3b4d0"
                            }
                          }
                        })
                      })

      }


texts: Returning structs in new version in Solidity

texts:
I have been reading about Solidity release version 0.4.17.
https://github.com/ethereum/solidity/releases

One of the following statements was really interesting:

  We also worked further on the new ABI encoder: Functions can now
  return structs. Switch it on using pragma experimental ABIEncoderV2.
  It should already work, but still generates more expensive code.

I`ve been trying to simulate that in Remix but without any luck, I am getting this error:

  "error": "Failed to decode output: Error: Unsupported or invalid type:
  tuple"
  Here is my code:

pragma solidity ^0.4.17;
pragma experimental ABIEncoderV2;
contract StructTest{
    struct someTestStruct {
        uint A;
        uint B;
        bytes32 C;
    }
    someTestStruct str;
    function StructTest(){
        str = someTestStruct({A: 5, B: 6, C: "Hi"});
    }
    // trying to get struct but getting "error": "Failed to decode output: Error: Unsupported or invalid type: tuple"
    function returnStruct() returns (someTestStruct){
        return str;
    }
}

Have someone tried this? What am I doing wrong here? Thanks in advance!


texts: Making a contract with new keyword address is always 0x0000000000000000000000000000000000000000

texts:
I'm making a contract that makes other contracts.  Once the contract is made using address tokenAddress = new MyToken('Name'); I want to save the address of the contract, tokenAddress, in MyStruct.  The problem is that myMapping[uuid].tokenAddress is always 0x0000000000000000000000000000000000000000.  I'm guessing this is the default.

My question is, how do I get the address of where a contract is deployed?

struct MyStruct {
    string someData;
    address tokenAddress;
}

mapping (uint256 => MyStruct) myMapping;

function makeContract(uint256 uuid) view public {
    address tokenAddress = new MyToken('Name');
    myMapping[uuid].tokenAddress = tokenAddress;
}

EDIT:

I changed the signature of makeContract

function makeContract(uint256 uuid) view public returns (address, uint256) {
    address tokenAddress = new MyToken('Name');
    myMapping[uuid].tokenAddress = tokenAddress;
    return (tokenAddress, uuid);
}

and now it returns an address.  So now I'm trying to figure out why myMapping[uuid].tokenAddress isn't working.

One possible thing is that early in the contract I have to initialize some variables:

function setData(uint256 uuid, string someData) public {
    var struct_ = myMapping[uuid];
    struct_.someData= someData;
}

then later on I call makeContract.  Is it possible the modifying the struct is causing the problem?


texts: How i can calculate deterministic address from contract clone (create2)

texts:
Is there any way to calculate the deterministic address of a contract cloned by a Factory through create2?
I have this contract Factory
contract ForwarderFactory {

    function cloneForwarder(address payable forwarder, uint256 salt)
        public
        returns (Forwarder clonedForwarder)
    {
        address payable clonedAddress = createClone(forwarder, salt);
        clonedForwarder = Forwarder(clonedAddress);
        clonedForwarder.init(Forwarder(forwarder).owner());
        emit Deployed(clonedAddress, msg.sender);
    }

    function createClone(address payable target, uint256 salt)
        private
        returns (address payable result)
    {
        bytes20 targetBytes = bytes20(target);
        assembly {
            let clone := mload(0x40)
            mstore(
                clone,
                0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
            )
            mstore(add(clone, 0x14), targetBytes)
            mstore(
                add(clone, 0x28),
                0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
            )
            result := create2(0, clone, 0x37, salt)
        }
    }
}

How can I know before creating the clone which address will it have?


texts:
I am trying to learn about web3.js
I install

npm install ethereumjs-testrpc

and

npm install web3  // version 0.20.6
npm install ganache-cli // version 6.0.3

then i using the following code

var TestRPC = require("ethereumjs-testrpc");
var web3 = require("web3");
var ganache = require("ganache-cli");
//~ web3.setProvider(TestRPC.provider());
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
//~ var web3 = new web3(web3.givenProvider || ganache.server());

//~ var web3 = new web3(web3.givenProvider || 'ws://some.local-or-remote.node:8546');
//~ web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
//~ web3.setProvider(new web3.providers.HttpProvider('http://geth-node-ip:8545'));
//~ console.log(web3.isAddress("0x8888f1f195afa192cfee860698584c030f4c9db1"))

//~ web3.setProvider(TestRPC.provider());
//~ console.log(web3.version);
//~ console.log(web3.providers);

error says web3.setProvider is not a function


texts: hardhat-deploy: ProviderError: The method evm_snapshot does not exist/is not available

texts:
I'm trying to run a test with hardhat, and have it deploy my deployments/fixtures with the command:
npx hardhat test --network rinkeby --deploy-fixture

When I run this, I get the following error:
ProviderError: The method evm_snapshot does not exist/is not available
I have a deploy folder containing all my methods to deploy, and npx hardhat deploy --network rinkeby works great.
What gives?


texts: When I run the $truffle test command in the terminal does it consume any gas from my local blockchain(say Ganache)?


texts: geth calling funtion from a different contract not working, ganache & remix works

texts:
I'm trying to call a contract function from another contract, using web3.js.

When using ganache or remix everything works fine: web3.js returns the events fired and the gas used (33938 in this example) and the relevant fields in the contracts are being changed.

However, when I am using geth all of the above works, but only as long as I don't call another contract's function.
When doing so, the events are not returned, the fields are not changed and  the gas returned is either 90000 or the gas I am sending in the web3 send options (e.g c1.methods.transferToC2(1).send({from: <my account address>, gas: 2000000});

This is not exactly the contracts, but for general understanding of the problem, the relevant contracts structure is something like:

Contract c1 () {
    event Event(uint256 someNumber);
    address private c2Address = 0x208bcebf6cfa80fe2862fcdacdeb6ad9d3533017;
    address private someAddress = 0x5e7105a34ed27f0b72285f2f951394f3da3ea5eb;
    function transferToC2(uint256 someNumber) public  {
        Event(someNumber);
        IERC20(c2Address).foo(someAddress, someNumber);
    }
}

Contract c2 is ERC20 () {

}

interface IERC20 {
    function foo(address someAddress, uint256 someNumber) public returns (bool);
}

contract ERC20 is IERC20 {
    mapping (address => uint256) internal someMapping;
    function foo(address someAddress, uint256 someNumber) public  {
        someMapping[someAddress] = someNumber;
        return true;
    }
}

I am deploying the contracts with truffle migrate --network <network> --reset and the output is something like:

Deploying c1...
... 0x703293ce078c3c50e6da8725c6e9a4b91ae904c2943929c8e4189069dccc3de8
c1: 0xed8b7d949b961b1135199e08a9180f5328234426
Deploying c2...
... 0x1b54c170d4fccc13724ee9000078ff437b49883438413e5bf8da68d9343ca6d8
c2: 0x208bcebf6cfa80fe2862fcdacdeb6ad9d3533017

Inside the geth node it seems that my account address's balance is always growing, I assume as a result of the mining.


texts:
back with another question towards solidity Guru's. I am trying to call a method which takes bytes array as an input, but either I am encoding this parameter wrongly or decoding it wrongly. Solidity docs on the matter is fairly vague, so I implemented as I saw was written in the example. The function callback receives the said parameter, but than fails as reverted whenever I call it in a testnet. What am I missing regarding bytes abi.decode() function, or have just encoded my data wrongly?
Any help would be greatly appreciated, thank you!

Here's the relevant kovan testnet transaction:
https://kovan.etherscan.io/tx/0xc4a158d99f78dcf68ad8a3e9e26e4b8bad8b8a631dd09661ea09fdac23a0729a

The intended packed structure of the data passed in was as follows:

ff - operId
ffffffffff - txId
6bc84f6a0fabbd7102be338c048fe0ae54948c2e - forwardAddress
6bc84f6a0fabbd7102be338c048fe0ae54948c2e - refundAddress

And from what I could see in the transaction linked above the parameters where received in the precise order and in the expected sequence.

contract StoForwarder is Controllable {

    constructor(address _controller, address _controllerAgent) public Controllable(_controller, _controllerAgent) {}

    event NewTask(bytes5 txId, address forwardAddress, address refundAddress, address tokenContract,
        bytes32 partition, uint256 amount);

    struct Task {
        bytes5 txId;
        address forwardAddress;
        address refundAddress;
        IERC1410 tokenContract;
        bytes32 partition;
        uint256 amount;
    }

    mapping (bytes5 => Task) public pendingTasks;

    function callback(IERC1410 _stoContract, bytes32 _partition, uint256 _amount, bytes calldata _data) external {
        require(_data.length >= 46, "Insufficient data provided");
        byte operCode;
        bytes5 txId;
        address forwardAddress;
        address refundAddress;
        (operCode, txId, forwardAddress, refundAddress) = abi.decode(_data, (byte, bytes5, address, address));

        require(txId != "", "TransactionId not specified");
        require(_partition != "", "Bad Partition");
        require(forwardAddress != address(0), "Bad Forward Address");
        require(refundAddress != address(0), "Bad refund Address");

        pendingTasks[txId].txId = txId;
        pendingTasks[txId].forwardAddress = forwardAddress;
        pendingTasks[txId].refundAddress = refundAddress;
        pendingTasks[txId].tokenContract = _stoContract;
        pendingTasks[txId].partition = _partition;
        pendingTasks[txId].amount = _amount;

        emit NewTask(txId, forwardAddress, refundAddress, address(_stoContract), _partition, _amount);
    }

    function controllerTransfer(bytes5 txId, bool forward) onlyController external {
        require(pendingTasks[txId].txId != "");
        Task storage task = pendingTasks[txId];
        address targetAddress;

        if (forward) {
            targetAddress = task.forwardAddress;
        } else {
            targetAddress = task.refundAddress;
        }

        task.tokenContract.transferByPartition(task.partition, targetAddress, task.amount, "");
    }
}

P.S.
A total noob question: how is it possible to read require() error message after it has occurred on the blockchain? This parts eludes me a bit.


texts: Why does java Ethereum use UDP? - isn't devp2p TCP only

texts:
Looking through the source code for java ethereum I see UDPListener is part of the org.ethereum.net.rlpx.discover package and that this seems to use NioDatagramChannel (Netty's way of handling UDP datagrams) to handle Ping, Pong, FindNode and Neighbours messages and do the kademia DHT stuff. However the Devp2p specs say it is TCP only and indeed TCP is used for communication once nodes are discovered.

So I'm slightly confused; is UDP officially used for node discovery and then TCP for communication and if so where is this node discovery protocol documented?


texts:
I want to check, if the first digit of a uint256 is equal 5.
I therefore do the following:
function _numDigits(uint256 _number) internal pure returns (uint8) {
  uint256 number = _number;
  uint8 digits = 0;
  while (number != 0) {
      number /= 10;
      digits++;
  }
  return digits;
}

function firstDigitIsFive(uint256 _number) external pure returns (bool) {
    uint256 numdigits = _numDigits(_number);
    if(numdigits == 1) {
        return _number == 5;
    } else {
        return _number/10**(numdigits-1) == 5;
    }
}

Is there a better, easier and cheaper way to evaluate the first digit of an uint256?


texts: Wrapping Cryptocurrencies for interoperability sake

texts: How is it possible to standardize bitcoin and wrap it to the ERC20 format, creating smart contracts for Bitcoin. This should make it easier to write smart contracts that integrate bitcoin transfers apparently, but for my understanding this makes no sense since the code bases are alien to each other. Can someone elaborate? this seems rather complex?


texts: What are the causes of Ethereum's scalability issues? What's different about private chains that makes them more scalable?

texts: Is it related to the PoW consensus method?  Or that every full node must execute every transaction (can this be done differently in private chains)?


texts:
Where can I find the parity password to confirm a contract?

I want to transfer some ERC20 Tokens and cannot find the password.


texts: EVM Contract Testing with JS issue - ReferenceError: artifact is not defined

texts:
There is a problem i have with a new DAPP tutorial i'm looking at from this YouTube video:

I have an issue from for testing of my contract. when i run the "truffle test": it returns the following error:

Using network 'development'.

Compiling .\contracts\Election.sol...
ReferenceError: artifact is not defined
    at Object.<anonymous> (C:\DAPP\election\test\election.js:1:16)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at C:\Users\User\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:231:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (C:\Users\User\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:228:14)
    at Mocha.run (C:\Users\User\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:536:10)
    at C:\Users\User\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\test.js:125:1
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

I'm wondering i can fix the issue and complete the testing. Also, Here are the details EVN detail:

Truffle v4.1.14 (core: 4.1.14)
Solidity v0.4.24 (solc-js)

Here is the Election.js

var Election = artifact.require("./Election.sol");

contract ("Election", function(accounts){

    it("Initialize with 2 candidates",function(){
        return Election.deployed().then(function(instance) {
            return instance.candidatesCount();
        }).then(function(count) {
            assert.equal(count,2);
        });
    });
});


texts: Transaction hash is 'undefined' when running web3 code from command prompt

texts:
I wrote this java script code to send test ether to my other account:

var Tx = require('ethereumjs-tx').Transaction
var Web3 = require('web3')
web3 = new Web3('https://ropsten.infura.io/hqRzEqFKv6IsjRxfVUMH')
const account1 = '0x0539B9c9C886e93778542B553C64cb5EAfB902b1'
const account2 = '0xca7F442c44b079dd07324C9c7eDfe348b92f46c9'
const privatekey1 = Buffer.from('cxxxxxxxxxxxxx5xd0804xxxxxxx238ca1aed1xxx' , 'hex')
web3.eth.getTransactionCount(account1 , (err, transCount) => {
const txObject = {
nonce: web3.utils.toHex(transCount) ,
to: account2 ,
value: web3.utils.toHex(web3.utils.toWei('1' , 'ether')) ,
gasLimit: web3.utils.toHex(30000) ,
gasPrice: web3.utils.toHex(web3.utils.toWei('10' , 'gwei'))
}
var tx = new Tx(txObject)
tx.sign(privatekey1)
const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')
web3.eth.sendSignedTransaction(raw , (err, txHash) =>
  {console.log('txHash: ' , txHash)})
})

Now I run this code in the command prompt:

C:\Users\HP\path>
node testEther

This outputs:

txHash: undefined

  txHash: undefined

Why does this happen? I have tried to connect to different ropsten network, but still the problem persists. I have checked my test ether balance and it shows that I have enough ether.The transaction does not happen at all. Is the way I am connecting to ropsten wrong?


texts: watching all the events of a contract (geth): 'cannot find event for log undefined: undefined'

texts:
I  am trying to watch all events of a contract with many events. The following code is supposed to do just that:
var events = myContract.allEvents();
events.watch(function(error, event){
    if (error) {
        console.log("Error: " + error);
    } else {
        console.log('some event occured');
    }
});

But if I try it in geth, and trigger an event, this is what the console tells me:
cannot find event for log
undefined: undefined

Can someone please tell me what s wrong with this code?
(I run mist at the same time, I just geth attached)
Note that I have no difficulty watching individual events. I am instead trying to watch them all with the code above.


texts:
Does anyone have data on the typical kWh required to produce 1 ETH?

This answer suggests 13.46 KWh/ETH. It would be useful to find some comparison data.

I'd imagine these values are dependent on hardware, ambient temperature and the characteristics of the blockchain. Have I missed anything? How does the energy use per ETH vary as the Blockchain lengthens?

Does anyone have data on recorded kWh/ETH values, ideally with hardware and ambient temp (mean/var) ?

Out of interest, for BTC, this article suggests 240 kWh/BTC.

EDIT:

Following @NickJohnson's comment, It seems more sensible to ask for typical kWh per hash. I can then use the network hashrate and ether supply to graph kWh/ETH.

Does anyone have data on recorded kWh/hash values, ideally with hardware and ambient temp (mean/var) ?


texts:
Hopefully someone can help me out with a problem I'm experiencing.

I created a wallet contract to which I transferred the ETH on my account. Unfortunately, a few days later I restarted Mist and initially I still saw the correct balance only having it vanishing before my eyes 0,5 seconds later. The balance on my main account also vanished.

I've tried a clean install of Mist importing the UTC-- file. But to no avail.

I've also tried to import the UTC-- file through myetherwallet.com. Which gives me control of my main account again, but not the wallet contract that should be associated with it.

  Below are the codes for my;  Main:
  0x9724Ba43c22c735A2A0C025b90F18AD2a25798C2  Contract:
  0xe2839b4DF4168b5FDDc813883844162Ba4A8Bc6F

I'm running Geth 1.4.10 and the ETH are forked.

Thanks in advance guys.


texts: I am trying to analyze if/how staking affects the price of an ERC-20. Is there a way to find the total number of a specific ERC20 token staked each day? Does the transaction hash or input provide any information on this.


texts: Deploying on Rinkeby with Truffle using infura

texts:
If I want to use HDWalletProvider to deploy my contract on a specific address, what should I do?

rinkeby: {
    provider: () => { return new HDWalletProvider("Mnemnoic", "https://ropsten.infura.io/v3/KEY") },
    network_id: 4,
    gas: 7003605,
    gasPrice: 21,
    host: "localhost",
    from: "0xdc18ee70c6215ac9c81a3f704648b8c8a6ec7201"
}

I am getting following error

Error encountered, bailing. Network state unknown. Review successful transactions manually.
Unknown address - unable to sign transaction for this address: "0xdc18ee70c6215ac9c81a3f704648b8c8a6ec7201"


texts: Can i restrict a user from making only one transaction in a smart contract?

texts: For example in a voting dapp, I want only one address to make one vote. My doubt is can i store all the address of message senders in an array and check before casting the vote and hence allowing only one person to cast only one vote ?/


texts:
i rented a windows 2012 vps and install both mistwallet and geth. Mistwallet is working great.. but geth in other hand... it closed iself right after i double click it... can anyone tell me what wrong? or i lack certain supporting files?

for references i install geth windows from this link https://geth.ethereum.org/downloads/

ty


texts: Account address in ethereum wallet already existed

texts:
My etherum got stolen today

I have hosted my own ethereum fast node. The node wallet has multiple account. I have created a mini app with api to create new account(without passwords) for users, also allowing them to deposit and withdraw ethreum.

When I did "eth.accounts" (about a month post hosting the node) in my wallet (from geth command line) I was surprised to find 3 addresses with transactions dating 2 months even before I created the node(source etherscan.io).
Please note the following:

I have hosted the node on AWS ec2, and storing data by attaching a volume. Note around the time of those unknown transaction i had another node with this same volume attached.
Is it possible that the node somehow picked up wallet accounts from the previous node?
Node is running on a docker container (client-go)

How did these accounts get into my wallet, when i know the probability of generating an already generated address is almost 0? Could there have been a hack, inserted these addresses into my wallet, making users think these are new?


texts:
So I setup my private net and I have multiple computers(peers) connected on this network, but when I deploy a new contract I have to mine it with the machine that created the contract. Shouldn't it be possible for my peers to mine the contract I upload?

If you need any extra information just ask me


texts: Solidity mapping multiple items to one user

texts:
i'm trying to assign array of items to one user and i want to put address to mapping function and get all items like that:

mapping(address => Item[]) public ownerToItems;

but there is problem with assignment, first time accessing this array will be empty. How example like this should be build?


texts:
I have a meteor app and would like to use web3 on the server. Wneh I call a web3 function I always get the following error:

TypeError: XMLHttpRequest is not a function

What do I have to do, that I can call web3 functions from the server?

Thanks for your help


texts: Storing custom data in an ethereum based token?

texts:
I have an idea for a cryptocurrency with features that require storing and entering custom data related to accounts into the network. So the network would need potential to store balances/currency transactions, and other custom data about accounts.
Is it possible to create a token for which the network can store data outside of transaction/balance information?
If it is not, is there another platform I could use, or would this require a custom blockchain?


texts:
I know this could be a very basic and stupid question, just that I need clarifications for now.
Executing geth --mine results in something like below.

  Generating DAG in progress               epoch=1 percentage=33 elapsed=5m8.892s

Does geth --mine do any mining? If so, if at all mined, will the gas go to the default account?


texts: What is Geth's "light" sync, and why is it so fast?

texts:
This question is in a similar vein to the past questions about geth --fast and parity --warp.

There was a recent question where the OP wanted to do as little syncing as possible, and one of the answers suggested the following:

  Try geth --light, available since v1.5.2 . Syncs in minutes if
  not seconds.

How is this possible? What is it actually syncing?


texts:
Is the following function parameter (string name) only visible to the owner contract itself?

function myFunction(string name) private returns (bool)
{
    return true;
}

So nobody can read / see the string name?  This includes all blockchain viewers and miners.

Or is there no way to hide the values of variables in functions even if they are private?

I am looking for information on if it is possible to prevent people from reading the values of function parameters and local variables.


texts: How to automatically transfer ETH from my address to another

texts:
I want to format or configure my ETH wallet in a way that if any ETH comes into the address, it will automatically be sent to another address.

I have the feeling that my private key is being compromised, and I used the address as payment address for a website and I can't easily change to another address, so I need a way to automate any payment that comes in to that wallet to another address fast.

I've googled to the ends of the earth and haven't seen any tutorial on this. I saw something about using web3js to watch address and forward any incoming eth fast to another address as soon as it enters with a script, but the person didn't say how to do this.