texts: invalid address error on running code - solidity

texts:
Here is my code :

var Web3 = require('web3');
var fs = require("fs");
var Artifactor = require("truffle-artifactor");
var provider = new Web3.providers.HttpProvider("http://localhost:8545");
var contract = require("truffle-contract");
var temp = require("temp").track();
var path = require("path");
var requireNoCache = require("require-nocache")(module);

var toAddress = null;
var toAmount = 0;
var web3 = null;
var web3Provider = null;
var balance = 0;
var contracts = {};
var account = null;
var callback = function(error, result) {if (!error) {} else {console.log(error)}}

function getProvider() {
  if (web3 !== null) {
    web3Provider = web3.currentProvider;
    web3 = new Web3(web3Provider);
  } else {
    web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
    web3 = new Web3(web3Provider);
  }
}

function getContract() {
  var DINRegistryArtifact = require('./build/contracts/DINRegistry.json');
  contracts.DINRegistry = contract(DINRegistryArtifact);
  contracts.DINRegistry.setProvider(web3Provider);
  networkCheck();
  getNewDIN();
}

function networkCheck() {
  web3.version.getNetwork((err, netId) => {
    if (err) {
      console.log(err)
      return
    }
    switch (netId) {
      case '1':
        console.log('This is mainnet')
        break
      case '2':
        console.log('This is the deprecated Morden test network.')
        break
      case '3':
        console.log('This is the ropsten test network.')
        break
      default:
        console.log('This is an unknown network.')
    }
  });
}

function getNewDIN() {
  // console.log('getting balances...')
  web3.eth.getAccounts((error, accounts) => {
    if (error) {
      console.log(error)
      return
    }
    this.account = accounts[0]

    console.log(contracts.DINRegistry);
    contracts.DINRegistry.at("0x4c70da2e04d097cca503832dc93be7ae58134c4a")
      .then(function(instance) {
        var DINRegistryInstance = instance;
        web3.eth.defaultAccount = this.account;
        console.log(web3.eth.defaultAccount);

        return DINRegistryInstance.registerNewDIN()
          .then(function(din) {
            console.log(din);
            return din;
          })
      })
      .then((result) => {
        return result;
        // console.log('new din is ' + result);
      })
      .catch((err) => {
        console.log(err.message)
      })
  })
}

getProvider()
getContract()

The code returns the error (node:9466) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: invalid address
 on running it. I don't understand what is causing the error. I have set the web3.eth.defaultAccount which was recommended by other answers.


texts: Unable to unlock account created by php script

texts:
I'm using geth over rpc in my php script for a website.

In my script I've created a random passphrase that I store in a file so I can use it later to unlock the account.

So, to keep thing simple I create it using this code :

$myfile = fopen($basepath.hash('sha256', $somethingToIdentifyTheAccountInAUniqueWay, "w"));
$passkey = bin2hex(openssl_random_pseudo_bytes(256));
$new_address = $eth->personal_newAccount($passkey);
fwrite($myfile, $passkey);
fclose($myfile);

and then I unlock it with :

$passphrase =  fread($myfile,filesize($filepath));
$eth->personal_unlockAccount($address, $passphrase, 5);

The system works, but for some reason 6 of my approximately 30k address are unable to unlock, even manually inside the geth console using the passphrase I got from the file...

The error is :

  Error: could not decrypt key with given passphrase

Is there something I can try to unlock the account? Somewhere I can try to track the problem? We do backup each 30min and nothing have change from creation to now.  I dont know where to look anymore as everything seems fine... I even try empty passphrase or php error code that could possibly been registered in the variable in case something went wrong somewhere...


texts:
The code below produces an error:

code:

 function safeTransferFrom(
    address _from,
    address _to,
    uint256 _tokenId,
    bytes calldata _data
  )
   external
  {
    _safeTransferFrom(_from, _to, _tokenId, _data);
  }

The error is:

Invalid type for arguement in function call. Invalid implicit
conversion from bytes calldata to bytes storage pointer requested.

It would be very helpful if someone could explain both the problem and the solution!


texts: How can I retrieve the number of decimals of a token with RPC?

texts:
There doesn't seem any obligation in the ERC20 standard to provide the number of decimals anywhere, yet etherscan and all other services can automatically determine the number of decimals of a token. How is that done?

Is there an automated way (through RPC to geth) to get the number of decimals of a token defined by some contract?


texts: Slither not working with Truffle imports

texts:
Currently I have a project that needs slither run against it so I pulled down the docker image for slither as specified in the docs here https://hub.docker.com/r/trailofbits/slither/, then I shared the folder from my computer that I needed to run slither against by running the docker images. I found the whole project inside the docker image, did a solc-select to the version of solidity I am using, ran slither against the contracts folder and received the following error:
ERROR:root:None
ERROR:root:Error in contracts/
ERROR:root:Traceback (most recent call last):
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/platform/solc.py", line 367, in _run_solc
    ret = json.loads(stdout)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ethsec/.local/lib/python3.6/site-packages/slither/__main__.py", line 693, in main_impl
    ) = process_all(filename, args, detector_classes, printer_classes)
  File "/home/ethsec/.local/lib/python3.6/site-packages/slither/__main__.py", line 68, in process_all
    compilations = compile_all(target, **vars(args))
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/crytic_compile.py", line 1041, in compile_all
    compilations.append(CryticCompile(filename, **kwargs))
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/crytic_compile.py", line 124, in __init__
    self._compile(**kwargs)
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/crytic_compile.py", line 931, in _compile
    self._platform.compile(self, **kwargs)
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/platform/solc.py", line 156, in compile
    force_legacy_json=force_legacy_json,
  File "/home/ethsec/.local/lib/python3.6/site-packages/crytic_compile/platform/solc.py", line 371, in _run_solc
    raise InvalidCompilation(f"Invalid solc compilation {stderr}")
crytic_compile.platform.exceptions.InvalidCompilation: Invalid solc compilation Error: Source "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol" not found: File not found.

Error: Source "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol" not found: File not found.

This seems to be an issue with running slither against files imported by truffle.
I ran slither using truffle as a framework like this:
slither contracts/ --compile-force-framework truffle@5.1.45
And I will still receive the same import issue as before.
I have also ran slither like this and it gives the exact same error:
slither contracts/  --truffle-version  truffle@5.1.45
Any help would be appreciated.


texts:
I want to write a gambling smart contract, that will be based on time (on block number in the ethereum blockchain).

What is the best way to do some work when current network block will archive some number? For example, I want to close the current round and send all awards to winners when current network block will archive 6320132 number?


texts: How to see value of NFT / ERC 721 token on etherscan?

texts: For instance here https://etherscan.io/token/0x06012c8cf97bead5deae237070f9587f8e7a266d?a=1  is token 1 of CryptoKitties and there are some transfers, but ether value is always set to 0 ether and I guess people paid something for this. So I guess I can see that value somewhere else. The question is where can I see this?


texts:
What is the best way to know if an element is " empyt " inside a mapping ?

For example

mapping ( address => uint) balances;

If the user already used the contract there will be an address => "foo" value but if not the mapping still exist it just gives back 0x00000 or something as value.So it's never really empty.

Is there a clean way to check if the value is 0x0000 or something an user inputted for that address?( other than if balances[address] == 0x0000 )


texts:
https://github.com/ethereum/go-ethereum/blob/master/core/types/log.go#L40

// Derived fields. These fields are filled in by the node
// but not secured by consensus.
...
// index of the log in the block
Index uint `json:"logIndex" gencodec:"required"`

So next time I am looking at eth_getLogs the particular transfer could appear with different index?

I am looking for a way to uniquely identify a particular incoming transfer, many transfers can appear in the same transaction and I need a way to store them and make sure there is no duplicates when worker goes through backlog again.

Simple guess is to use unique composite index for fields: (txid, to, logIndex), but that comment in log.go is confusing me.

Parity returns is as transactionLogIndex, so may I assume it will always be the same in further responses and even if chain reorganises and tx will be included in another block?


texts: Process of getting a token on an exchange?

texts: Does anyone know what the typical process of getting a token on exchanges is?


texts: Can we freeze amount of token, amount of time with smart contract code?

texts: Is there a smart contract code to freeze amount of token amount of time. For example i have 20 ether, with a smart contract code can i freeze it 1 year, even i can not touch it? With that code our ether will freeze in our account or blocked somewhere else?


texts:
I have accomplish to add a parity node to the private network with the help of this valuable guide: https://ethereum.stackexchange.com/a/13035/4575

Now I would like to attach ethminer to my parity node, in order to do mining. Please note that my parity node successfully run on the background, as connected to my private chain. Also did rm -rf .ethash/.

[$] cpp-ethereum/build/ethminer/ethminer -F http://localhost:8545

Error:

miner  13:13:13.230|  Getting work package...
  ✘  13:13:13.231|  Failed to submit hashrate.
  ✘  13:13:13.231|  Dynamic exception type: jsonrpc::JsonRpcException
std::exception::what: Exception -32601 : METHOD_NOT_FOUND: The method being requested is not available on this server: Method not found

[Q] How could I fix the error I am facing?

=> Also when I attach geth to parity, it does not see miner.start() command.

Note:
The way I installed ethminer:

[$] git clone --recursive https://github.com/ethereum/cpp-ethereum.git
 [$] cd cpp-ethereum

Build:

[$] cmake -H. -Bbuild
[$] cmake --build build

[$]ethminer --version
 ethminer version 1.3.0 | Build: ETH_BUILD_PLATFORM/ETH_BUILD_TYPE

Please note that similar question asked but has not been covered well. ethminer Failed to submit hashrate
Thank you for your valuable time and help.


texts:
I have two contracts. One of them inherits another. Inside the parent contract I have the interface

interface Token {
    function transfer(address to, uint256 value) external returns (bool);
}

I want to override one inside the child contract to

interface Token {
    function transfer(address to, uint256 value) external returns (bool);
    function balanceOf(address who) external view returns (uint256);
}

But compiler shows DeclarationError: Identifier already declared.

Is there a way to override an interface?


texts: etherem private network stopped for unknow reasons

texts:
I have setup an ethereum private network using geth.
but it stopped as server got restarted. Here is the command that i am running.
geth -datadir . -rpc -rpcport "8545" -port "30303" --networkid 15 -rpccorsdomain "*" --rpcaddr "0.0.0.0" -rpcapi eth,web3,personal,net

Now when i try to rerun it, It is not showing any accounts now and also blocknumber is also showing as 0.
Can anyone let me what should i do to run ethereum from the block where it was terminated?


texts: Can an Erc-20 token that I create on my Quorum be integrated with any cryptocurrency exchange (for example Coinbase)?

texts: I have setup my own quorum blockchain network. If I deploy an ERC20 token contract with a coin name (say ABC), will I be able to list the coin in exchanges ?


texts: How to send message to an address using solidity contract + truffle

texts:
Here is the link to my code: https://github.com/nandinicbit1981/hello-truffle

The problem with this is: If I am sending a message: Hello World, I am getting the input field in the mined transaction as @#$R%%%Hello World.

I am not sure what is wrong with the code, I am new to ethereum. Any help is much appreciated.


texts: ClamAV finds eicar in chaindata ldb and quarantines file

texts:
What would happen if one of the .ldb files from the mist chaindata was deleted, i.e. /Users/yourname/Library/Ethereum/chaindata/060540.ldb was removed.

One of the ClamAV engines found a test virus signature file this Mist chaindata ldb and quarantined the file.


texts: I have a token I am creating that I would like to implement extra logic for in the "transfer" and "transferFrom". For example, to send a certain portion to be burnt for each transaction involving the token. My question is, would the extra gas (shouldn't be much) that this would require to call these functions be a problem for conforming to erc20 standards or for other accounts interacting with the token?


texts: Understand the functionality of one contract

texts:
I am trying to understand the following contract sample:

// Refund contract for trust DAO #16

contract DAO {
    function balanceOf(address addr) returns (uint);
    function transferFrom(address from, address to, uint balance) returns (bool);
    uint public totalSupply;
}

contract WithdrawDAO {
    DAO constant public mainDAO = DAO(0x200450f06520bdd6c527622a273333384d870efb);
    address public trustee = 0x7c81d252d9d1295058cd3620835f37e0eedd8840;

    function withdraw(){
        uint balance = mainDAO.balanceOf(msg.sender);

        if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance))
            throw;
    }

    function trusteeWithdraw() {
        trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply());
    }
}

I am a bit confused about the withdraw function. What if the first transfer transferFrom always failed due to certain reason? Would it somehow lock the fund and therefore the second fund transfer can never happen? Thanks a lot!


texts:
I am writing very basic sample contract to get the name of instructor on browser using Ganache.
Contract looks fine but web3.js page is not responding .

Contract code :

pragma solidity ^0.5.0;

contract Coursetro {

   string fName;
   uint age;

   function setInstructorName(string memory _fName) public {
       fName = _fName;

   }

   function getInstructorName() public view returns (string memory) {
       return (fName);
   }

}

Web3.js code

    Document

<link rel="stylesheet" type="text/css" href="main.css">

Coursetro Instructor

    Instructor Name
    <input id="name" type="text">

    <button id="button">Update Instructor</button>


texts: Why does Remix's jsVM show incorrect gas?

texts:
I tested the gas consumption of a contract in the jsVM, which showed consistent outputs. I then deployed it to mainnet, and the function calls consume much different amounts of gas. Is the jsVM running an old version of Ethereum?
What is the best way to test gas consumption of a contract that reflects mainnet?


texts:
myContractInstance.methods.approve('0x...', 300).call(function(error, approve){
        if(error){console.log(error)};

        if(approve){console.log("allowance for this address :"+ approve)};
        //$('#allowanceAmount').text(allowance);
})})};

Hi, what's the problem with the function? It doesn't work.. Thanks


texts:
I am trying to get the price impact of a trade in uniswap sdk and I noticed that the result from the sdk isn't accurate as what was shown on the uniswap webapp. There is  0.3 difference regardless of which token and input value. Where does the 0.3 come from?
Here is my snippet:

const amountIn = '2';
const TOKEN_ADDRESS = '0x30f271C9E86D2B7d00a6376Cd96A1cFBD5F0b9b3';

// swapTokensForExactToken
const TOKEN = new UNISWAP.Token(UNISWAP.ChainId.MAINNET, TOKEN_ADDRESS, 18)
let pair = await UNISWAP.Fetcher.fetchPairData(UNISWAP.WETH[TOKEN.chainId], TOKEN)
let route = new UNISWAP.Route([pair], UNISWAP.WETH[TOKEN.chainId])
const inputToken = web3.utils.toWei((parseFloat(amountIn) * parseFloat(route.midPrice.raw.toSignificant(6))).toString(), 'ether');

let trade = new UNISWAP.Trade(route, new UNISWAP.TokenAmount(TOKEN, inputToken), UNISWAP.TradeType.EXACT_OUTPUT)

console.log('impact: ', trade.priceImpact.toFixed()) // 1.10
// Uniswap app value 0.80


texts: How to call Internal functions ? or how to protect Withdraw and kill functions?

texts:
I had some function like withdraw and self-destruct functions set as internal, but I can't call them from "Mist", then I turned them to public but I set the modifier :

modifier isOwner() {
if (msg.sender != owner) _;
}

Then added isOwner to my functions

function kill() isOwner public {
    selfdestruct(beneficiary);
}

But when I try to call it from a subaccount (not the owner account) it works!


texts: Loading smart contract x with tokens; sending eth to smart contract x; receiving tokens for that eth

texts:
Hello dear Eth community,

I am a complete noob, please go easy on me ;) I am an IT teacher and I want to create a reward system for my class for a game that we play weekly. The game is not blockchain related - basically it is a quiz which when solved would open an ethereum address and an amount of ETH to sent to the address. E.g. “Address is 0x337hj377v..; you can now transfer 2ETH to get your “game reward tokens”.
Once individual sends that ETH, he receives back the appropriate amount of game tokens e.g. 1eth = 0.1 game tokens.

We then count who collected the most and determine the winner.

Again, I am completely new to developing smart contracts and I have some challenges.

I am working on a test net and already created my “game reward tokens”.

Next what I am struggling to do is to create a smart contract which would accept my “game reward tokens” and then would send it to users, to whoever is sending ETH, lets say 1ETH = 10 “game reward tokens”.

So “game reward tokens” >> moved to smart contract address >> sits there until someone sends the ETH. If 1eth sent from address x >> 10 game reward tokens sent to address x.

Is there a change anyone could help me out? Maybe there already were similar discussions and you could point me there.

Would appreciate any suggestions,
Cheers!


texts:
I can´t execute geth account import command in gethjs console. What is the comand equivalent?? any help??

Thx


texts: Release ERC-20 tokens that is used, but not on a Blockchain?

texts:
I would like to know the following: is it possible to generate and release ERC20 tokens that can be used to acces a service that is not on a Blockchain?

E.g. tokens are being sold but one can use it at a website to acces a specific service

Would like to hear what you guys think!


texts: Why using Merkle Patricia trie for keeping transactions and receipts instead of Merkle trie?

texts:
Using Merkle Patricia trie for keeping Ethereum states has the advantage of fewer changes in the data structure during the updates in the states compared to Merkle trie.

But what is the advantage of using Merkle Patricia trie for keeping transactions and receipts of Ethereum while there is no update in the stored transactions? Why does not Ethereum use Merkle trie for transactions just like Bitcoin ?


texts: How to use signed message and prevent replay attack when using openzeppelin ERC20 contract?

texts:
openzeppelin ERC20 provide building blocks to quickly build ERC20 smart contract. Here is an simple example:
pragma solidity ^0.4.24;

import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";

  contract TutorialToken is ERC20 {
    string public name = "TutorialToken";
    string public symbol = "TT";
    uint8 public decimals = 2;
    uint public INITIAL_SUPPLY = 12000;

    constructor() public {
      _mint(msg.sender, INITIAL_SUPPLY);
    }

}

I went through the ERC20 classes and didn't see security measure to prevent, such as, replay attack. Shall I as developer add the security measure on my own? How the smart contract above fend off replay attack and prevent impersonation (pretend as someone else to do transaction)?


texts:
I'm looking for a better testnet environment for solidity development. My current flow at the moment is kinda slow:

Asking for ETH on testnet faucet.
Just deploy my smart contract to work and test.
Wallet is getting reset after like 1 hour or so.
Beggin for ETH again, now get blocked for spamming ( ropsten, rinkeby ).

Is there a better way to do this, I'm curious, this is like a 90s development environment. I'm thinking about building a private testnet, however, if there is any service we can use?
Thanks in advance.


texts:
I want to get the value that my smart contract returns in javascript.

Here is the contract. (version 0.4.25 - web3 version 1.2)

pragma solidity ^0.4.25;
contract SimpleStorage {

    uint public storedData;
    event numberSaved(uint number);

    constructor(uint initVal) public {
        storedData = initVal;
    }

    function set(uint x) public{
        storedData = x;
        emit numberSaved(storedData);
    }

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

}

Now how do I get the value the event returned?

I tried with:

mySmartContract.events.numberSaved();

mysmartContract.once('numberSaved', function(error, event){ console.log(event); });

This one returns null

What am I doing wrong?

It works in Remix.


texts:
In solidity version 0.5.8, it is giving me the error that I have an uninitialized storage pointer. How do I fix this error, and if your answer is by making it a memory variable instead of storage variable, then how do i append a value instead of pushing?

my code is:

function enRouteList(uint rideNumber) public view returns(address[] memory) {
Ride storage curRide = rides[rideNumber];
address[] storage addressesEnRoute;
for(uint i = 0; i < curRide.passengerAccts.length; i++) {
  if (keccak256(bytes(curRide.passengers[curRide.passengerAccts[i]].state)) == keccak256("enRoute")) {
    addressesEnRoute.push(curRide.passengerAccts[i]);
  }
}

Thank you


texts: Geth determine synchronisation mode from console

texts:
How can I get know using geth console was my database synced in fast or full mode ?

UPD
Its not the same as checking a process ps ux | grep geth. I know that i have started geth without sync parameter - i just to get know what a difference from client side on this state.


texts: I can no longer access old blocks via RPC in full syncmode?

texts:
I have a private network based on geth v1.9.25. I upgraded from v1.8.27. Recently, I saw that I'm unable to access the previous blocks at all. Like, e.g. eth.getBlockByNumber(1) gives me null, even though I can get the latest blocks just fine. I have a few questions regarding that:

Does this have anything to do with the ancient deep freezing of the previous blocks? If so, is it possible to
a,  disable it (can't find anything relevant in the configurations) and
b, recover/bring the frozen blocks back/thaw them out into active db from the ancient db? I'm looking into the debug options but I can't seem to find anything like what I'm looking for.

Does this mean that "full" sync doesn't keep track of the blocks? I understand that gcmode=archive is required for complete state persistence but I was under the impression that syncmode=full will at least persist the entire blockchain (all blocks). I have read up on EVM tracing and haven't found anything contradictory to my understanding.

Update @ Apr 29
This doesn't seem to be normal behavior for geth. I've confirmed with experiments with geth v1.9.25 and rinkeby chain. So there's something wrong with my version (I've brought in consensus from Quorum to v1.9.25).


texts: How to create forwarder wallet in Ethereum?

texts: I have more than one ETH wallet. I want to automatically combine these wallets into one wallet. For example, when I get an ETH in wallet 0x1, I want it to automatically transfer it to wallet 0x2. Can I do this with a smart contract? Or how can I do it?  Can you help me?


texts: Transfrerring Ether onto exchanges bought in aud

texts:
Hello and thanks in advance for your assistance.

I am in the process of transferring my ether bought in AUD from Coinspot and there third party affiliate wallets into myetherwallet or the like (as nano ledger s is sold out) to manage my own affairs and I was wondering how I then go about using those ethers on Poloniex or Kraken or any other exchange that would support the transfer of my ether coins purchased with fiat aud for the purpose of converting those coins back into aud? (As Coinspot now charge 6% on transfers (which is still a heck of a lot better than their original 10% spread. High fees and terrible service seems the norm over there)

Any recommendations you could may would be much appreciated as my knowledge of trading on exchanges for alt coins and fiat currency is limited, not through lack of effort but an extremely complicated space with a lot of misinformation.

Thanks

Mark


texts: How to detect public address with web3 py on dapp level?

texts:
Let's say I deploy a voting app with web3py as the backend.
Now an arbitrary user wants to cast a vote.
Given that web3py cannot be integrated with metamask, what is the conventional way to detect the address of a user?
If I had web3 js running in the backend, I believe this would have been simpler since it can easily integrate with metamask and I'd have the user's public details.
How do I accomplish the equivalent with web3 py?


texts: Is it possible to use MetaMask for a private consortium on Ethereum?

texts:
Assuming we create a private consortium chain over Ethereum and we want to use MetaMask for storing the keys and signing transactions to send the tokens belonging to this private consortium. Apparently, MetaMask only support the Ethereum mainnet along with three following testnets:

Ropsten
Kovan
Rinkeby

So, is it possible to use MetaMask for holding the keys and signing the transactions to send the tokens belonging to this private consortium that has been created over the Ethereum? And if yes, how to do?


texts: Is it possible to generate a transaction request that populates all tx fields, except signature?

texts: Does Ethereum have the basic functionality to allow a payment request to be generated which the user can then choose to accept and sign?  The application for this is a token auction where the payer's assent to the contract is included in the memo field.  Therefore, I wish to be able to pre-populate the memo field in a payment request.


texts: Behavior of a contract created from another contract

texts:
If I call getterA() from contract B the result is 0. Can someone explain me why? In my opinion it has to be 2, because I set it to 2.

pragma solidity ^0.4.24;

contract A {

    uint private a;

    function setA(uint _a) external { a = _a; }
    function getA() external view returns(uint) { return a; }
}

contract B {
    A a;

    constructor() public {
        a = new A();

        a.setA(2);
    }

    function getterA() public view returns(uint) { a.getA(); }
}


texts:
In the contract for EOS crowdsale:

https://etherscan.io/address/0xd0a6e6c54dbc68db5db3a091b171a77407ff7ccf#code

line 469:

  assert(address(EOS) == address(0));

"assert" will test if both sides of the expression are equals, but:

1) address(EOS) is the address of the contract, right ?
2) what is address(0) ?
3) why to compare those values ?


texts: What does the beacon chain deposit contract ceremony entail?

texts:
To bootstrap an Ethereum 2.0 beacon chain, the deposit contract has to be deployed on the proof-of-work legacy chain. For the beacon-chain mainnet, we are talking about a ceremony potentially involving a number of participants.

  The original plan was to deploy this in a ceremony at DevCon [...]

My questions are,

what is required to successfully deploy a deposit contract?
what are the steps to conclude a ceremony? What does the ceremony entail?
can anyone participate? Who can participate?
how many deposits are required to bootstrap a beacon chain?

This looks like multiple questions, but it's mainly one question broken down into different thoughts. See also this article.

  However, launch can only occur once a minimum number of deposits is registered and there are at least three production ready clients.

Would this also apply for testnet launches?

My question is of a practical nature, as I want to assist bootstrapping different ETH 2.0 beacon-chain testnets. Would a testnet even require a ceremony or can I just use fake deposits? Any pointers are much appreciated.


texts: Problem with Stack too deep, try removing local variables

texts:
code:
 function collect(address addr)  public returns (uint256){
        Deposit[] storage invests = users[addr].deposits;
         uint256  i = 0;
         uint256 profit = 0;
        while (i < invests.length){
            Deposit storage  invest = invests[i];
            if (invest.lastDepositTime < invest.depositTime.add(200 days)){
                 uint256  remainedTime = BOX_PERIOD[0].sub(invest.lastDepositTime.sub(invest.depositTime));
              //  timeSpent = now.sub(invest.lastDepositTime);

                if (remainedTime > 0){

                   uint256 a;
                   uint256 b;
                   uint256 c;
                   uint256 d;
                   uint256 e;
                   uint256 f;
                   uint256 g;
                   uint256 timespend;
                   uint256 i2;
                   uint256 j;
                   uint256 k;
                   uint256 h;

                  a=profit;
                  b=24;
                  c=100;
                  d=60;
                  e=100;
                  f=60;
                  g=100;

                  h=10000000;
                  timespend=now.sub(invest.lastDepositTime);

                profit = a.div(b).mul(c).div(d).mul(e).div(f).mul(g).div(h);

I got error:
browser/test1.sol:76:30: CompilerError: Stack too deep, try removing local variables. profit = invest.amount.div(24).mul(100).div(60).mul(100).div(60).mul(100).div(1000000).mul(timeSpent); ^----^
This is only if add .mul(timeSpent),other way works.
I have tried too uint[8], uint[256] I got data location bust be storage or memory for variable but still not works..


texts:
I am trying to iterate through the ethereum ldb files. When I run this code my iterator believes there is nothing stored on the ropsten's testnet blockchain. There are no errors, and the iter gets to the for loop's test for whether it hasNext(). So it loads the DB properly, just doesn't recognize the keys.

I am using Dain's LevelDB API.

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    Options options = new Options();
    options.createIfMissing(false);
    ReadOptions ROoptions = new ReadOptions();
    try {
        DB db = factory.open(new File("chaindata"), options);
        ROoptions.snapshot(db.getSnapshot());
        try {
            // Use the db in here....
            System.out.println("Creating itr");
            DBIterator iterator = db.iterator(ROoptions);
            try {
                System.out.println("Testing itr");
                for (iterator.seekToFirst(); iterator.hasNext(); iterator.next()) {
                    String key = asString(iterator.peekNext().getKey());
                    String value = asString(iterator.peekNext().getValue());
                    System.out.println(key + " = " + value);
                }
            } finally {
                // Make sure you close the iterator to avoid resource leaks.
                iterator.close();
            }

        } finally {
            // Make sure you close the db to shutdown the
            // database and avoid resource leaks.
            db.close();
        }
    } catch (FileNotFoundException E) {
        System.out.println("File not found! " + E);
        throw new FileNotFoundException();
    }

}

}


texts: How can I check if a contract has self-destructed in Solidity?

texts:
I have got a problem: I have a contract factory that creates some temporary contracts. I want every contract to exist for about 5 days, afterwards, it self-destructs. However, I want to create a directory that stores the addresses of all temporary contracts and lists them for you. Registering the temporary contracts to the directory contract is no problem I just don't know how I can find out if a contract does still exist so that the destroyed contracts are not listed anymore.

Thank you in advance.


texts: How to interact with Smart Contracts (for test)

texts:
MY question is related to question 1 in:

How to interact with a smart contract in practice (for free)? A bigger picture!

But the difference is that here I need more details.

I know I can compile a smart contract on Remix. I need to know how exactly I can interact with the smart contract.

Assume I have very simple smart contract; I have the following questions:

Question 1: How can  I write a transaction that calls (or interacts with) the contract?

Question 2: Is there any online service that allows me to do that (for free)?

I tried to get some free Ether from here, and I installed metamask, but my account shows zero Ether, so I couldn't get any Ether for the test.

Also, I don't know how to use the Ether for the test even if I have some.


texts: How can Creators update or edit there Contracts after they are craeted.

texts: My question is how do people change things in there contract after they have published it, since the ICO contract and the normal contract of a token are usually the same, how do some people have the option to extend or shorten there ICO or change things in there contract without making a new contract and changing the contract address. Working in Remix Solidity IDE. Like doesnt the whole contract have to be finished in the same block? how can someone make a new contract and merge it (i guess..?) into the original token contract.


texts:
I have a online shop where users can recieve ETH and do shopping.
So to have a secure wallet, I have created an offline service which generates xpub and xpriv which I  use to generate addresses in my online service.

I am using xpub in my online service to genreate addresses for users and using xpriv in my second offline service to send transactions.

Here is a code which generates xpub

const hdkey = require('ethereumjs-wallet/hdkey');
const bip39 = require('bip39');

var seed = bip39.mnemonicToSeed('my_mnemonic_phrase', 'my_password');

var chain = hdkey.fromMasterSeed(seed);

var xpub = chain.publicExtendedKey();

var xpriv = chain.privateExtendedKey();

Than using xpub in my online service I am generating addresses for users

const generate = async (index) => {

    const xpub = process.env.ETH_XPUB;

    const hdk = hdkey.fromExtendedKey(xpub);

    index = index || 0;

    const child = hdk.deriveChild(index);
    const w = wallet.fromExtendedPublicKey(child.publicExtendedKey());

    return w.getAddressString();
};

So all is ok, but I in my offline service I also have a service which should send all coins to my own account from generated addresses.

Here is my second service

onst ethTx = require('ethereumjs-tx');
const Web3 = require('web3');

const web3 = new Web3(
    new Web3.providers.HttpProvider('http://localhost:8545')
);

//Verify connection is successful
web3.eth.net.isListening()
    .then(() => console.log('is connected'))
    .catch(e => console.log('Wow. Something went wrong'));

const params = {
    nonce: 0,
    to: my_address,
    value: '0.1',
    gasPrice: 5000000000,
    gasLimit: 21000,
    chainId: 3
};

const privKey = new Buffer('xprv_MY_XPRIV_KEY','hex');

const tx = new ethTx(params);
//Signing the transaction with the correct private key
tx.sign(privKey);

const serializedTx = tx.serialize();

Web3.eth.sendSignedTransaction(
    `0x${serializedTx.toString('hex')}`,
    (error, result) => {
        if (error) { console.log(`Error: ${error}`); }
        else { console.log(`Result: ${result}`); }
    }
);

But in this case I am getting an error look like this

  private key length is invalid

I am using xpriv as a private key . Is this ok ? or where my mistake ?
What I need to add/change to  send transactions?

Any suggestions would be much appreciate.


texts: Why am i getting "removed tx from pool: low tx nonce or out of funds"?


texts: Changing supply of an issued ERC20 token?

texts: If I was to create my own ERC20 token, would I be able to change my token supply down the line? What other solutions let me adjust token supply if ERC20 isn't an option?


texts:
Here are smartcontract A and B

B has BuyService function. User need to call this function to get service.
A has token(erc20) enough. If user call A without tokens, then A call B and pay tokens on behalf of user. B receive tokens from A and give service to user.
B is very regular and simple standard contract.

Can contract A work? If so, can any contract be interacted with A?


texts: Weird behaviour with prettier in VS Code

texts:
So Prettier is behaving quite weirdly for me. Lets take this simplified interface:
interface Token {
  function getTotalSupply(address _market, TokenType _tokenType) external view returns (uint256);
  function mint(address _to, uint256 _amount, TokenType _tokenType) external;
}

After formatting it gets formatted to this:
interface Token {
  function getTotalSupply(address _market, TokenType _tokenType) external view returns (uint256);

  function mint(
    address _to,
    uint256 _amount,
    TokenType _tokenType
  ) external;
}

I want both functions to stay on one line. The printWidth option does not seem to be the issue here, as the first function is actually longer than the second one and does not line break. The difference seems to be that the second function has more arguments and that every function with more than 2 arguments gets split up.
Here is my .prettierrc
{
  "overrides": [
    {
      "files": "*.sol",
      "options": {
        "printWidth": 160,
        "tabWidth": 4,
        "useTabs": false,
        "singleQuote": false,
        "bracketSpacing": false,
        "explicitTypes": "always"
      }
    }
  ]
}

How can I fix this?


texts:
I was playing in remix just to concretize my understanding of Solidity linearization, and got a result I didn't expect and can't rationalize. Why does AC_BA.go() return 3?

(Please scroll to the bottom of the code below.)

pragma solidity ^0.4.24;

contract A {
    function go() public pure returns (uint out) {
        out = 1;
    }
}
contract B {
    function go() public pure returns (uint out) {
        out = 2;
    }
}
contract C {
    function go() public pure returns (uint out) {
        out = 3;
    }
}

// returns 2 as expected
contract AB is A, B {
    function go() public pure returns (uint out) {
       out = super.go();
    }
}

// returns 1 as expected
contract BA is B, A {
    function go() public pure returns (uint out) {
       out = super.go();
    }
}

// returns 3 as expected
contract AC is A, C {
    function go() public pure returns (uint out) {
       out = super.go();
    }
}

// refuses to compile, can't linearize, ok
//
// contact AC_A is AC, A {
//     function go() public pure returns (uint out) {
//       out = super.go();
//    }
// }

// compiles, returns 2, from AB
contract AC_AB is AC, AB {
    function go() public pure returns (uint out) {
       out = super.go();
    }
}

// compiles, returns 3, why???
contract AC_BA is AC, BA {
    function go() public pure returns (uint out) {
       out = super.go();
    }
}


texts: Solidity extract a sub bytes32 from a source bytes32

texts:
I need to extract a sub-bytes32 from a source bytes32 so I wrote this solidity function:

function bytesOf(bytes32 source, uint start, uint count) private pure returns(bytes32) {
    bytes32 result;
    uint end = start + count;
    for (uint i = start; i < end; i++) {
        result[i - start] = source[i];
    }
    return result;
}

Unfortunately that does not work and I get the error

TypeError: Expression has to be an lvalue.
    result[i - start] = source[i];
    ^---------------^

How would I do this?


texts:
I'm trying to create a contract object with web3.

      var contract_abi = result['contracts']['Test']["interface"];

//[{"constant":false,"inputs":[],"name":"inc","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"odd","type":"bool"},{"indexed":false,"name":"x","type":"uint256"}],"name":"Incremented","type":"event"}];

var contract = new web3.eth.Contract(contract_abi);

However I keep getting the error:

Uncaught Error: You must provide the json interface of the contract when instantiating a contract object.

However if I copy my contract_abi console output and directly create a variable like so:

var contract_abi =
[{"constant":false,"inputs":[],"name":"inc","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"odd","type":"bool"},{"indexed":false,"name":"x","type":"uint256"}],"name":"Incremented","type":"event"}];

It works. Whats going on? Thanks


texts: When 2 blocks or more are distributed at the same time, but the longest one delayed

texts:
I have a problem understanding the concept of handling two or more blocks that distributed at the same time (in the blockchain network).

As far as I understood, When I get 2 or more blocks at the same time, the miner starts to create a new block on the top of the longest block he received.

But what if user1 got BlockA and BlockB (BlockB is the longest one), and user2 got BlockA, and BlockB is delayed (it takes time to send this block to user2 because of many reasons), so eventually user2 sees only BlockA at the moment, and starts to build a block on a top of this block, while user1 builds the block on top of BlockB.

I don't fully understand how blockchain synchronizes the blocks properly. I need a better explanation.


texts: Need Help with a University Project to make a DApp

texts:
I want to make a DApp which stores information of people who have taken the COVID vaccine.
Information to be stored will be:

Name of the Person
Date of Birth
Some Form of PIN Provided by the Government
Photograph of the Person
Receipt which is Received after taking the vaccine
(Please suggest any other info which can be stored)

Since there is a growing number of Fake Covid Vaccine Cards/Certificates I thought of making this project.
After the Data is stored, the person can then present this as a proof for travelling, booking flights, etc.
I am new to developing DApps and I don't know how to go about starting this project. Any advice would be helpful.


texts: What is the MetaMask workaround if Web3 is deprecated

texts:
While using MetaMask, adding Web3 to a Javascript program displays the following message in the Chrome console:
"MetaMask: web3 will be deprecated in the near future in favor of the ethereumProvider"

Should I continue creating a website that requires MetaMask, if Web3 will be deprecated in the near future?

Is there a workaround, or is there another extension that allows Javascript to interact with Ethereum in the Chrome browser?


texts: How to create an automatic smart payment ERC20 system

texts:
how can I create an automatic smart contract to send tokens ,if a user send ETH to the smart contract and also to bee able to recover ETH from the smart contract and tokens too thank you.
To explain brief, if Bob sends 1ETH he receives automatic 100tokens in ERC20 and the contract owner can withdraw ETH from the smart contract and tokens (incase tokens are mistakenly sent).


texts: Undefined in truffle-contract initialization

texts:
why I always have undefined from

contract(_contract).setProvider(this.web3Provided);

Component:

import React, {Component, PropTypes} from 'react';
import { default as Web3 } from 'web3';
import { default as contract } from 'truffle-contract';
import Products from '../../build/contracts/Products.json';
import SimpleStorage from '../../build/contracts/SimpleStorage.json';
import TruffleConfig from '../../truffle-config';

class TruffleContractWrapper extends Component {

  constructor(props) {
    super(props);
    this.web3Provided;
    this.web3Inizialize = this.web3Inizialize.bind(this);
    this.contracts = [
      Products,
      SimpleStorage
    ];
  }

  componentWillMount() {
    this.web3Inizialize();
  }

  web3Inizialize() {
    let { NODE_ENV = 'development' } = process.env;
    let {
      host = 'localhost',
      port = 8545 } = TruffleConfig.networks[NODE_ENV];
    let web3Location = `http://${host}:${port}`;

    if (typeof web3 !== 'undefined') {
      // Use the Mist/wallet provider.
      // DEVELOPER NOTE: removing the next commented line will break the app
      // eslint-disable-next-line
      this.web3Provided = new Web3(web3.currentProvider);
    } else {
      // DEVELOPER NOTE: What happens in the wild if the
      // user does not have a browser based wallet? What happens
      // if the Web3 object cannot be initialized with the httpProvider
      // given from the loction in the truffle-config file?
      this.web3Provided = new Web3(new Web3.providers.HttpProvider(web3Location));
    }
  }

  buildTruffleContracts() {
    let contracts = {};

    this.contracts.forEach( (_contract) => {
      let {contract_name = ''} = _contract;
      contracts[contract_name] = contract(_contract).setProvider(
        this.web3Provided
        );
    });
    return contracts;
  }

  getChildContext() {
    let contracts = this.buildTruffleContracts();
    return { contracts, web3: this.web3Provided };
  }

  render() {
    return <div>{this.props.children}</div>;
  }
}

TruffleContractWrapper.childContextTypes = {
  contracts: React.PropTypes.object,
  web3: React.PropTypes.object
};

export default TruffleContractWrapper;

Is like a loop problem, this block of code works:

componentWillMount() {
    this.web3Inizialize();
    let provider = new Web3.providers.HttpProvider('http://localhost:8545');
    var meta = contract(Products);
    meta.setProvider(provider);
    console.log(meta.deployed().then((poppo) => {
      console.log(poppo);
    }));
  }


texts: How to get money out of a smart contract

texts:
I need some help unterstanding how to communicate with a smart contract.
Here is my story:

I gambled 0.2 eth on idice.io
I actually won another 0.2 eth. They said they will return the amount ASAP.

Here is the contract:

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

But now I have 0.4 eth stuck in some internal transaction

Will this money every arrive? Or is this some sort of scam?

In Mist I found a function like this:

But it doesn't work. Can you guys help me out?

Thanks.


texts:
I am trying to take user input strings and convert them to bytes32 and bytes5 for a contract built in Solidity 5.11, I tried 32 and 5 character long random strings respectively however they are not working, is there an inbuilt function for web3 to convert Strings to bytes (either 32 or 5) like web3.utils.fromAscii can be used to generate appropriate addresses from strings?
console.log(addressing("address");
console.log(bitify32("data"));
console.log(bitify5("key"));
function addressing(input) {
    let zeros = "0";
    let input = web3.utils.fromAscii(input);
    if (input.length < 42) {
        let remainder = 32-input.length;
        for(let i = remainder-1; i > 0; i--) {
            zeros += "0";
        }
    }
    let inputZerod = input+zeros;
    return inputZerod;
}

function bytify32(input) {
    let zeros = "0";
    let input = web3.utils.fromAscii(input);
    if (input.length < 32) {
        let remainder = 32-input.length;
        for(let i = remainder-1; i > 0; i--) {
            zeros += "0";
        }
    }
    let inputZerod = input+zeros;
    return inputZerod;
}

pragma solidity ^0.5.11;

contract bytesTest{

  mapping(address => BytesStruct) testBytes;

     struct BytesStruct{
        address stringAddress;
       bytes32 string1;
       bytes5 string2;
     }

     function getByteStrings(address _stringAddress) view public returns(bytes32, bytes5){
         return(testBytes[_stringAddress].string1, testBytes[_stringAddress].string2);
     }

  function addByteString(address _stringAddress, bytes32 _string1, bytes5 _string2) public{
    testBytes[_stringAddress].string1 = _string1;
    testBytes[_stringAddress].string2 = _string2;

  }

}


texts: How much time until the state data is PoW validated when using parity warp?

texts:
Ethcore claims parity --warp  only takes one minute to sync the chain. I tried myself and it indeed takes around 2-3 minutes on my machine with a slightly bad connection.

 0 ✓ user@hoster ~ $ parity --mode passive --db-compaction ssd --pruning fast --warp --cache-size 4096
2016-11-30 12:21:26  Starting Parity/v1.4.5-beta-UNKNOWN-UNKNOWN/x86_64-linux-gnu/rustc1.13.0
2016-11-30 12:21:26  State DB configuation: fast
2016-11-30 12:21:26  Operating mode: passive
2016-11-30 12:21:26  Configured for Frontier/Homestead using Ethash engine
2016-11-30 12:21:32  Syncing snapshot 1/69         #0    4/10/25 peers      3 MiB db    7 KiB chain  0 bytes queue   10 KiB sync
                     [...]
2016-11-30 12:23:43  Syncing snapshot 68/69         #0    1/14/25 peers      3 MiB db    7 KiB chain  0 bytes queue   10 KiB sync
2016-11-30 12:23:48  Syncing #2720000 e0a7…f90a      0 blk/s    0 tx/s   0 Mgas/s       0+    0 Qed   #2720000    8/11/25 peers    0 bytes db  656 KiB chain  0 bytes queue   12 KiB sync
2016-11-30 12:23:56  Syncing #2720149 3f85…a2c7    120 blk/s  979 tx/s  40 Mgas/s       0+  613 Qed   #2721511    8/14/25 peers     23 MiB db    2 MiB chain    5 MiB queue    1 MiB sync
2016-11-30 12:23:57  Imported #2721511 3702…acd3 (0 txs, 0.00 Mgas, 1.02 ms, 0.51 KiB) + another 3 block(s) containing 4 tx(s)
2016-11-30 12:24:11  Imported #2721512 e6c5…2d67 (0 txs, 0.00 Mgas, 0.74 ms, 0.51 KiB)

But, how much time does it take until the state data is PoW validated? And, is it validated at all?


texts: How do I tell mist not to download geth, but use the system-wide version?

texts:
I run Manjaro Linux which is based on Arch, so I have a very up-to-date system version of geth.

How do I tell mist not to download a per-user version of geth, but use the system-wide version instead?


texts: Modifier causing "invalid opcode" in TestRPC

texts:
I have a token and crowdfund that works fine, except in tests. I can use all the methods, but I get invalid opcode on any of them that have a call to another contract that has a modifier on that function.

For instance, if I have ContractA, ContractB, and ContractC, and I call ContractA from addressA, and ContractA has a modifier to only accept calls from addressA, and all the functions on ContractA call out to ContractB and the functions on ContractB all have modifiers to only accept calls from ContractA.

This works great in practice, breaks when I run my tests. If I remove the modifiers, the tests run. Is this a known bug? I can confirm the modifiers all use msg.sender - perhaps testrpc isn't forwarding this correctly?


texts:
I got no accounts loaded with code

import Web3 from "web3";

let web3;

// typeof check if variable exists
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {

    web3 = new Web3(window.web3.currentProvider);
    console.log("Metamask used");
    const getAccounts = async () => {
        const accounts = await web3.eth.getAccounts();
        return accounts;
    };

    console.log('first account is ', getAccounts()[0]);
} else {
    console.log('not Metamask');
    const provider = new Web3.providers.HttpProvider(
        'https://rinkeby.infura.io/v3/foo'
    );
    web3 = new Web3(provider);
}

export default web3;

And I got console log:

Metamask used
first account is `undefined`

So I can assume metamask is injected in the window, however no accounts were loaded. (I absolutely had logged in my metamask)

Version:

"next": "^4.1.4",
"web3": "^1.0.0-beta.35"

Have someone encountered the same problem, thanks in advance!


texts:
Assuming we have two parties (A & B). How the following scenario be achieved using smart contracts?

User A will deposit some funds (x coins).
user A can receive penalty funds from user B, So user B will also deposit funds (y coins).

if, within certain time (time locked),  B provides a preimage to a certain hash value. Then, he gets the x coins and the B coins (y coins) back. otherwise A can get his coins back and also the B'coins (y coins) ?

A related nice answer is in here:

1.Zero knowledge contingent payment on etherum?

Is the following scenario doable by a smart contract?


texts: Solidity compile Error: Expected primary expression help

texts:
Compile Error

I cannot understand why this happens.I copied and pasted this code from https://zoom-blc.com/how-to-create-first-dapp

Error message is as follows:

truffle(develop)> compile
Error parsing /Users/akitasatoshi/pet-shop-tutorial/contracts/Adoption.sol: ParsedContract.sol:10:3: ParserError: Expected primary expression.
  　 return petId;
  ^

The code is as follows:

pragma solidity ^0.4.23;

contract Adoption {

  address[16] public adopters;

  function adopt(uint petId) returns(uint) {
    require(petId >= 0 && petId =< 15);
    adopters [pedId] = msg.sender;
    return petId;
  }

  function getAdopters(uint) public returns (address[16]) {
    return adopters;
  }


texts: Why in some contracts I see: If (condition_1 & 0xfffffffffffffff...)?

texts:
I'm looking at the code of some smart contracts and I've seen somewhere where the code is something like:
if (msg.sender == storage[0x00] & 0xffffffffffffffffffffffffffffffffffffffff)
From my limited understanding, 0xfffff is always true, isn't it? What is the reason of having it there? In other places I see 0xff instead of the whole f deal, is there any difference?
Thanks


texts: Initial Genesis difficulty on an ethereum clone

texts:
I've created an ethereum clone that i hope someday can become a public blockchain. This is working good so far, however i have a question regarding the initial setup for once i set this live.

If i redo my chain (With the current difficulty on genesis.json of 0x20000) the blocks will be mined very fast and my only miner gets "Rich" with coins.

If this was a real case scenario and i wanted to launch this blockchain to the public would that be the only parameter i would have to set to ensure the first miners dont get ridiculously weatlhy?

Should i set it to the same difficulty that Ethereum would have at that same time and let the algorithm adapt by itself? or another value?

My goal is to prevent "whales" being created straight from the second the chain is launched.


texts: Is next formula to calculate TX cost in euros correct?

texts:
I want to create a transaction in the main-net. Each transaction modifies 4 * 32 bytes of storage. It also creates a event with 3 indexes and 150 bytes of real log.

Note: I arbitrarily take 300 Euros/Eth.

The calculus made follows:

Cost in gas calculus:
  Cost  TX      :    21000 gas/TX      * 1TX        = 21000
  Cost storage  :    20000 gas/32bytes * 4*32 bytes = 80000
  Cost   event  :      375 gas/LOG     * 1LOG       =   375
  Cost   Topic  :      375 gas/topic   * 3topic     =  1125
  Cost  byte/log:        8 gas/byte    * 150 bytes  =  1240
                                                    -------
                                            TOTAL    103740 gas
gas to Euro calculus:
  103740 (TOTAL) gas * 0.000000032 Eth/gas * 300 Euros/Eth = 0.995904 Eu

The 0.000000032 Eth/gas is taken from the average gas price at http://ethgasstation.info/

The final price, 0.996Eu, looks extremely costly, so I'm thinking there is a mistake in my calculus or something else that scapes to my understanding.

I base my calculus/data in next references:

What's cheaper — contract storage | log data | transaction input?
How are Ethereum transaction costs calculated?
http://ethgasstation.info/


texts: How to create a web3 connection in react interface?

texts:
I have created a simple login and register interface using react js and want to connected through web3 or any other method with a smart contract to stored the registered user's data on the blockchain and verify their login credentials to gain access. I'm using ganache and metamask to create an test environment for my application. Can someone help me or guide me to specific articles/tutorial to use the functions of the smart contract to store and get data ?
my smart contract is
pragma solidity ^0.5.0;

contract register {
    uint public userCount = 0;
    uint i=0;
    bool verUser = true;
    mapping(uint => user) public users;

    struct user {
        uint id;
        string username;
        string email;
        address useraddr;
        string password;
        bool loggedIn;
    }

    event userCreated(
      uint id,
      string username,
      string email,
      address useraddr,
      string password,
      bool loggedIn
    );
   event userLoggedIn(
       uint id,
      string username,
      address useraddr,
      string password,
      bool loggedIn
       );

function createuser(string memory _username, string memory _email, string memory _password) public
    verification(_username, _password, userCount) {
        require(bytes(_username).length > 0);
        userCount ++;
        users[userCount] = user(userCount, _username, _email, msg.sender, _password,false);
        emit userCreated(userCount, _username, _email, msg.sender, _password, false);
    }

 function loginuser(string memory _username,  string memory _password) public
    logInVerified(_username, _password, userCount) {

        emit userLoggedIn(userCount, _username,  msg.sender, _password, true);
    }

modifier verification(string memory _username,string memory _password, uint _userCount){

 user  memory p = users[i];
 for (i=0; i<userCount; i++)
    {
     if((keccak256(bytes(_username))) == keccak256(bytes(users[i].username)) ||
    (keccak256(bytes(_password))) == keccak256(bytes(users[i].password)) ){

        verUser = false;
    }
    else{
        verUser = true;
    }
}
require(verUser == true, 'username or password already exists, please try again');
_;
}
modifier logInVerified(string memory _username,string memory _password, uint _userCount){

 user  memory p = users[i];
 for (i=0; i<userCount; i++)
    {
     if((keccak256(bytes(_username))) == keccak256(bytes(users[i].username)) &&
    (keccak256(bytes(_password))) == keccak256(bytes(users[i].password)) ){

        verUser = true;
    }
    else{
        verUser = false;
    }
}
require(verUser == true, 'Wrong username or password');
_;
}
}


texts: Does an entire transaction revert when throw occurs?

texts: I have a contract that calls another contract that calls another. If there is a throw (or out-of-gas error) that occurs somewhere in the second contract, does the entire transaction get reverted or is it just the stuff in the second and third contract that does, while the execution from the first contract still stands?


texts: How to call smart contract from html/Javascript

texts: I want to have an html/Javascript code interact with a smart contract. Can someone  please outline the basic/high level steps? I am seeing too many things spread across the net,  finally confusing.


texts: Why does truffle console work fine with testrpc but truffle serve isn't finding accounts?

texts:
I'm running testrpc on the default port 8545.

I run truffle console and test with: web3.eth.sign(web3.eth.accounts[0], web3.sha3("123"))

This works fine. According to docs the sign method only works if the account is unlocked, so it seems I should be all set.

But after successfully running init/compile/migrate, I run truffle serve and when I go to the web page on localhost:8080, I get this popup message:

"Couldn't get any accounts! Make sure your Ethereum client is configured correctly."


texts: How to send an amount of ether from the smart contract to an address and save any information along with the transaction (in the TX DATA) (solidity)

texts:
I need to send a certain quality of ether from the smart contract to an address, but the problem is that I need that along with that transaction I need information to be recorded in the blockchain for later access. How do I make sure that only the information I want is recorded along with the transaction?
I was trying to do something like this:
  function Transaction(address payable _to, bytes memory info) public payable {

    //_to.transfer(msg.value);//this works but only performs the transfer

    (bool sent, bytes memory data) = _to.call{value: msg.value}(info);
    require(sent, "Failed to send Ether");
  }

But with this it doesn't work and I don't understand how to register only the information (info) in the blockchain.

Turning TX DATA
0x1e6595ab0000000000000000000000003d1188b926bee218b7980fa23b3c01a222e9806c000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000045445535400000000000000000000000000000000000000000000000000000000 to string the result is:

What are the characters before? And how do I make sure they are not stored in the blockchain?
But with this it doesn't work because if you turn TX DATA
0x1e6595ab0000000000000000000000003d1188b926bee218b7980fa23b3c01a222e9806c000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000045445535400000000000000000000000000000000000000000000000000000000
to string the result is:


texts:
Verifiable computing is computing where the worker provides the clients with not only the result of the program, but a proof that those are the correct results (i.e. they didn't just fudge them so they wouldn't have to do any work). In Ethereum, AFAICT, verification is done by having miners re-run the program entirely. However, for some simple programs, it's possible to do the verification quickly and securely (e.g.
 Non-interactive verifiable computing: Outsourcing computation to untrusted workers). The protocol in the paper I linked only works for boolean circuits, but it provides input/output privacy, and the verification time scales with the size of the input, not the size of the circuit.

My question is, does Ethereum plan to support verifiable computing protocols similar to the one I linked in order to speed up verification / provide privacy? If not, are there any other cryptocurrencies that do?


texts:
I wonder if there is a way to be notified of a potential contract state change (ie it has been part of a transaction) without having to use the event mecanism.

Say I have contract that can be modified across time and I want to be able to read their constant functions if I am notified that they were changed in a transaction.

I have created the following test case

contract Simple {
  uint public data; // a state field
  event Notify(uint newData);

  function setData(uint _data) { data = _data; }
  function setDataAndNotify(uint _data) { setData(_data); Notify(_data); }
}

And on the console side, create the contract, then subscribe to the NotifyEvent or if I subscribe to any event using the filter function as follow : (S is my contract instance variable)

S.Notify(function(e, log) { console.log("Notified ", log); })
web3.eth.filter({ address: S.address }, function(e, log) { console.log("Generic filter ", log); })

when I call the following, both notification are received (normal)

S.setDataAndNotify(1, web3.callinfo)

when I call the following, nothing get triggered on my callback.

S.setData(2, web3.callinfo)

But the transaction went through because the S.data() returns 2.

So is there a way to still receive a callback when the S.setData() transaction is called?
I guess not but has anyone found a way (that does not imply checking after each new block with the filter('latest').

Thanks


texts: ERC721TokenReceiver, assuming that transfer function exists?

texts:
When trying to find out if a contract implemented onERC721Received from safeTransferFrom function, are we just safely assuming the contract has all the erc721 related functionalities? such as transfer, etc?

because it is simply just returning an interface identifier 0x150b7a02, not returning whether it can perform transfer tokens or not.


texts: How permanent is data stored in Ethereum?

texts: Does it all depend on the availability of nodes? What if say there's 1 node left in Ethereum, will that node contains the entire blockchain?


texts: How to make batch transaction in ethereum using web3.py

texts:
I want to make batch transaction in ethereum using the web3.py. I found
web3.createBatch() in Web3.js, but i can not find it on web3.py.


texts: Is there a way to use remixd with the Remix electron app to access local filesystem?

texts:
I'm using the bundled remix electon app, and it's quite cool, but I was just wondering if there is a way to use remixd with the Remix electron app to access local filesystem?  It seems that to use remixd, I need to run remix in a browser instance, is that correct?
As per the docs, I run the following command in the terminal:
remixd -s ./contracts package://a7df6d3c223593f3550b35e90d7b0b1f.mod
then I boot up Remix desktop and it gives me this error:
Uncaught Exception:
Error: listen EADDRINUSE: address already in use 127.0.0.1:65520
    at Server.setupListenHandle [as _listen2] (net.js:1226:14)
    at listenInCluster (net.js:1274:12)
    at doListen (net.js:1413:7)
    at processTicksAndRejections (internal/process/task_queues.js:84:9)

Then Remix boots up and remixd shuts down.  Any ideas where I'm going wrong?


texts: Calling a function inheriting onlyOwner via other contract

texts:
I need to call mint() function in MyNFToken.sol via MyContract.sol.

Ownable.sol

pragma solidity ^0.4.20;

contract Ownable {

address public owner;

function Ownable()
public
{
  owner = msg.sender;

}

 modifier onlyOwner() {

  require(msg.sender == owner);
_;
  }

}

MyNFToken.sol

pragma solidity ^0.4.20;

import "../tokens/NFTokenMetadata.sol";
import "../../node_modules/@0xcert/ethereum-utils/contracts/ownership/Ownable.sol";

contract MyNFToken is
  NFTokenMetadata,
  Ownable

{

function MyNFToken(
    string _name,
    string _symbol
)
public
{
     nftName = _name;
     nftSymbol = _symbol;
  }

function mint(
    address _owner,
    uint256 _id
)
 onlyOwner
 external
{
    super._mint(_owner, _id);
 }

}

MyContract.sol

pragma solidity ^0.4.20;

import "../tokens/MyNFToken.sol";

 contract MyContract{

address nftaddress;

function MyContract (address _nftaddress) public {
    nftaddress = _nftaddress;

}

 function createToken(address _owner,uint256 _tokenId) onlyOwner public payable returns(bool){

    MyNFToken instance = MyNFToken(nftaddress);
    instance.mint(_owner,_tokenId);
    return true;
}

I'm able to execute mint() directly from MYNFToken.sol by accurately    checking the owner of contract(Ownable.sol). But not able call mint() via MyContract.sol. Is there something missing or beyond my understanding?..Please help to resolve this issue.


texts: Is there a way to see events in failed transactions

texts:
Let's suppose this solidity function:
   function myfunction() external {
      emit myevent("hello");
      ...
      revert();
   }

As you can see, the function fires an event.
In some cases, the function will revert a few lines later.
In this case, i will see a failed transaction in the blockchain (with a blockchain explorer). This is normal.
But My event is not visible in this failed transaction. This is a problem because Events are a kind of log for me and it can be usefull to understand why the transaction failed.
Is there a way to fire an event and be sure it will apears in the transaction, even if it fails.
If not, is there a way to "log" some informations with another way than events.
Thanks a lot


texts: Failing to send() 1 wei from one contract to another

texts:
The following code is supposed to send 1 wei from the current contract to a newly created contract. The recipient contract gets created successfully and the sending contract has a positive balance, but the call to send() fails.
address payable this_addr = address (this);
require (this_addr.balance > 100000);

MyContract mc_new = new MyContract ();
address payable mc_new_addr = address (mc_new);
bool success = mc_new_addr.send (1);

Here is the relevant code from the contract being created. I can see that the contract never has a balance and neither recieve() nor fallback() is ever called.
contract MyContract
{
    bool receive_called;
    bool fallback_called;

    constructor () payable
    {
        receive_called = false;
        fallback_called = false;
    }

    receive () external payable
    {
        receive_called = true;
    }

    fallback () external payable
    {
        fallback_called = true;
    }
}

The transfer() function doesn't work either. What am I doing wrong?
Also, what triggers calls to receive() and fallback()? Can it only be done by using one of the assembly functions? Or is the a way to trigger these function calls in ordinary solidity?


texts:
const event = contractInst.Transfer({},{fromBlock: 0, toBlock: 'latest'});

    events.get(function (error, result) {
        if (!error) {
            console.log(result);
        }
    });

The get callback is called immidiately and always returns an empty array.

I synced rinkeby on my local machine (fast mode):

> eth.syncing
{
  currentBlock: 2695904,
  highestBlock: 2695974,
  knownStates: 5468913,
  pulledStates: 5466381,
  startingBlock: 1062319
}

All the transfer events are shown on etherscan:

https://rinkeby.etherscan.io/address/0xf736de997449df5cd756c34858747786e98bcd3d#events

EDIT:

It works if I use an external node (like using metamask to fetch web3). I'm using Geth to sync my node with the following command:

geth --rinkeby --syncmode=fast --rpc --rpcaddr "0.0.0.0" --rpccorsdomain "*" --rpcapi db,eth,net,web3,personal

To connect the node I'm doing:

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


texts: Can I run a website 'on' ethereum or only 'with' ethereum?

texts: Do you run a website 'on' ethereum or 'with' ethereum and if the latter, is that only with 'nodejs'?


texts: Is there any advantage of using localhost as testnet in Metamask?

texts:
I am using Metamask with ganache to deploy my Dapp, i use localhost testnet depend on some tutorials i followed it but really i don't know if it has any advantages comparing with other testnets or no? what is the best testnet in my situation? i search a lot about that but i didn't found any comparison contain localhost testnet, it just between other testnets like: Rinkeby and Ropsten, etc.
thanks in advance.


texts: How to create withdraw token requests on my custom token sale dashboard

texts:
I created a token sale dashboard. Users can send BTC,LTC,ETH to dashboard. When user send BTC, LTC or ETH to dashboard, they get tokens to their dashboard budget (offchain) based on current token price.

I want to let users create token withdraw requests.
1. User created token withdraw request
2. Admin verified the request on admin panel.
3. Dashboard says ethereum network to "Send 1000 tokens to 0x... wallet address"
4. Transaction created.

Step 1 and 2 are Ok. I dont know how to do Step 3.

I deployed the token smart contract on Ropsten.

Users will tell "withdraw amount"(how many tokens) - "withdraw address"(user's personal wallet).

I dont know how to do that.
Thank you!


texts: Geth 1.6.1 hangs throwing "unexpected fault address" fatal error

texts:
Since upgraded to version 1.6.1, Geth node hangs form time to time (once a week) with following fatal error:

fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0x7f6453b72c88 pc=0x461097]

goroutine 1500070 [running]:
runtime.throw(0xe9b327, 0x5)
    /home/travis/.gimme/versions/go1.8.1.linux.amd64/src/runtime/panic.go:596 +0x95 fp=0xc43095a9f0 sp=0xc43095a9d0
runtime.sigpanic()
    /home/travis/.gimme/versions/go1.8.1.linux.amd64/src/runtime/signal_unix.go:297 +0x28c fp=0xc43095aa40 sp=0xc43095a9f0
runtime.memmove(0xc423ad8b80, 0x7f6453b72c88, 0x40)
    /home/travis/.gimme/versions/go1.8.1.linux.amd64/src/runtime/memmove_amd64.s:184 +0x657 fp=0xc43095aa48 sp=0xc43095aa40
github.com/ethereum/go-ethereum/consensus/ethash.hashimoto(0xc43095ad78, 0x20, 0x20, 0x3ff85f426cae9afa, 0x50ffff80, 0xc448b3abe0, 0xc43095ac48, 0x40b944, 0xd2b540, 0xc427ef5320, ...)
    /home/travis/gopath/src/github.com/ethereum/go-ethereum/consensus/ethash/algorithm.go:314 +0x36e fp=0xc43095abe0 sp=0xc43095aa48
github.com/ethereum/go-ethereum/consensus/ethash.hashimotoFull(0x7f6453000008, 0x143fffe0, 0x143fffe0, 0xc43095ad78, 0x20, 0x20, 0x3ff85f426cae9afa, 0xc448b3ab20, 0x20, 0x20, ...)
    /home/travis/gopath/src/github.com/ethereum/go-ethereum/consensus/ethash/algorithm.go:357 +0xbe fp=0xc43095ac58 sp=0xc43095abe0
github.com/ethereum/go-ethereum/consensus/ethash.(*Ethash).mine(0xc420fc0b40, 0xc43363c990, 0x0, 0x3ff85f426cac4155, 0xc427ef5320, 0xc427ef5380)
    /home/travis/gopath/src/github.com/ethereum/go-ethereum/consensus/ethash/sealer.go:130 +0x451 fp=0xc43095af68 sp=0xc43095ac58
github.com/ethereum/go-ethereum/consensus/ethash.(*Ethash).Seal.func1(0xc420695aa0, 0xc420fc0b40, 0xc43363c990, 0xc427ef5320, 0xc427ef5380, 0x0, 0x3ff85f426cac4155)
    /home/travis/gopath/src/github.com/ethereum/go-ethereum/consensus/ethash/sealer.go:72 +0x87 fp=0xc43095afa8 sp=0xc43095af68
runtime.goexit()
    /home/travis/.gimme/versions/go1.8.1.linux.amd64/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc43095afb0 sp=0xc43095afa8
created by github.com/ethereum/go-ethereum/consensus/ethash.(*Ethash).Seal
    /home/travis/gopath/src/github.com/ethereum/go-ethereum/consensus/ethash/sealer.go:73 +0x1d7

Any idea what is the reason for this error? how to fix? Thx!


texts: geth only syncing s few blocks at a time

texts:
I am running geth with syncmode = full (because I need the full state tree of old blocks) and even though it was syncing over 200-300 blocks at a time a while ago, it is now only syncing a few blocks. Any idea why?
thanks

INFO [02-17|14:25:45] Imported new chain segment               blocks=3  txs=50 mgas=3.975 elapsed=9.658s  mgasps=0.412 number=2683028 hash=7723ea…f2eb9c
INFO [02-17|14:25:59] Imported new chain segment               blocks=7  txs=20 mgas=5.019 elapsed=14.057s mgasps=0.357 number=2683035 hash=d77b20…3d24aa
INFO [02-17|14:26:09] Imported new chain segment               blocks=3  txs=29 mgas=3.688 elapsed=9.971s  mgasps=0.370 number=2683038 hash=e6222f…28998e
INFO [02-17|14:26:24] Imported new chain segment               blocks=12 txs=64 mgas=5.841 elapsed=14.272s mgasps=0.409 number=2683050 hash=e6dbb5…036062
INFO [02-17|14:26:36] Imported new chain segment               blocks=6  txs=65 mgas=5.181 elapsed=12.149s mgasps=0.426 number=2683056 hash=edcf5a…2636b3
INFO [02-17|14:26:46] Imported new chain segment               blocks=4  txs=23 mgas=3.763 elapsed=10.503s mgasps=0.358 number=2683060 hash=4b806b…d392d4
INFO [02-17|14:26:55] Imported new chain segment               blocks=1  txs=18 mgas=2.617 elapsed=8.350s  mgasps=0.313 number=2683061 hash=895953…1a9caf


texts: Setting up a server to run a geth node - what hardware would you recommend?

texts:
I am planning to run a geth node 24/7 on a server, what hardware specs would you recommend for this?

I'd like to download the chain pretty fast and want the block download to be consistently quick.

What processor/mainboard is doing the job here?
If I am understanding this correctly, a good SSD and fast RAM are the main components I will have to spend lots of money on, correct?

If someone has more insight on how their server runs a geth node, I would happily listen to it as I have never in my life possessed a server so I don't even know how to connect to it via my PC (This one might be pretty easy though).

Thanks :)


texts: I am using the 'transact' function on the web3 generated contract functions, and I noticed it does a call to estimate gas before sending the transaction.  What other calls does it do?  Does it do calls for gasLimit and Nonce as well?


texts: I would like to know if it was possible to automatically send any ETH amout to an address "B" just after receiving them on an address "A"? Maybe via a script? I need help


texts: Watch contract events without heaving to set up na api key or MetaMask?

texts: I really just need to listen for events coming from the smart contract. Metamask works good on pc but it wont work on mobile and other circumstances. I was thinkng about an open api from infura but still I'm not sure it allows events watching. Do you have any idea?


texts: Truffle Console: Sending Ether to a contract using fallback function

texts:
I have the following contract:
pragma solidity ^0.5.8;
contract  Victim {
   address owner;
   constructor() public{
      owner = msg.sender;
   }

   function deposit()  payable public {}
}

If I wanted to send Ether to the above contract using deposit function, I used to wrote:
acc1 = accounts[1]

options = { from: acc1, to : victim.address, value: web3.utils.toWei('99', 'ether')}

and then:
contractObj.deposit.sendTransaction(options)

Now suppose that I have a fallback function instead of deposit function, how can I send Ether to the contract? Somebody please guide me.
Zulfi.


texts:
I have a function in my contract. First takes argument, the second one does not. Everything works fine until I change the name of the second one into the same one as the first one and create overloading. Then during tests execution I am getting

  Error: Invalid number of arguments to Solidity function

What might be wrong?


texts:
When I run truffle compile it stuck forever after compiling contracts . I am importing openzeppelin library and  using infura , ropsten and metamask to deploy contract on testnet. . Here is the output

Compiling ./contracts/Migrations.sol...
Compiling ./contracts/obaidminttoken.sol...
Compiling zeppelin-solidity/contracts/math/SafeMath.sol...
Compiling zeppelin-solidity/contracts/ownership/Ownable.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/BasicToken.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/ERC20.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/MintableToken.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/StandardToken.sol...
Writing artifacts to ./build/contracts

Here is my truffle.js file

require('dotenv').config();
const HDWalletProvider = require("truffle-hdwallet-provider");
module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 7545,
      gas: 6500000,
      network_id: "5777"
    },
    ropsten: {
        provider: new HDWalletProvider(process.env.MNENOMIC, "https://ropsten.infura.io/v3/" + process.env.INFURA_API_KEY),
        network_id: 3,
        gas: 4500000
    },
  }
};


texts:
I'm using Web3j 5.0.0. I would listen to events of a smart contract. So, I write

      this.getContract().tokenMintedEventFlowable(DefaultBlockParameterName.EARLIEST,
                         DefaultBlockParameterName.LATEST)
            .subscribe(new TokenMintedEventConsumer()

 ...
public class TokenMintedEventConsumer implements Consumer
{
@Override
public void accept(Object t) throws Exception
{
   TheContract.TokenMintedEventResponse event=
   (TheContract.TokenMintedEventResponse)t;
   System.out.println("Token Minted: "+event.creator+" "+ event.tokenId);
}
}

for each event i would listen (about 8 events). Now, i have two main problems:

1) Using Ganache, some events get not listened to. I have cheched the transaction on Ganache,  they are correctly performed, but the related event are not catched.

2) Using Infura (both https and wss), I receive the errors

io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | Invalid response received: 404; 404 page not found

and org.web3j.protocol.exceptions.ClientConnectionException: Invalid response received: 404; 404 page not found

Additionally, the latter error is also raised if I call the web3j method

 ethGasPrice().send().getGasPrice()

I suppose that event listener and ethGasPrice() are not supported by infura, but why some events are missed on Ganache?.


texts: Where is documented all the basic members of a contract?

texts:
It seems every contract instance has a member balance, as per Solidity documentation:

  It also means that this.balance can be higher than the sum of some manual accounting implemented in a contract (i.e. having a counter updated in the fallback function).

Where is documented all the members of this base contract?


texts: Receive Ether to multiple addresses best practice

texts:
Say I am an exchange that has many users. When I ask a user to deposit ETH I give him a unique address so I can attribute the ETH to him.

With Bitcoin this is easy. The bitcoin wallet software handles this and I can have BTC on multiple addresses and it's treated as one account.

I understand that with Ethereum this is different.

I found 2 options to achieve this:

Deploy a forwarder smart contract once for each user, give the address to the user. When the smart contract receives ETH, it forwards it to my main ETH address.
Pros:

User pays the gas cost of forwarding ETH
Only have to keep track of one account (1 private key).

Cons:

I have to pay gas cost of deploying the forwarder contract multiple times

Create an account for each user. Don't give the private key to the user. Periodically go over all "user accounts" I control and send the ETH to the "main account"

Pros:

I don't have to pay gas for deploying any smart contracts

Cons:

I have to keep track of multiple accounts

Which of these two approaches will cost me more gas? Intuitively I think 2nd would cost less gas because deploying smart contracts is more expensive than sending ETH. But the 1st approach seems to be the one that is more popular with exchanges. Why is that?

I should note that I don't expect users to deposit ETH more than once. (Or rather for each deposit I would give them a new address so it's easier to keep track of their deposits)


texts: How does money randomly dissapear when using ethereum?

texts: I was browsing Hacker News this morning and I came across this thread. I've tried searching for answers, but it still baffles me. If Ethereum is "safe" how can things like this happen?


texts: Where are tokens stored from an implementation level

texts:
I have the following questions:

1.From a LevelDB perspective, where are tokens stored? Is it part of account info? Or is it only part of the smart contract?

If it is only part of the contract, how does block explorer know what tokens each account has?
Anyone can point me to the relevant implementation files in aleth impl?


texts: TypeError: Type address is not implicitly convertible to expected type address payable

texts:
I'm taking the course from lynda.com "Ethereum: Building Blockchain Decentralized Apps (DApps)" but there's an issue with the contract we're given, and it won't compile:
pragma solidity ^0.5.0;

contract ApprovalContract {
    address payable public sender;
    address payable public receiver;
    address public constant approver = 0x3999BA5D247c800E5Ef3d4de66618741E3675379 ;

function deposit(address _receiver) external payable {

    require (msg.value > 0);
    sender = msg.sender;
    receiver = _receiver;
    }

function viewApprover () external pure returns(address) {
    return(approver);
    }

function approve() external {
        require(msg.sender == approver);
        receiver.transfer(address(this).balance);

    }
}

Here the picture from the result of trying to compile the solidity contract:


texts: Given logs are streamed to a client via the eth_subscribe(“logs”) rpc method with a logIndex, is there a way to tell the number of total logs in a block from its header?


texts: Solidity airdrop exiting with REVERT opcode

texts:
I work on solidity airdrop contract. I tested the contract in ropsten testnet
https://ropsten.etherscan.io/address/0xc91cc586a0f4b08df677b0b0ef3e1e96cea9a1b2#tokentxns
Our goal is working multisend function. As you can see on the ropsten network, everything works fine (https://ropsten.etherscan.io/tx/0xe8c998d5ac6a1ded0fc695f641a1e0b7afc0c861197b37219f8326fae4210e1f multisend function works fine).
I have problems with this feature in the public network even though the smart contract is identical (https://etherscan.io/address/0xf76672b64f62f72ef9ac64df24fde45366b09770#code).
The multisend function call fails (https://etherscan.io/tx/0x90d6ce9bbf42b1118bdd58cf96b9a923f94aa16617ce5823976fd7d01be10454)

In the ropsten network web3 successfully estimate gas price but in public network i get an error:
"gas required exceeds allowance or always failing transaction".
I have to put the price manually


texts: What kind of HD Wallet is used in test rpc?

texts:
EthereumJS TestRPC starts with a HD Wallet:

HD Wallet
==================
Mnemonic:      behave differ train script wedding grant carbon buyer tape make wise soup
Base HD Path:  m/44'/60'/0'/0/{account_index}

what implementation is it? can I use it in production?


texts: truffle - how to invoke functions based on the address elements

texts:
// 1) I am invoking a function and getting the entire project list - SUCCESS

    truffle(development)> hub.then(function(instance){return instance.getProjAddr.call();})
    [ '0x5b5348b0f831da7ad1818a5b1eff5b305bd6386a',
      '0x0a4d0ae8486053bad0d9a8cd1d5cba1b73bab925' ]

    // 2) Here I am able to print the address one by one - - SUCCESS

    truffle(development)> func.then(function(result) {
     projects = result;
     for ( var i =0 ; i < result.length ; i++)  {
        console.log(projects[i]);
        }
     })

    0x5b5348b0f831da7ad1818a5b1eff5b305bd6386a
    0x0a4d0ae8486053bad0d9a8cd1d5cba1b73bab925

// 3) Based on this address . I am trying to invoke a function named //getProjInfo() which will return me 4 arguments. How do I achive calling it ? //- FAIL

    truffle(development)> func.then(function(result){
     projects = result;
     for(var i =0 ; i < result.length ; i++) {
     projects[i].getProjInfo.call();
     }})

TypeError: Cannot read property 'call' of undefined
        at evalmachine.<anonymous>:1:111
        at process._tickDomainCallback (internal/process/next_tick.js:129:7)

I get the following error.

truffle(development)>func.then(function(result){projects = result;for(var i =0 ; i < result.length ; i++) { var sg = projects[i];Project.at(sg).then(function(instance) {return instance.getProjInfo.call();}).then(function(result) {console.log(result)});}});
undefined
truffle(development)> (node:11734) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 7): Error: Error: VM Exception while executing eth_call: invalid JUMP at 2e01c934adfa06a05d90d510117437f7727fe11b4e03f31e3936ee8ba7cf972e/6098e17865fd773133ad30d2c9bbe7071b01b7fe:138
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/web3-provider-engine/subproviders/vm.js:117:17
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/lib/runTx.js:59:5
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:3694:9
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:359:16
    at replenish (/usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:876:25)
    at iterateeCallback (/usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:866:17)
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:843:16
    at /usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:3691:13
    at apply (/usr/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js


texts: Truffle solidity tests: out of gas & exceeds block gas limit

texts:
I am trying to run some basic test w/ my contract, written with Truffle's Solidity tests (tests written in Solidity).

When runninng truffle test, I get

Error: VM Exception while processing transaction: out of gas

Note: This is caused by the contract constructor new ..., which is indeed doing a lot of things. And I can't break anything down in my code.

Is there any way to get this working with a test written in Solidity? Is there a way to configure the amount of gas the test contract has available?

--

UPDATE:

Actually I figured out changing the gas config value in truffle.js does have an effect. Yet, I am hitting now another roadblock

Error: Error: Exceeds block gas limit

I guess that I have no other choice than optimising the deployment (thus, the constructor) of my contract so as to make it lighter?


texts: Go-Ethereum (Geth) run error: flag provided but not defined: -http.port

texts:
I use official tutorial to run Ethereum private network:
https://geth.ethereum.org/docs/getting-started/private-net
but the command :
geth --datadir="/home/user/1" -verbosity 6 --ipcdisable --port 30301 --http.port 8101 console 2>> /home/user/1/01.log

return error:
Incorrect Usage. flag provided but not defined: -http.port

WAIDW?
upd. : upgrading of geth fith problem


texts: web3.eth.accounts.wallet.create() works on desktop Chrome but not on mobile

texts:
The following lines of code work (a generator function of redux-saga in my React app) on desktop Chrome. However, it does not work on desktop Safari, iOS, and mobile Chrome (on Android). Did not works means console.log(wallet) did not print anything as if the execution stop at the corresponding line.
Any tips to make it works?
FYI, I have implemented using online Ethereum wallet provider/node such as Bitski and Authereum. So, this is my attempt to implement it differently since the web3 library has the web3.eth.accounts.wallet.create function.
export function* createNewAccount(action) {
  const infuraKey = `${process.env.REACT_APP_INFURA_KEY}`;
  const provider = new Web3.providers.WebsocketProvider(
    `wss://rinkeby.infura.io/ws/v3/${infuraKey}`
  );

  const web3 = new Web3(provider);
  const wallet = web3.eth.accounts.wallet.create(1);
  console.log(wallet);
}


texts: How to configure a node and connect it to a browser so that I can perform erc20 token transactions on my site between users?


texts:
For the compliance reasons I need to implement account freeze functionality in ab ERC-20 token. Initially, issued tokens are not transferable until the address holder goes through Know Your Customer process. When the process is complete, a centralized system, having the key of the owner account, informs the smart contract that tokens in this address become transferable.

What would be the best data structure to do this? Assuming there will be 1000-2000 token holders are there any scalability issues in smart contracts regarding this area.


texts: How to fix gas estimation failed error while getting random number from Provable Random DS?

texts:
I'm using Provable for getting a random number and I am using following code snippet from their github: https://github.com/provable-things/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol

Here is code snippet:

pragma solidity >= 0.5.0 < 0.6.0;

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract RandomExample is usingOraclize {

    uint256 constant MAX_INT_FROM_BYTE = 256;
    uint256 constant NUM_RANDOM_BYTES_REQUESTED = 7;

    event LogNewOraclizeQuery(string description);
    event generatedRandomNumber(uint256 randomNumber);

    constructor()
        public
    {
        oraclize_setProof(proofType_Ledger);
        update();
    }

    function __callback(
        bytes32 _queryId,
        string memory _result,
        bytes memory _proof
    )
        public
    {
        require(msg.sender == oraclize_cbAddress());

        if (
            oraclize_randomDS_proofVerify__returnCode(
                _queryId,
                _result,
                _proof
            ) != 0
        ) {
            /**
             * @notice  The proof verification has failed! Handle this case
             *          however you see fit.
             */
        } else {
            /**
             *
             * @notice  The proof verifiction has passed!
             *
             *          Let's convert the random bytes received from the query
             *          to a `uint256`.
             *
             *          To do so, We define the variable `ceiling`, where
             *          `ceiling - 1` is the highest `uint256` we want to get.
             *          The variable `ceiling` should never be greater than:
             *          `(MAX_INT_FROM_BYTE ^ NUM_RANDOM_BYTES_REQUESTED) - 1`.
             *
             *          By hashing the random bytes and casting them to a
             *          `uint256` we can then modulo that number by our ceiling
             *          in order to get a random number within the desired
             *          range of [0, ceiling - 1].
             *
             */
            uint256 ceiling = (MAX_INT_FROM_BYTE ** NUM_RANDOM_BYTES_REQUESTED) - 1;
            uint256 randomNumber = uint256(keccak256(abi.encodePacked(_result))) % ceiling;
            emit generatedRandomNumber(randomNumber);
        }
    }

    function update()
        payable
        public
    {
        uint256 QUERY_EXECUTION_DELAY = 0;
        uint256 GAS_FOR_CALLBACK = 200000;
        oraclize_newRandomDSQuery(
            QUERY_EXECUTION_DELAY,
            NUM_RANDOM_BYTES_REQUESTED,
            GAS_FOR_CALLBACK
        );
        emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer...");
    }

}

When I deployed it via remixIDE, and hit "update" button, it says the following error message:

How can I fix it to get a random number?

Also, I tried depositing some ethers to my contract address too but it failed:https://ropsten.etherscan.io/tx/0x92007536a6d66387b8593063ee774b2e542dc9d0412e7dd9f244124353ff52c7


texts: Is there any way to disable contract creation on a private network?

texts:
I want to use a private Ethereum chain for a specific purpose.

I want users to be able to execute contracts that I have created or that I have initialized the blockchain with, but I do not want users to be able to create new contracts.

Is there any way to do this through either settings or a simple source code edit (in geth specifically)?

Just the node I provide the users not being able to accept new contracts would suffice.


texts: Refund mechanism - How is it possible to have transactions with M$ fee?

texts:
As stated here, my current understanding is that an unused gas is refund when the transaction succeeds (otherwise it is fully consumed)
Lately I found an article about some fee mistakes that led to more than 5M$ spending in transaction fees in only two transactions !
Eventually two questions come to my mind:

Why the extra fee (totalFee - consumedGas) was not sent back to the sender? It seems that the miner was able to keep everything.
How is it possible to have a transaction fee of 2.5M$ included compared to the block gas limit?

Thanks


texts: Reduce gas usage in contract that creates other contracts

texts:
I have a contract that is exceeding block gas limits (using something like 8000000 gas) when I deploy it. I think it is because it is importing a bunch of other contracts and has functions that create other contracts. Is it possible to reduce gas usage in this scenario? I'm thinking it is compiling all the bytecode from all the imported contracts into the main contract and deploying it all in the transaction.

I suppose one solution is to not create all the contracts from the main contract, but rather initialize with references to the deployed contract addresses. Is there another solution that wouldn't require this type of refactor?

Edit: Just realized my idea of the solution might not work because I still need at least the abstract interfaces for the contract to be deployed with my contract. Not sure how much gas savings that would give me.


texts:
I'd like to describe time like Apr15th 10:00AM . I know how to describe time range as follows, but I am not sure how to call date of time. Could you tell me about it if you know?

1 == 1 second
1 minutes == 60 seconds
1 hours == 60 minutes
1 days == 24 hours
1 weeks = 7 days
1 years = 365 days


texts:
Actually, I'm not even sure if what I'm asking is possible.

At the moment, I can run a script in the Geth Console which is creating contract in local.
I would like to create a simple interface with 2 inputs and a submit button to beautify the process.

Do you have any ideas about the easiest way to this ?


texts: Blockcypher Generate Address Endpoint all hex-encoded

texts:
I'm trying to generate a new eth address in www.blockcypher.com.

Everything works fine, but the address returns this type e3f7e628fff7589218d88ae1d6bcdac52fef2168, but it must start with0x, and there is a note all hex-encoded.

Tell me, how right?


texts: How smart contract execute when receiving two transaction in the same time?

texts: When a smart contract receives two transaction by different users, what is the transaction that the smart contract will deal at first ?


texts: I have done simple data transaction on ropsten, it's stll increasing blocks confirmation

texts:
Why there are so many block confirmations in small transaction?

How blocks are working while transaction?