texts: Better pattern to detect web3 default account when using metamask

texts:
Context: I want to use blockies to render an identicon on the page, i get the defaultAccount from web3, for this, the user has to be logged on to metamask with a selected address from his wallet.

The problem: the web app seems to not detect the web3 object on the load event of the page, wchih is the recommended place to detect it.

The code: below is inspired from recommendations at:

https://github.com/MetaMask/metamask-plugin/issues/1158

https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#partly_sunny-web3---ethereum-browser-environment-check

I keep having intermittent behaviour, sometimes web3 is there and sometimes it is not, the only solution I can think of is to have a timer, but that seems to me a bit too simplistic, I would prefer something more elegant.

Question: Is there a better solution to detect the defaultAccount from web3 when the page loads?

 function startApp() {
        GenerateIdenticon();
}

window.addEventListener('load', function () {

// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {

    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
    if (web3.currentProvider.isMetaMask === true) {
        if (typeof web3.eth.defaultAccount === 'undefined') {
            document.body.innerHTML = '
Oops! Your browser does not support Ethereum Ðapps.
';
        }
        else {
            startApp();
        }
    }
    else {
         alert('No web3? Please use google chrome and metamask plugin to enter this Dapp!', null, null);
        // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
       window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}


texts: Erc20 deployed on private Ethereum blockchain

texts: Is an erc20 token which is deployed on a private Ethereum blockchain of any value and is it possible? would it be smarter to deploy on another platform like fabric for permissioned/private blockchains?


texts: Why isn't my account balance changing in my private Ethereum network after successfully mining (thousands of) blocks?

texts:
I have a newly created private Ethereum "network".  I have a question about my balance.  In my genesis file, I have my account listed with a starting balance of 0x200000000000000000000000000000000000000000000000000000000000000 (the default value when you use puppeth)  Even though I have mined many blocks, my balance isn't changing.  I have been staring at this for a while now and don't know what else to look at.

The gist of what I've done:

Install geth
mkdir -p /data/miner0
cd /data
geth --datadir miner0/ account new
(enter password, save password and account id)
using puppeth, create genesis.json file (mine is named 5private.json) and I've chosen "Ethash - proof-of-work"
initialize nodes geth --datadir miner0/ init 5private.json
geth --datadir miner0/ --networkid 35195193 --syncmode 'full' --port 32519 --rpc --rpcaddr 'localhost' --rpcport 8502 --rpcapi 'admin,debug,web3,eth,txpool,personal,ethash,miner,net' --bootnodes 'enode://e2bfa2c1c3dbed66ca2f6787935ea0d6b7013057c9632189e7339c2a6cc2c0452b0d08784517652e0e4dd17044401549bbaef23faf0e16e87bf3d16f42a699f3@127.0.0.1:30519' --gasprice '1' -unlock '0xD4D34828d38A87BcAf376C03696582D6010E14D4' --password miner0/passwd.txt --mine --allow-insecure-unlock
Connect to console geth attach miner0/geth.ipc
Start miner miner.start(1)

My genesis file looks like:

{
  "config": {
    "chainId": 51933519,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 0,
    "eip158Block": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock": 0,
    "petersburgBlock": 0,
    "istanbulBlock": 0,
    "ethash": {}
  },
  "nonce": "0x0",
  "timestamp": "0x5ea26680",
  "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x47b760",
  "difficulty": "0x80000",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    <...omitted...a ton of "precompile-addresses that were prefunded w/ 1 wei...>
    "213eff4c47c046b2ea39748ee57232062114074e": {
      "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
    },
    "54f7bad5b53e43e884254b4d92af0f2d7988589f": {
      "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
    }
  }
}

But after nearly 24 hours, my balance remains at the initial value - it is not changing even though I have been mining blocks.

> eth.getBlock(eth.blockNumber).miner
"0xdfdabe96077efd9d537623a60da946cffddf25e8"
> eth.getBalance("dFdaBE96077EFD9D537623A60dA946cfFDDf25e8")
9.04625697166532776746648320380374280103671755200316916267512375061821325312e+74
(this is the decimal value of the hex balance in genesis above)
> eth.accounts
["0xdfdabe96077efd9d537623a60da946cffddf25e8"]
> eth.blockNumber
6545
> eth.hashrate
45566
> eth.getBalance(eth.coinbase).toNumber();
9.046256971665328e+74
> eth.syncing
false

Any suggestions on what I need to look at?


texts: ERROR Transaction was not mined within 50 blocks, please make sure your transaction was properly send

texts:
I am getting the following error While trying to transfer fund from one account to another:

Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!
    at /home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-method/src/index.js:368:45
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at tryCatcher (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/promise.js:497:31)
    at Promise._settlePromise (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/promise.js:555:18)
    at Promise._settlePromise0 (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/promise.js:600:10)
    at Promise._settlePromises (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/promise.js:679:18)
    at Async._drainQueue (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/async.js:125:16)
    at Async._drainQueues (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/async.js:135:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/home/munim/codes/eth-test-01/node_modules/web3/packages/web3-core-promievent/node_modules/bluebird/js/release/async.js:16:14)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)

My genesis.json file:

{
  "config": {
        "chainId": 10,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

Initiated geth with the following command:

~ geth --datadir="./prinet-betty/data/" init prinet-betty/genesis.json
~ eth --fast --cache=1024 --rpc --rpcaddr="localhost" --rpccorsdomain="*" --datadir="./prinet-betty/data" --nodiscover --rpcapi="db,eth,net,web3,personal" console

The following code returns the error

const Web3 = require("web3");

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

web3.eth.getAccounts((err, acc) => {
    console.log(acc);
    web3.eth.personal.unlockAccount(acc[0], "qwer1234", 1500)
    .then(res => {
        if (res === true) {
            web3.eth.sendTransaction({
                from: acc[0],
                to: acc[1],
                value: web3.utils.toWei(0.1, "ether")
            })
            .then(console.log)
        }
    });
});


texts: Transaction internal transaction out of gas?

texts:
The first error i got was when i was out of gas

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

Subsequently i tried again after having more ether in my wallet and then this happened.

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

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

May i know how do i solve it as i cant transact the item due to multiple internal txns failures?


texts: How to generate the correct go-ethereum bootnode when creating a private blockchain

texts:
I am trying to setup a private ethereum chain and connect two peers to it. I followed this tutorial on github. One of the two peers ran from a windows 10 geth client. The other ran from a Ubuntu geth client (Ubuntu itself ran on Virtual Box).

I started off by creating a genesis block (genesis.json) on the windows client:

  {

    "config": {

      "chainId": 19,

      "homesteadBlock": 0,

      "eip155Block": 0,

      "eip158Block": 0

    },

    "difficulty": "15",

    "gasLimit": "2100000",

    "alloc": {}

  }

Then I ran in cmd :

  geth --datadir path/to/data init genesis.json

After that, I created the bootnode：

  bootnode --genkey = boot.key

and

  bootnode --nodekey = node.key

I then received

  self=enode://6b2700c843fb78732706a2b687ce751a2fbaf7d9034f455f5037af68f1ca0c1a52824cd178f17bc994af9c489d9e3ed0795900ae0efe4eacafb1e8653dc3eb6e@[myip]:30301

My understanding is that this enode will point the future peers to the genesis block and other peers.
Here is the problem. I am able to ping myip,yet

  telnet myip 30301

is unsuccessful. I suspect that i did not use the correct Ip address. I tried using the ipv4 address found from ipconfig, as well as my ipv4 address that I looked up online (probably given by the service proider) with no avail.


texts: Installing Mist after I already had Geth

texts:
I already had geth installed and Rinkeby testnet synced. After that, I wanted to see how Mist works and downloaded Mist (
36.7 MB Mist-linux64-0-9-0.deb).

When launched Mist and choose Rinkeby test net, synchronization started again from block 0. Could there have been a way for me to use already downloaded blockchain with geth.

Secondary questions:
Also, if I install Mist, do I need to install Ethereum Wallet also? Is it already included with Mist?
If geth is included in Mist, but I had geth installed previously, could that be a problem in future?


texts:
I'm thinking on how to implement a P2P messaging platform using Whisper (https://github.com/ethereum/wiki/wiki/Whisper), but before of starting designing a protocol on top of it and work on its implementation, I have some questions about the protocol itself and on the project status:

Do you know if it's suitable for production environment?
Is there a web service that provides stats about Whisper nodes, such as network coverage, network load, average latency, etc?

Thanks.


texts: Can I save my Ganache private blockchain instead starting a new one every time?

texts:
Every time I turn my computer off or even change settings on Ganache (I need to restart) I lose the state of the blockchain and it creates a new one, I have to redeploy my contracts, etc.

Is there a way to keep the same blockchain every time I open Ganache?

How should I proceed if I want to keep track of my private blockchain?


texts: How to run Ethereum Wallet on a custom chain?

texts:
So I downloaded the Ethereum Wallet

I know you can use a custom directory by running geth first with the datadir flag set up, and then launching the wallet. But besides a custom directory, I want to use a private chain.

I'm geth on a private chain like this:

geth --datadir ./genesis -verbosity 6 --port 30301 --rpcport 8102 --genesis ./genesis.json --networkid 321 --nodiscover  --maxpeers 3 console

And it works well. But upon launching the wallet, it starts syncing with the actual Ethereum blockchain of 900,000 blocks.

Is there anything else I need to do so the Wallet uses the geth instance with the private chain?


texts: POS/Sharding - Incentive for submitting proof-of-dishonesty

texts:
While reading through the Nothing at Stake section of the Proof of Stake FAQs it is described how dishonest validators will be punished for voting on two chains. This requires a proof of misbehavior which will have to be inserted in the chain by another honest validator.

This makes me wonder:

what is the incentive for validators to submit this proof, given that it takes resources to monitor for these kinds of misbehavior?
if there is an incentive, why would a validator include anyone's proof if they can simply replace it with their own proof to get this incentive?

with sharding this problem seems even worse, with a larger number of chains/shards to monitor.


texts: Does a for-loop set the input integer to zero?

texts:
I am just starting to experiment with for-loops, and noticed that whether I declare the integer used as i in the for-loop as a global or local variable, it's value seems to be reset each time the following function is run:

function inccountNum() public {
for(i = 0; i < 4; i++) {
    countnum += 2;
}

In other words, I declared i as a global variable, and expected it to be equal to 4 at after executing this function and for countnum (another global variable), to be equal to 8.  This in fact was the case.

However, I expected that running the function again would not be possible, since the variable i = 4 and so can not be < 4.  Instead, I see that i still equals 4 and now countnum = 16.

I even tried setting the global i to 25, assuming the function wouldn't run at all, but it still worked and i was again equal to 4.

Is it safe to assume that the "i = 0" part of the for-loop resets the value of i to zero each time the function is run?


texts: How to get tokens from a contracts 0x0 address?

texts:
I was having a deep dive through an address I found interesting and noticed that all his tokens always came from a contracts 0x0 address. How is this done?
I assume this is how smart contracts work and the address owner can somehow write a smart contract to buy the tokens from that address but I am not sure how I would go about doing something similar. Am I able to write a contract like this within EtherScan's write contract feature?


texts:
I'm trying to import Web3 to my component files which is written in Typescript but I couldn't make it.

I used npm install --save web3-typescript-typings and added

"include": [
    "../node_modules/web3-typescript-typings/index.d.ts"
  ]

to tsconfig.json. However I still get errors from browser's console:

Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/node_modules/web3
    Error: XHR error (404 Not Found) loading http://localhost:3000/node_modules/web3
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3000/node_modules/web3 as "@web3" from http://localhost:3000/app/exchange.component.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3000/node_modules/web3 as "@web3" from http://localhost:3000/app/exchange.component.js
(anonymous) @ (index):18
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:141
(anonymous) @ zone.js:818
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:191
drainMicroTaskQueue @ zone.js:584
ZoneTask.invoke @ zone.js:490

Can anyone shed me some lights?


texts: is it possible to have a password bug in mist wallet 0.8.10

texts:
I was playing with account creation with in MIST and i find one account always saying "password wrong" when i try to transfer ether to other accounts. It can still receive ether though.

I use same password for all accounts in MIST, so I am 99.9% sure password is the regular password i use.


texts: Remix: This contract does not implement all functions and thus cannot be created error

texts:
I have 2 contracts:

pragma solidity ^0.4.18;

contract Coin {
    function transfer(address whom, uint256 amount) public;
}

contract ManagedWallet {
    event ReceivedEther(address source, uint256 amount);
    event ContractCalled(address theContract,uint256 value, bytes data);

    function () public payable {
        ReceivedEther(msg.sender,msg.value);
    }

    function sendEther(address whom, uint256 amount) public {
        whom.transfer(amount);
    }

    function sendToken(Coin token, address whom, uint256 amount) public {
        token.transfer(whom,amount);
    }

    function callContract(address theContract, uint256 value, bytes data) public {
        require(theContract.call.value(value)(data));
        ContractCalled(theContract,value,data);
    }

}

But when I try to deploy that Coin contract, I get this error in Remix.

  This contract does not implement all functions and thus cannot be
  created

What am I missing here? Really appreciate help because I'm new to smart contract development and Solidity.


texts: Ether wallet stuck while syncing. Can I upgrade without syncing?

texts:
My ether wallet (0.5.2) is stuck on block 2,420,853 while syncing.

Can I upgrade to 0.8.1 without syncing?

My goal is to convert my Dao tokens to ether. So I need to update my wallet.

Eeek!

Thank you!


texts: ETH miner recommendation in 2021 (Nvidia RTX 2070)

texts:
As you may know, a few days ago I asked which ETH wallet you would recommend. You can find the question here: Ethereum wallet recommendation
Unfortunately, I have not received an answer yet.
Now I would like to ask - which Ethereum miner (pool mining, on Windows) would you recommend for mining especially on RTX 2070? Do you recommend NiceHash or ClayMore or rather GMiner, Phoenix Mine or any other that comes to your mind? Also could you please explain why? My goal is basically just to try it. As I have an IT background, I have no problems with using the command line interface.
Thank you for the answers in advance.


texts: ERC20 totalSupply not returning the correct value

texts:
I am testing an ERC20 contract based on Openzeppelin-solidity template. But I am observing a curious behavior with reading a global variable. Here is the contract:

pragma solidity ^0.4.24;

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

contract FunnyToken is ERC20 {
    string public constant name = "FunnyToken";
    string public constant symbol = "FYT";
    uint8 public constant decimals = 18;
    uint256 private _totalSupply = 10000 * (10 ** uint256(decimals));
    address private owner;

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

then I truffle migrate it to ganache-cli and run the following commands on truffle console:

FunnyToken.deployed().then(inst=> tok=inst);
tok.totalSupply();

the value returne is: BigNumber { s: 1, e: 0, c: [ 0 ] }. So I conclude that the _totalSupply global variable is not being initialized properly, because the function totalSupply is implemented like this:

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

Can anyone explain me what is going on?


texts: geth --dev exposes live net accounts. Is it safe?

texts:
Running geth console with and without the --dev option seems to expose the same accounts.

Is it safe to use same accounts when developing? If not, what is the recommendation?


texts: Error: Invalid number of arguments to Solidity function (with correct number of parameter)

texts:
I've the following contract function:

/*Solidity Code, inside my contract*/
function isGranted(address _user, address _content) view external returns (bool) {
    return (grantedAccess[_user][_content]);
}

That works on Remix IDE without any problem.

Then I wrote a Web3JS frontend

this.catalog = (this.web3.eth.contract(this.props.catalog.abi)).at(this.props.catalog.address);
this.catalog.isGranted(
            this.web3.eth.defaultAccount, //Parameter1
            this.state.address, //Parameter2
        (err, res) => { //Callback
            if(!err){
                console.log(res);
                this.setState(this.setState({userHasRightAccess: res}));
            } else {
                console.error(err);
            }
        })

But the execution returns Error: Invalid number of arguments to Solidity function. I tried to add the other optional parameter to Web3js function but the error remains. Any idea/solution?

(I don't use Truffle or any more framework. Web3JS version is "0.19.0")

Edit: I've update the library to 0.20.6 version


texts:
as Quorum and Ethereum are developed in Go, would like to understand why Tessera, the new Quorum transaction manager to replace Constellation, is written in Java instead of Go?

Thank you.

Nathan Aw


texts: Transfer Ether from my wallet to another wallet

texts:
I have a wallet at MyEtherWallet.com . Is there any API which allows me to transfer Ether from my account to different accounts ? Does MyEtherWallet provides any such API's ?

I saw the documentation, it mentioned the params below:

eth_sendTransaction

Creates new message call transaction or a contract creation, if the data field contains code.

params: [{
  "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
  "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
  "gas": "0x76c0", // 30400,
  "gasPrice": "0x9184e72a000", // 10000000000000
  "value": "0x9184e72a", // 2441406250
  "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}]

But what is the URL endpoint ? How do I authenticate that I am the owner of this wallet ?


texts: Is possible to check if a address belongs to an exchange?

texts: Most of the exchanges do not accept utility tokens from a contract. Is there a way to validate/check if the target address is/belongs to a exchange?


texts:
I have a wallet on myetherwallet.com with some Ethereum in it.

What's the best safe and easy way to sell these tokens?
Coinbase is irrelevant in my country.


texts: how to get balance for multiple addresses(batch request)?

texts: I need to check the balance for multiple addresses (i.e. 100) a eth_getbalance seems to accept only one address.


texts: Switch between nodes/peers in Mist wallet

texts: I'm new to ethereum and i'm facing this issue. I've created multiple nodes and add them as peers using geth console and can make transactions and stuff from there only. But on installing mist wallet it just shows one of the nodes and accounts in it. It shows others as peers as you can see "2 peers" but there is no option to operate on them from UI. Any suggestions on how I can operate on accounts in other nodes using mist.


texts: send() or sendAsync() while using Web3j to call functions

texts:
I built a java web application which connects using Web3j with my smart contract deployed on Ropsten Network.

My web application provides a control panel to allow the user to send transactions to the smart contract. Sometimes the user can send more than 5 calls at the same time. (actually much more than 5 :) )

I have a java class wrapper of my smart contract to call the functions of it.

  The question is: What I have to use, send() or sendAsync? How to
  manage() I tried to use send() and sendAync().get() and I got the same
  result.

TransactionReceipt receipt = myContract.callFunction1(...)
).sendAsync().get();

What I get with this code is a long wait to complete the call and get the transaction receipt.... Is there another way to do this?

I know this could involve promises but I am not familiar with them. Could someone provide some code?

Thanks in advance


texts: Parity syncing in archive mode stuck at block 4839206

texts:
I am running Parity inside docker in pod in Kubernets on Google Cloud.
The pod is using disk with 2700 GB for storing Ethereum blockchain, and currently
disk has about 2100 GB free.
Unfortunately for few days parity is stuck at block 4839206, it gives logs like this and block number in log does not change.

2019-04-20 17:05:15 UTC Syncing #4839206 0x5e68…aa34 0.00 blk/s 0.0 tx/s 0.0
Mgas/s 0+ 0 Qed #28575 49/50 peers 206 KiB chain 4 KiB db 0 bytes queue 54 MiB
sync RPC: 0 conn, 2 req/s, 32 µs

Arguments for docker image are:

    args: ["-d", "/ethereum-data", "--no-warp", "--tracing", "on", "--pruning", "archive","--jsonrpc-hosts", "all",
           "--jsonrpc-interface", "all", "--allow-ips=public", "--no-discovery"]

Have tried with adding maxpeers minpeers argument.

Have someone any ideas what can be the purpose of not syncing new blocks?


texts:
Is there any way that we can add hex data in ERC20 transaction? Let
s say we want to keep track of why we send the token and other detailed information. How can we achieve that?


texts: How to copy every Address and Holds from an ERC20 Token?

texts:
I'm gona create new version from my f***d of ERC20 token(the problem where in somewhere else not in the ERC20 implementation), I already know how to burn the old Tokens and send out the new one if the user request it.

But it will be much better to doing it once right after the Contract init.

I get that I can use the mapping to get the addresses,

contract OLD_CONTRACT {
    mapping (address => mapping (uint => uint)) public balances;

But then how I can use these addresses in some loop to transfer the exact number of my new Tokens to every address. Most importantly how I can do it in some efficient way?


texts: Why not use require() in place of assert()?

texts:
Even though require() is used substantially more than assert(), there are places where assert() gets used.
One example would be in the widely adopted SafeMath library by OpenZeppelin:

function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
   c = a + b;
   assert(c >= a);
   return c;
}

where a + b is checked after summation to prevent overflow.

It seems like require(c >= a) can be used in place of assert(c >= a) for same functionality with an additional opportunity to refund unused gas. Are there any reason not to use require() here? Is assert() used just to force people not to perform operations that result in bad consequences like overflow/underflow?

Cheers


texts: how to create an address value in solidity

texts:
I have a simple prgram

contract Xyz {
       struct A {
              address x;
              string y;
        }
        mapping( string => A) someMap;
        function record(string y) {
             xAddress = How do i create an address?
            someMap[y] = A(xAddress, 'test')
      }
      getAddress(string y) public constant returns (address) {
             return someMap[y].x;
     }
}

How do i create a address value?

One way I know I can do it is create a dummy contract and then create an instance to get the address. is there another way?


texts: Is this diagram from Uniswap's documentation correct?

texts:
Denote respectively rA and rB the reserve of Token A and Token B. Let f = 1 - fee (i.e. 0.997) and x be the input amount. Then the price function of Uniswap v2 for a pair (A, B) is
P(x) = (rB * x * f)/(rA + x * f)
This answer explains well how the source code computes it:
the computation is based upon the preservation of the "constant product formula": rA * rB = k, where k is a constant. In other word, the product of the new reservers is the same as the old: rA' * rB' = rA * rB = k. But this seems to contradict the documentation of Uniswap v2 which says that

In practice, Uniswap applies a 0.30% fee to trades, which is added to reserves. As a result, each trade actually increases k.

Moreover, the answer seems to suggest that the new reserves are rA' = rA + x * f and rB' = rB - P(x).
I was rather confused when I have seen the diagram below from the documentation.

Here are my questions:

If k actually increase at each trade, then why the price is computed in such a way (i.e. based on preservation of k) ?
What should be the value of rA' on the diagram? Let x = 3, rA = 1200, then by the computation above,  rA' = rA + x * f < 1203. It looks like that the illustration  has multiple errors:

It says that the fee is 0.03%, but it should be 0.3%
It doesn't agree whether rA' is 1203.03 or 1203.3. But both are wrong either way.

What the "price" in blue on the diagram actually means ? (why it doesn't use P(x) ?)


texts: Is Solidity block.number more secure than timestamp?

texts:
In Solidity, some properties such as block.timestamp are attackable by miners and are not (strongly) protected by the protocol. How about block.number, could a miner introduce a randomly high number?

EDIT: I'm thinking of securing a game which facilitates actions such as a pay out, after a certain time period elapsed.


texts: What's difference between "Gas Used By Txn" and "Cumulative Gas Used" fields?

texts:
I'm exploring the following transaction and don't realize What's difference between there two fields:

Gas Used By Txn
Cumulative Gas Used

Could you please explain. Thanks in advance


texts: i am thinking about convert eth to btc etc,is there any platform for this? Uniswap can only convert among erc20 tokens but I am thinking about converting among different type of token?


texts: How can I share a geth service and corresponding chaindata between multiple users but not a keystore / wallet?

texts:
I would like to avoid storing redundant chaindata on the same system (MacOS). As per Ismael, it looks like a solution would be to run geth as a service and have both user accounts' Mist clients connect to that geth instance. I am able to start the geth instance and connect to it from both user accounts (with the help of knocte's answer here, but I cannot figure out how to do this while allowing use of separate keystores for each of these user accounts.

If I start geth using this command, a new keystore is created in the datadir, which is used by both user accounts:

geth --datadir "/Users/Shared/Ethereum/"

If I start it with this command, both user accounts use the specified keystore:

geth --datadir "/Users/Shared/Ethereum/" --keystore "/Users/[username]/Library/Ethereum/keystore/"

My goal is to allow multiple users to share the same chaindata and ideally run one geth service that can be shared between any user accounts on the same system. I'm open to suggestions if I am going about this the wrong way and there is a better way to acheive what I am trying to do.


texts:
I am trying to deploy a contract as explained in this section on Web3.js docs.

As I understand it, I need to do the following:

Create a new contract via web3.eth.Contract
Take the returned-object and call deploy with it
Take the returned-object and call send with it

Some questions about this:

Why do I need to pass the address of the contract to web3.eth.Contract? Wouldn't the contract be allocated wherever there's a "free space"? It's as if I would allocate a variable dynamically, but then tell the compiler exactly where I wanted it.
I see several redundancies, which make me feel like I've got something wrong in my understanding of the 3-step process described above:

Both web3.eth.Contract and deploy take the byte-code as input
Both web3.eth.Contract and send take the owner-address, gas and gas-price as input

Here is the code that I've implemented:

let fs = require("fs");
let Web3 = require("web3");

async deploy(contractName, contractArgs) {
    let web3 = new Web3(new Web3.providers.HttpProvider(NODE_URL));
    let abi = fs.readFileSync(contractName + ".abi").toString();
    let bin = fs.readFileSync(contractName + ".bin").toString();
    let contract = new web3.eth.Contract(JSON.parse(abi), CONTRACT_ADDRESS, {from: MY_ADDRESS, gasPrice: '1000', gas: 2310334, data: "0x" + bin});
    await contract.deploy({data: "0x" + bin, arguments: contractArgs}).send({from: MY_ADDRESS, gasPrice: '1000', gas: 2310334});
    return contract;
}

Can somebody please point out what I need to do differently (in correlation with my questions above)?

Thank you!!!


texts:
Good afternoon!

I have a question regarding testing Integer overflows with truffle.

The contract method is:

function sumNumbers(uint256 numberA, uint256 numberB) public view returns(uint256) {
    return numberA.add(numberB);
}

My test code is as follows:

    it('the sum should not overflow', async () => {
        try {
            // Trying to sum 2^256 + 5, which should overflow and throw an exception in the best case
            const sumResult = await _erc20.sumNumbers(2e256, 5);
            assert.ok(false, 'The contract should throw an exception to avoid overflowing and thus making bad calculations')
        } catch(error) {
            assert.ok(true, 'The contract is throwing which is the expected behaviour when you try to overflow')
            console.log(error);
        }
    })

The test result is as follows:

RangeError: Invalid array length
at Object.padLeft (/app/node_modules/truffle/build/webpack:/~/web3/lib/utils/utils.js:81:1)
at SolidityTypeUInt.formatInputInt [as _inputFormatter] (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/formatters.js:40:1)
at SolidityTypeUInt.SolidityType.encode (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/type.js:188:1)
at /app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/coder.js:91:1
at Array.map (<anonymous>)
at SolidityCoder.encodeParams (/app/node_modules/truffle/build/webpack:/~/web3/lib/solidity/coder.js:90:1)
at SolidityFunction.toPayload (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:92:1)
at SolidityFunction.call (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:131:1)
at SolidityFunction.execute (/app/node_modules/truffle/build/webpack:/~/web3/lib/web3/function.js:260:1)
at /app/node_modules/truffle/build/webpack:/packages/truffle-contract/contract.js:135:1
at new Promise (<anonymous>)
at /app/node_modules/truffle/build/webpack:/packages/truffle-contract/contract.js:126:1

I just can't figure out what is going wrong, except when I change the value 2e256 to a much lower value, say 5, I don't get this error.

Can anyone help me with this case?


texts: understanding value on token transfer transaction

texts:
When a token transfer transaction has an ether price associated with it, is it fair to assume that that transaction used ether to buy the tokens?

For example, this transacion triggered by account A  transfered 1680 tokens from acc 0x0000...to account A (tokens where minted) and cost 12 ehter.
Is it fair to say that the value of the token at the time was 12/1680 = 0.0071428571428571  ETH?


texts: How to store negative values inside {8||16||32} bits in populus?

texts:
I want to store -1 in smallest memory such as in {8||16||32} bits instead of 256 bits.

int i = -1;

When I return var, it returns
-1L instead of -1.

I have assigned -1 into a int8 variable. As I know int8 is signed integer.

int8 i = -1;

But when I return output, it returns: '115792089237316195423570985008687907853269984665640564039457584007913129639679L' instead of -1.

[Q] What should I do to obtain -1?

Please note that I have experimented this problem in populus:

As contract I have use @RichardHorrocks's contract: NumTest on the answer.

test.py:

def test_receipt(web3, accounts, chain, unmigrated_chain):
    my_contract       = unmigrated_chain.get_contract('NumTest');

    set_txn_hash     = my_contract.transact().NumTest();
    contract_address = unmigrated_chain.wait.for_receipt(set_txn_hash)

    output           = my_contract.call().number();
    print(output);

Thank you for your valuable time and help.


texts: TypeError: Indexed expression has to be a type, mapping or array (is function (address) view external returns (string memory,string memory...)

texts:
I have 2 contracts first one is sub second one is main .
First i deploy main and create a new subtoken.
Then I want to access my maincontract in subToken contract but I cant :(
When I compile this contract I saw this error at getName2 function :

  browser/opz4.sol:17:16: TypeError: Indexed expression has to be a type, mapping or array (is function (address) view external returns
  (string memory,string memory,uint8,uint256,uint256)) return
  mc.tokens[address(this)].name; ^-------^

pragma solidity ^0.5.0;
import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol';

contract SubToken{
    MainContract mc;

    constructor(address _address) public{
       mc=MainContract(_address);

    }

    function getName1() view public returns(string memory){
        return mc.getNameMain(address(this));
    }

    function getName2() view public returns(string memory){
        return mc.tokens[address(this)].name;
    }

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

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

}
contract MainContract {
    //mapping(address => mapping(address=>uint)) balances;

    //mapping(address => mapping(address => uint)) allowed;

    address[] public contracts;

    using SafeMath for uint;

    address contract_address;

    struct token{
        string  name;
        string   symbol;
        uint8  decimals;
        uint  totalSupply;
        uint balances;
    }
    mapping(address => token) public tokens;

    address mycontraddress;

    function createNewContract(string memory _name,string memory _symbol,uint8 _decimals,uint256 _totalSupply,uint _balance) public returns(address youraddress){
        SubToken st = new SubToken(address(this));//address(this)
        tokens[address(st)] = token(_name,_symbol,_decimals,_totalSupply,_balance);
        mycontraddress=address(st);
        return mycontraddress;
    }
    function seeContracttAddress() public view returns(address){
        return mycontraddress;
    }

    function getNameMain(address _address) public view returns(string memory){
        return tokens[_address].name;
    }

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

}

anyone can help me please :)


texts: Weird error 'The method eth_accounts does not exist/is not available'

texts:
I am trying to use truffle to migrate with the following command

truffle migrate --network ropsten

and I face the following error

The method eth_accounts does not exist/is not available

I tried to enter geth and inspect using

> eth.accounts

Error: The method eth_accounts does not exist/is not available
    at web3.js:3143:20
    at web3.js:6347:15
    at get (web3.js:6247:38)
    at <unknown>

Anyone has similar experience or know how to solve it ?


texts: Can my Mobile wallet company steal my coins?

texts: My mist-wallet is used for purely for dapp development. To fuel my future ambitions, I went to an online exchange and bought some ether coins and used a mobile-only wallet for these real ether. When trying to research how a mobile wallet differs from Mist-wallet, it seems mobile wallet is a contract and my mobile wallet company participates on my behalf in EVM. If this is the case, how can I trust my mobile wallet company? Can my mobile wallet company transfer all the currency I got into their own and blame it on hackers? TIA


texts: Failing Transaction within Truffle Testing

texts:
How does one test a transaction that is supposed to fail when testing with truffle?

For example, say I was testing an ERC token, in which accounts[0] had a balance of 20. Within a test, I call ERC.transfer(accounts[1], 25, {from: accounts[0]}), hoping to make sure that this would fail. How would I confirm that it did fail?

Sure, I could check that the balances of accounts[0] and accounts[1] do not change - but it seems like there may be a more elegant way to do so. Is there a way to do this?


texts:
I was getting a "EVM error", so I commented out some code and backtracked to find the issue. I added my _feeAmount to an Emit, and getting a what seems to be a bizarre math answer on a simple math problem.

results displayed from Truffle Unit Test with
console.log statements. Everything converted from WeiToEth.

event.feePercent =10
event.FeeAmount  =-18
event.amountGet  =2
event.amountGive =1

FeeAmount should be 2 / 100 * 10
which should be .2 but I'm getting -18.
No idea why it's negative.

import "openzeppelin-solidity/contracts/math/SafeMath.sol";
...

 function _trade(uint _orderId, address _user, address _tokenGet,
                uint _amountGet, address _tokenGive, uint _amountGive) internal {
     // Fee paid by the user that fills the order, a.k.a. msg.sender.
     // charge fees - paid by msg.sender - user filling the order
     // taken from the amount he gets
     uint _feeAmount = _amountGet.div(100).mul(feePercent);

     // do the trade, _user created the order, msg.sender is filling the order
     //tokens[_tokenGet][msg.sender] = tokens[_tokenGet][msg.sender].sub(_amountGet.add(_feeAmount));
     /*
     tokens[_tokenGet][_user] = tokens[_tokenGet][_user].add(_amountGet);

     // send the fees to the feeAccount
     tokens[_tokenGet][feeAccount] = tokens[_tokenGet][feeAccount].add(_feeAmount);

     tokens[_tokenGive][_user] = tokens[_tokenGive][_user].sub(_amountGive);
     tokens[_tokenGive][msg.sender] = tokens[_tokenGive][msg.sender].add(_amountGive);
     */

     // emit trade event
     emit Trade(_orderId, _user, _tokenGet, _amountGet, _tokenGive, _amountGive, _feeAmount,
                feePercent, msg.sender, now);
 }

Truffle test code:

it('emits a "Trade" event', async () => {
    // this is why we needed the "result=" above;
    // "result" is what a subscriber would get subscribing to this event
    //console.log(result);
    console.log("Number of logs=" + result.logs.length)

const log = result.logs[0];
let event;
// get event from logs
event = log.args

console.log("event.feePercent =" + event.feePercent);
console.log("event.FeeAmount  ="  + WeiToEth(event.feeAmount))
console.log("event.amountGet  ="  + WeiToEth(event.amountGet))
console.log("event.amountGive ="  + WeiToEth(event.amountGive))

Definition of Trade event:

  event Trade(
      uint id,
      address user,
      address tokenGet,
      uint amountGet,
      address tokenGive,
      uint amountGive,
      uint feeAmount,
      uint feePercent,
      address userFill,
      uint timestamp
      );

Helper function:

export const WeiToEth = (n) => {
    return new web3.utils.BN(
      web3.utils.fromWei(n.toString(),'ether')
    )
  }

Definition of feePercent:

uint public feePercent;  // Fee percentage

Everything in WEI:

event.feePercent =10
event.FeeAmount  =200000000000000000
event.amountGet  =2000000000000000000
event.amountGive =1000000000000000000


texts:
How can I calculate percentage of a number in solidity? say I want to calculate 95% of the number 200.
How should I go about doing that ?


texts:
I received the error message UnimplementedFeatureError: Only byte arrays can be encoded from calldata currently from the compiler, but without any reference to a file or line.
In a big project, and with a lot of changes, this made the source difficult to find.

The code that caused it ultimately was of this form:

pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;

contract Foo {
    constructor(address[] memory _addrs) public {}
}

contract FooFactory {
    function createInstance(address[] calldata _addrs) external {
        new Foo(_addrs);
    }
}


texts:
I was watching a talk by Vitalik in DEVCON1 in which he says code can do three things one of them being code can send ETH to other contracts.

But can it send ETH to users account as well?
Attached is the snapshot of slide Vitalik was using


texts: web3py error while interacting with smart contract 'message': 'execution error: revert', 'code': -32000

texts:
When I try to interact with the contract with web3.py, I am using ganache, I get the completely useless error message:

  ValueError: {'message': 'execution error: revert', 'code': -32000, ...
  , 'name': 'Error'}

It works correctly when using remix. This is my python code:

w3.eth.defaultAccount = w3.eth.accounts[0]
exams_contract = w3.eth.contract(abi=abi, bytecode=bytecode)
exams = w3.eth.contract(
    address=tx_receipt.contractAddress,
    abi=abi
)
tx_hash3 = exams.functions.studentAddExam(w3.eth.accounts[1]).transact()

And my solidity code:

function studentAddExam(address studentAddress) public returns (string memory returnString){
    // Receives a student's address and adds it to the people that passed that exam
    // Only the creator of the exam can do this
    string memory professorsExamHash = professorsExam[msg.sender];  // The hash of the exam owned by msg.sender
    Exam storage examObj = examHash[professorsExamHash];
    examObj.examSuccess[studentAddress] = true;
    return professorsExamHash;
}

I can interact with the contract using other functions.


texts: What is the size of the blockchain in 2017?

texts:
I have been running the geth with the --fast option to get the blockchain. So far my computer has been running for nearly two days only this program.

The current size of my chaindata folder is 30 GB, and I am on block 1950132. It looks like it is over half way done, but I noticed it's finding less and less blocks as time goes on.

My concern is that my hard drive will fill up before the blockchain is finished. Does anybody know exactly how big the geth blockchain is as of today?

Are there any other ways to get around downloading the full chain to be able to run the ethereum wallet properly?


texts: Best way of storing & querying geographical information

texts:
Lets say I'm developing a dapp that helps people redeem their beer coins by buying each other beers. They need to find each other and so they use a mobile DAPP. Bar owners are be able to add their bar struct Bar {int lat; int long; string32 bar_name; uint ownerID} and drinkers can  find their nearest bar findknearest(int lat,int long), check in checkIn(barID,userID), which would enable them to be found and find other people in the same bar who owe them a beer whoCanBuyMeABeer(uint barID).

So there needs to be a way to store and efficiently query lot of lat,long points.  What are your opinions on the best way to do this.

My initial idea is to:

Simply store the bars in a contract as array of structs Bar[] bars
Load into a KDtree using client side code that findknearest(int lat,int long) is implemented client side.

However it seems wasteful:

Each client has to parse all the points in the world in order to find nearby bars's.
Storing a lot of information on the blockchain

So I wondered if you had any better ideas e.g. :

is there a smart way of splitting the state up. e.g. number of grids cells over earth and bar owner decides where to insert their bar. (might also help with spherical geometry)
is there an efficient way to build a searchable tree structure on insert. e.g. inserts are optimal but tree is not rebalanced.
store data in IPFS/SWARM (can you store as an append only data structure? as a tree?)


texts: What actually happen when we unlock an account?

texts:
I know the purpose of personal.unlockAccount() function is to unlock account i.e. when I want to send ETH or tokens.

After reading the documentation, I'm still not sure what is actually happening under the hood when we unlock our account.

Does it mean someone else with my public key can move my ETH/token when I unlock my account?
Does it mean someone else can deploy a contract using my account when I unlock my account?
Can I unlock an account in node A and deploy a contract from machine B via node A RPC without having to download/copy down my private key from node A into machine B?

Really appreciate all the assistance and pointers.


texts: When Serenity comes around, the network will undergo many changes, some of which may have unexpected consequences on existing Smart Contracts. How can I plan so that I am best prepared to take advantage of new features in Serenity and least likely to see unexpected bugs and security flaws?


texts:
I don't quite understand the hype behind erc tokens.
As I understand it, it is basically an interface for a solidity contract.
So what exactly is the big deal about? The only positive I see is that it allows you to make a well-structured contracts.


texts: Sending ether to a list of accounts in a loop but only the first account receives ether

texts:
I'm implementing a betting smart contracts where users can stake on games and if their team won then admin pay all of the winners by calling function payoutWinners() but the problem is when I call the function payoutWinners, only the first account gets paid not the other winners. Below is the function definition and I need help on how to fix this problem or a workaround thanks

function payoutWinners(uint _gameId) public payable onlyOwner returns(bool){
    require(isValidGamesId(_gameId), "Invalid game Id provided");
    require(!isGameActive(_gameId), " You can only request payment after game is over");

    GameResults memory gameResult = gamesResults[_gameId];
    Bet[] memory allBets = gameBets[_gameId];

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

        Bet memory bet = allBets[i];

        address staker = bet.staker;
        uint160 stakerInt = uint160(staker);
        address payable betStaker = address(stakerInt);

        require(gamersBalances[betStaker][_gameId] > 0, "Your stake cannot be  0 ");

        uint amountToPay = bet.amount * 2;
        require(!bet.paid, "Bet already paid out");

        if(bet.betOn != gameResult.won ){

            continue;

        }else{

            require(amountToPay < address(this).balance, "Inufficient balance please try again later");
            betStaker.transfer(amountToPay);
            gamersBalances[betStaker][_gameId] = 0;
            bet.paid = true;
        }
        emit BetPaid( betStaker,  amountToPay, _gameId);
        return true;
    }
}


texts: How to parse method signature from msg.data in Solidity

texts:
I need to parse method signature from msg.data in Solidity.
To understand what method are calling in msg.data.
So I need to understand that f.e user call transfer method in passed data
sha3('transfer(address,uint256)'="0xa9059cbb"


texts: Is a Raspberry Pi 2 a suitable piece of hardware to run a Quorum Node with Tessera? If so has it been done?

texts:
I would like to set up some Quorum nodes (5) for test purposes and thus far have been unsuccessful in getting a node to run on a Pi 2. The work has stopped due to the need to recompile the binaries from quorum to run on ARM and not as they are on Intel. The Haskell for the constellation isn't playing nicely.

Has anyone attempted or managed this type of deployment?

Thanks in advance for your time in replying!


texts:
In Ethereum, does Account nonce depend on network?

I mean for same address on different network, will there be different nonce?


texts: How can I create Ethereum wallet addresses that can be revoked after certain time? Is it possible to do that? I am trying to create temporary wallets for employees in a company for their company expenses, so that the accounts can be revoked later according to certain conditions or time period.


texts: Is the transaction fee reduced from the transaction value?

texts:
Address A holds 1 ether and address B holds 0 ethers.

Lets create a transaction to transfer all balance from A to B.

This transaction will consume roughly gas_price * gas_used = 20 gwei * 21000 = 0.00042 ethers at the time of writing.

In the end, the B will hold 1 - 0.00042 = 0.99958 ethers either way since there's only 1 ether in total existence.

When the sender creates the transaction, say with https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction, should he leave the estimated transaction cost 0.00042 ethers in A and reduce the transaction value to 0.99958? Or is the fee reduced from the transaction's value automatically?

Put another way, if the sender sets the transaction's value to be 1 ether, will this transaction complete or not?


texts:
Am I paying gas in ETH for sending tokens to a specific miner? If so is it possible to find out how that miner is and to make a deal with that miner to pay less gas for many transactions or maybe pay in tokens?

Thank you very, very much.


texts: How to get block size and block mining time while using ganache and truffle

texts:
I am using truffle framework and Ganache (GUI) as emulator.
I want to know the size of the generated block.
Also I want to know the time required to mine/generate/create a block after the command.
I need to use it for performance evaluation.
The version I am using are downloaded from the https://www.trufflesuite.com/ on Feb'2020
and Running in the VirtualBox LINUX OS.

Thanks


texts:
Is there any penalty for the amount of data passed to a function? Asking because I see non-linear behavior in gas usage during testing when sending more than 31 items in the array.
struct Payment {
    uint256 amount;
    bytes32 salt;
    bytes32 authorClientHash;
    bytes32 payToHash;
    address author;
    address client;
    address payTo;
    bytes authorSig;
    bytes clientSig;
    bytes payToSig;
    bytes approvedSignerSig;
}

function batchPay(Payment[] calldata payments) external onlyApprovedSender nonReentrant { }

TIA!


texts: What's the difference between solc's --opcodes and --asm?

texts:
I'm leanring low-level Solidity inline assembly, but confused by different output formats.
The ouptut option of Solidity compiler says:
  --asm                EVM assembly of the contracts.
  --opcodes            Opcodes of the contracts.

I tried both options to compile the contract below:
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;

contract MyContract {
    string bar = "Hello World";

    function foo() public view returns(string memory) {
        return bar;
    }
}

The command solc -o output --asm contract.sol generated MyContract.evm:
    /* "contract.sol":70:208  contract MyContract {... */
  mstore(0x40, 0x80)
    /* "contract.sol":96:122  string bar = "Hello World" */
  mload(0x40)
  dup1
  0x40
  add
  0x40
  mstore
  dup1
  0x0b
  dup2
  mstore
  0x20
  add
  0x7657399374655890603765000000000000000000000000000000000000000000
  dup2
  mstore
  pop
  0x00
  swap1
  dup1
  mload
  swap1
  0x20
  add
  swap1
  tag_1
  swap3
  swap2
  swap1
  tag_2
  jump  // in
tag_1:
  pop
    /* "contract.sol":70:208  contract MyContract {... */
  callvalue
  dup1
... (and a lot more code)

The command solc -o output --opcodes contract.sol generated MyContract.opcode:
PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x40 MLOAD DUP1 PUSH1 0x40 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0xB DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x7657399374655890603765000000000000000000000000000000000000000000 DUP2 MSTORE POP PUSH1 0x0 SWAP1 DUP1 MLOAD SWAP1 PUSH1 0x20 ADD SWAP1 PUSH2 0x4F SWAP3 SWAP2 SWAP1 PUSH2 0x62 JUMP JUMPDEST POP CALLVALUE DUP1 ISZERO PUSH2 0x5C JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH2 0x166 JUMP JUMPDEST DUP3 DUP1 SLOAD PUSH2 0x6E SWAP1 PUSH2 0x105 JUMP JUMPDEST SWAP1 PUSH1 0x0 MSTORE PUSH1 0x20 PUSH1 0x0 KECCAK256 SWAP1 PUSH1 0x1F ADD PUSH1 0x20 SWAP1 DIV DUP2 ADD SWAP3 DUP3 PUSH2 0x90 JUMPI PUSH1 0x0 DUP6 SSTORE PUSH2 0xD7 JUMP JUMPDEST DUP3 PUSH1 0x1F LT PUSH2 0xA9 JUMPI DUP1 MLOAD PUSH1 ... ...

They look pretty much similar, although not 100% matching each other...
Questions

Does --opcodes just give a more compact form of assembly code compared to --asm output?
PUSH1 0x80 PUSH1 0x40 MSTORE in --opcodes format vs.  mstore(0x40, 0x80) in --asm format. Are they doing the same thing? (I guess so but not 100% sure...)
Is there a way to print --opcodes in a pretty format rather than in a single line?
Are there any good resouces to learn Solidity inline assembly? I googled around but found a bunch of one page blogs, which are good to explain the basics but unfortunately none of them gives a complete and in-depth tutorial


texts:
I need to loop though all of the members of a map and change their property (which is a struct).

the way i'm doing this is when adding a member to the map object also save it's address inside an array and later loop through the array and load the user's struct from the map then do changes.

struct Users {
    address user;
    uint balance;
    uint bonus;
}

mapping (address => Users) instructors;
address[] public allUsers;

function setInstructor(address _address, uint balance, uint _bonus) onlyOwner public {
    Users storage instructor = instructors[_address];

    instructor.user = _address;
    instructor.balance = _balance;
    instructor.bonus = _bonus;

    allUsers.push(_address) -1;
}

function addBalance(_amount) onlyOwner public {

    uint length = allUsers.length;

    for (uint i = 0; i < length ; i++) {
        Users[allUsers[i]].balance = Users[allUsers[i]].balance + (Users[allUsers[i]].bonus * _amount);
    }
}

I was wondering if there is a better way to this? because user's can go pretty a lot and a for loop is expensive in terms of gas usage.

should i user a external server to do the loop?


texts:
My idea for college was to make contract where the total amount from contract is shared equally between 2 partners on testnet I am using Mist and have two wallets (accounts) one is called the MainAcc and other partner1. I can push my contract online, there's no errors in compiler I can push it on the blockchain, but when I go to my contract and call function withdraw and choose an user it starts processing, everything looks fine and transaction is mined, but no ether have been moved from contract to partner or MainAcc.

If i compile it Remix it works i can send money beetween Accounts but have warning --- Gas requirement of function PayCheck.withdraw() high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage) --- maybe thats reason why it wont work on TestNet

I am really desperate, have made whole seminar about smart contracts (history, idea, crypto currency, blockchain, benefits etc) and Ethereum as biggest platform and only need this simple contract to finish it with cool example :(

Thanks in advance!

pragma solidity ^0.4.18;

contract PayCheck {

    address[] employees = [0xE83fad0b5EdF2999c29a00199Ca9B773A4627239, 0x118531D9C6C9114c8B999Ac1197778d1669Fc6c6];

    mapping (address => uint) withdrawnAmounts;

    constructor() payable public{
    }

    function () payable public{
    }

    modifier canWithdraw() {
        bool contains = false;

        for(uint i = 0; i < employees.length; i++) {
            if(employees[i] == msg.sender) {
                contains = true;
            }
        }
        require(contains);
        _;
    }

    function withdraw() canWithdraw public{
        uint amountAllocated = address(this).balance/employees.length;
        uint amountWithdrawn = withdrawnAmounts[msg.sender];
        uint amount = amountAllocated - amountWithdrawn;
        withdrawnAmounts[msg.sender] = amountWithdrawn + amount;
        if (amount > 0) {
            msg.sender.transfer(amount);
        }

    }

}


texts: How do I manually configure the geth fast sync pivot block?

texts:
WARNING - Running Ethereum Wallet 0.8.7 without manually starting geth 1.5.2 will end up clobbering your blockchain data!

UPDATE Nov 22 2016 - New geth 1.5.2 binaries will be downloaded by Ethereum Wallet / Mist (source) so this problem should go away. You will have to restart Ethereum Wallet / Mist for the new binaries to be downloaded.

I have been using the "Cry Uncle" 1.5.2-stable geth version which includes the latest Hard Fork No. 4: Spurious Dragon.

I started the current latest Ethereum Wallet 0.8.7 which packages geth 1.4.18-stable - see mist/clientBinaries.json, lines 39-55:

"mac": {
  "x64": {
    "download": {
      "url": "https://bintray.com/artifact/download/karalabe/ethereum/geth-1.4.18-stable-c72f545-darwin-10.6-amd64.tar.bz2",
      "type": "tar",
      "sha256": "1f7ac168a4502a9e88474f74b3cef2dda4843f350d7f9fcdd9ef10dff30b7282",
      "bin": "geth-1.4.18-stable-c72f545-darwin-10.6-amd64"
    },
    "bin": "geth",
    "commands": {
        "sanity": {
        "args": ["version"],
        "output": [ "Geth", "1.4.18" ]
      }
    }
  }
},

As I was not running geth 1.5.2 manually then, Ethereum Wallet started geth 1.4.18 and this ended up clobbering my chain data as stated in the geth 1.5.2 release notes:

  Database Upgrade

  The 1.5.0 release changes the structure of the blockchain database. Geth will upgrade the database
  during normal operation, but you cannot revert to the previous 1.4.x releases. If you
  do want to revert, you'll need to keep a backup of the chaindata directory or resync.

I then had to decide whether to download the fast sync blockchain, but I need the debug.traceTransaction(...) capabilities from block #2,394,190 as I am using this information for some transaction analysis, but fast syncing exclude this information until a very recent block (currently 2661841).

My blockchain on my mining node is a full archive node and is currently at 87 Gb and I do not want to use this amount of space on my notebook:

user@Rasterbator:~$ du -hs .ethereum/chaindata/
87G .ethereum/chaindata/

How do I fast sync the Ethereum blockchain up until a specified block?


texts: Where is the code for web3 version 0.20.x?

texts:
I'm using the following:

truffle(development)> version
Truffle v4.0.5 (core: 4.0.5)
Solidity v0.4.18 (solc-js)
truffle(development)> web3.version
{ api: '0.20.3',
  node: [Getter],
  getNode: { [Function: get] request: [Function: bound ] },
  network: [Getter],
  getNetwork: { [Function: get] request: [Function: bound ] },
  ethereum: [Getter],
  getEthereum: { [Function: get] request: [Function: bound ] },
  whisper: [Getter],
  getWhisper: { [Function: get] request: [Function: bound ] } }

Apparently my truffle console is using v0.20.3 of web3.js. However, the web3.js releases shows that it skips from 0.19 to 1.0-beta.


texts: How to pass 0 length array as parameter on EtherScan contract editor

texts:
suppose one of the function input parameter is bool[] testInput sometimes I want to pass 0 length array like this => [] instead of this => [true,false,true], how does it possible with etherscan.io.

For example, how do you pass an empty array to function cmp in this contract on Ropsten?


texts: How to get the sum of tokens on all Ethereum addresses generated by one private key?

texts:
I need a tool that automatically show all wallet addresses generated with one private key. Ideally, it would be to manage tokens on any of the addresses from one place.
This is implemented in the web version of MEW, but it is very inconvenient, perhaps there are some other wallets with this functionality.


texts: Using oraclize function into fallback function

texts:
I have an issue with my oraclize. I need to call oraclize for update exchange rate. If I call function updatePrice() manually - it's ok, global variable dollarCost is updating. But if I call updatePrice() automatically into the fallback function, dollarCost isn't updating.

How to call updatePrice() into the fallback function and get result in dollarCost before calc tokens (tokens = msg.value * dollarCost / 1000 / (10 ** 16);)?

pragma solidity ^0.4.11;

import 'https://github.com/oraclize/ethereum-api/oraclizeAPI.sol';

contract Test is usingOraclize {

    uint public tokens;

    uint public dollarCost;

    function() payable {
        updatePrice();
        tokens = msg.value * dollarCost / 1000 / (10 ** 16);
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        dollarCost = parseInt(result, 3);
    }

    function updatePrice() public payable {

        if (oraclize_getPrice("URL") > this.balance) {
            return;
        }
        else {
          oraclize_query("URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD).[0].price_usd");
        }
    }
}


texts: Member "" not found or not visible after argument dependent lookup line 45

texts:
i am trying to create e platform which people can contribute in answering questions by sending funds with specific answer to a question: group A or B,
can anyone help me why am i getting this error?
pragma solidity ^0.8.2;
contract prediction {
address private Manager;

string public Question;

string public winnerGroup;

mapping(address => string) userGroup;

mapping(address => uint) payment;

//mapping(address => uint) profitPerUser;

constructor(string memory _Question) {
    Manager == msg.sender;
    Question = _Question;
}

modifier onlyManager() {
    require(msg.sender == Manager);
    _;
}

struct group_A {
    address[] addresses;
    uint totalFund;
    uint userCount;
    uint profitPerUser;
}

struct group_B {
    address[] addresses;
    uint totalFund;
    uint userCount;
    uint profitPerUser;
}

function pickAnswerA() public payable {
    group_A.addresses.push(msg.sender);
    payment[msg.sender] += msg.value;
    group_A.totalFund = msg.value;
    group_A.userCount += 1;
    userGroup[msg.sender] == "A";
}

function pickAnswerB() public payable {
    group_B.addresses.push(msg.sender);
    payment[msg.sender] += msg.value;
    group_B.totalFund += msg.value;
    group_B.userCount += 1;
    userGroup[msg.sender] == "B";
}


texts: I am looking for some good tutorial about smart contract (beside these on the ethereum website) - do you have some links for me?


texts: Is it possible to use smart contracts to do money transfers? If so, how?

texts:
I've recently gotten into blockchain and I was having trouble understanding smart contracts.
Is it possible to use smart contracts to do money transfers?
Something similar to Venmo I guess. when I researched online I could only find smart contracts that were using crypto currency but I was not able to find someone explaining how smart contracts could be used with fiat money.
Even if this is not possible, could you reference sources so I could further understand how and why it is possible or why it is not possible?
Thanks in advance!


texts:
Can we use tuple as mapping keys? For example:

mapping ((address, uint256) => uint256) myMapping;

If not, what's the closest workaround? Consider the two components of the tuple can go up to uint16.

EDIT

To be more explicit, I can think of two workarounds. The first is a mapping of mapping, though I don't know if it will lead to any additional computational costs than knowing that the two mappings are always used together.

The second is a fixed 2D array (since it goes up to uint16 I can just allocate a 65536 * 65535 array. But this seems to have the potential of allowing a lot of empty spaces (especially if we consider that the value of the mapping might be a struct). I'm guessing such a huge structure might have larger transaction fees comparing to the sparse representation (especially at the beginning where the grid is almost empty).

EDIT2

Originally I was asking with the following example, which was misleading and made ppl think that this was my actual question. I have updated my example (above) to avoid the confusion. For this particular case below, a comment to my question cleverly pointed out that we can convert two uint16 into one uint32 and avoid the tuple situation.

mapping ((uint16, uint16) => uint256) myMapping;


texts: Run truffle test without recompile every time?

texts:
Is there a way to run truffle test and not recompile the solidity code each time?
It takes a lot of time if i just want to play around with the javascript tests...

Thanks!


texts: Two desktop GPU cards, and the second is wrongly identified and unusable

texts:
I've got 2 GPUs inserted into my desktop motherboard:
Device 0: Name: AMD Radeon (TM) RX 480 Graphics Address: 10:0

This one works, displays and mines OK.
Then:
Device 1: Name: AMD Radeon (TM) RX 480 Graphics (POLARIS10, DRM 3.40.0, 5.10.34-1-lts, LLVM 11.1.0) Address: 4294967295:4294967295 Vendor: Intel(R) Corporation Drivers: OpenCL Memory: 4096 MByte Active: false (not selected)

In reality this is ASUS Strix RX 470 Gaming. I have 3 of these cards. All of them identifies same. Address seems to be -1 (4294967295). Vendor = Intel? Wahoa?
About STRIX cards: they light up, when I turn-on PC they also starts spinning coolers for a moment. LED on top of them works; LED indication for external power (red = no power; white = power OK) also works on them fine.
When trying to reflash the cards with amdvbflash on my linux system, it sees the first card, that's working; but it does not sees the second card. Also; if I'm trying to use only 1 or 2 STRIX cards; the system beeps saying GPU error. No display output from this card at any conditions, as well.
Could somebody lead me somewhere? Should I check something on the cards themselves?
Thanks.


texts: How to make a token that matches with string

texts:
I want to create 15 tokens every time the releaseToken() method receives the string hello. I tried to create this condition but it doesn't work. This is code I've written so far:

pragma solidity ^0.4.11;

import './IERC20.sol';
import './SafeMath.sol';

contract testcoin{

    using SafeMath for uint256;

    uint public _totalSupply = 0;

    string public constant symbol = "TES";
    string public constant name = "testcoin";
    uint8 public constant decimals = 3;
    string public contractString = 'hello';

    uint256 public constant RATE = 500;
    address public owner;

    mapping(address => uint256) balances;
    mapping(address => mapping(address => uint256)) allowed;

    function releaseToken(string _string)  payable{
        require(keccak256(_string) == keccak256(contractString));
        createTokens();
    }

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

    function totalSupply() constant returns (uint256 totalSupply){
        return _totalSupply;
    }

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

    function transfer(address _to, uint256 _value) returns (bool success){
        require(
            balances[msg.sender] >= _value
            && _value > 0
        );
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function createTokens() payable {
        uint256 tokens = msg.value.mul(RATE);
        balances[msg.sender] = balances[msg.sender].add(tokens);
        _totalSupply = _totalSupply.add(tokens);
        owner.transfer(msg.value);
    }

    function totalSupply() constant returns (uint256 totalSupply){
        return _totalSupply;
    }

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

    function transfer(address _to, uint256 _value) returns (bool success){
        require(
            balances[msg.sender] >= _value
            && _value > 0
        );
        balances[msg.sender] = balances[msg.sender].sub(_value); //changed
        balances[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success){
        require(
            allowed[_from][msg.sender] >= _value
            && balances[_from] >= _value
            && _value > 0
        );
        balances[_from] -= _value;
        balances[_to] += _value;
        allowed[_from][msg.sender] -= _value;
        Transfer(_from, _to, _value);
        return true;
    }

    function approve(address _spender, uint256 _value) returns (bool success){
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256 remaining){
        return allowed[_owner][_spender];
    }

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

    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

Where should I fix it? Thank you for your answer.


texts: When I deploy a smart contract does it create a new block or when I perfrom a write operation in the smart contract

texts:
I am new in smart contracts and ethereum development DAPPS. I am just curious to know about blocks when they are created and how a block is different from a transaction and a new block is created.
When a deploy a contract its also transaction?
When I call function in a smart contract which performs update its also a transaction?

If Yes, So when does the block is created?

Consider the following smart contract.

contract mortal {
    /* Define variable owner of the type address */
    address owner;

    /* This function is executed at initialization and sets the owner of the contract */
    function mortal() { owner = msg.sender; }

    /* Function to recover the funds on the contract */
    function kill() { if (msg.sender == owner) selfdestruct(owner); }
}

contract greeter is mortal {
    /* Define variable greeting of the type string */
    string greeting;

    /* This runs when the contract is executed */
    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* Main function */
    function greet() constant returns (string) {
        return greeting;
    }

    function updateGreet(string _greeting) public payable returns(bool) {
        greeting = _greeting;
        return true;
    }
}

The above code is taken from https://ethereum.org/greeter and modified so that anyone can update greeting string by calling updateGreeting function in the greeter smart contract. So considering this smart contract.
Please help me understanding the concept.


texts: get back to Ropsten: reclaim address after deletion of genesis block & /testnet/geth/chaindata

texts:
Recently I've been playing around with JPM's Quorum.

It's similar to go-ethereum (goethe) in many ways, but one of the key differentiating factors is that it has a genesis block which isn't the same as the normal network, and I suppose, by extension, the "normal" test-network (Ropsten revivial).

My guess is that running Quorum from my machine has overwritten the genesis block of my standard Ethereum network, in addition to the standard testnets.

To get myself back to Ropsten I deleted the following directory:

database=/Users/s.matthew.english/Library/Ethereum/testnet/geth/chaindata

However, later when I looked at the balance for my account, I was startled to see this:

The block numbers are also strange:

Seems that I'm just running my own private network with myself, is that the case?

My account, 0xd7a9a61a480d458a1181e0563b07f944df4489a6, is visible on Etherscan as it was before:

What is the best way to get myself back onto Ropsten revival, with possession of my keys? Is it still possible?


texts: Posting data from raspberry pi on blockchain and retrieving it back

texts:
I am new to blockchain technology.
I just want to know if it is possible to post the data from raspberry pi on blockchain (ethereum) and retrieve the posted data for viewing.
My question is if its possible how can it be achieved ?


texts: What happens if I cancel contract deployment midway through?

texts:
I would love if someone could clarify what occurs if you cancel a migration midway through, I'm hoping that no harm is done and my artifacts still point to the right corrects.

Running migration: 1_initial_migration.js
Deploying Migrations...
... 0x1453fbfb5c9fbeb5eb29097b0298c4e1dd36cf3e49e42e7e72205e42df8a0877

This is where I pressed the CTRL+C


texts: How to get tokens out of a metamask account

texts: I transferred tokens (GNT) from an exchange to a metamask account but I can't figure out how to get them out. They do not show up in metamask, but etherscan shows them. I tried to import the account to mist but I do not have a json file to import it, only the private key. I am not sure if metamask has the capability to transfer them? I also do not know how to create a json file or import that account to mist. Any direction greatly appreciated? learning slowly. Thanks!


texts: Cannot use delegatecalls in Remix since either the addresses aren't displayed correcly or I cannot access the memory address?

texts:
For instance delegatecall to the same address works:

  function callTheOtherContract() public {
        require(address(this).delegatecall(bytes4(keccak256("callMe()"))));

    }

    event CallMe(address _from);

    function callMe() payable public {
        CallMeMaybeEvent(this);
        balances[0xD3755576a0413ADd8Ba11B5430692630DEa74cCE] += 1;
    }

However trying do call external addressed of a deployed remix contract "in memory" doesn't work:

  function call() public {
        address x =0xCab77B4B9BF9b92a53572091C5798C570051BE8f;
    x.delegatecall(bytes4(keccak256("tobecalled()")));
  }


texts: How do I see from the Etherscan or Bscscan my current holdings of the pair in the liquidity pool?

texts:
After staking into the Pancake Swap liquidity pool - CAKE-BNB 0x0eD7e52944161450477ee417DE9Cd3a859b14fD0, the initial staking amount will change, how can I find out my current holdings of each coin the the pool via Bscscan? Can we query it from the Contract Tab - "Read contract" ?
We can see the smart contract's current holdings via Token Holdings but how do we see our current holdings ?


texts:
uint256 amount = msg.value;

this means if use my code
var tx = await tronweb.transactionBuilder.sendTrx('TKKtaGBH2E2nGSK7F6zKUxvrvtr6iRbp1S', 10 * 1e6, window.tronWeb.defaultAddress.base58)

that means I will get 10 value from msg.value?


texts: Transaction ran out of gas, how to recover and how to prevent

texts:
My transaction ran out of gas. When this occurs, the contract returns the sent ether to the senders wallet, right? It doesn't show yet in my wallet and it happened yesterday, 16 hours ago. The support of the exchange is not reacting.

Can someone kindly advice me what to do?
How can I prevent such happening in the future?

Thanks a lot.


texts: How to optimize the gasPrice and gas options in a contract send() function?

texts:
There are many questions and answers about estimating the amount of gas consumed. This question is about what to do with this estimate.

What values should we actually provide to gas and gasPrice in the send() options, to make sure transactions go through, but we won't pay too much:

myContract.methods.myMethod(123).send({
    from: myAddress,
    gas: myGasLimit,
    gasPrice: myGasPrice
    }, function(error, transactionHash){
    ...
});

Most people seem to advise to set the gas option to 10-20% above estimatedGas (which can be retrieved via the web3 interface).

But what about the case where the estimate is wrong? Because not-used gas is returned, why not set the maximum to something huge? What about the gasPrice, should we leave that up to the miner or actually set a value?

So far I didn't provide any values for gas and gasPrice in the send options, and that resulted in wildly varying amounts of actually paid gas between wallets. In the browser with MetaMask a contract deploy costs 0.000633134 Ether (on Rinkeby) and the same deploy in the CoinbaseWallet costs 0.01268828 Ether (also on Rinkeby). Apparently the gasPrice at the CoinbaseWallet transaction was 20 GWei compared to 1 GWei for the MetaMask transaction.

Edit: clarification of this question:

To make my question more clear: where the question I link to above is about the limitations of the getEstimate function, I am here asking about best practices after having used this function to get an estimate.

Having an estimate, what values do I provide for the gas and gasPrice fields to limit the risk to pay too much and to be picked up in the first upcoming block?

Let's assume here that the method is our own and we know that the estimate is more or less correct (no state changes are possible that make the gas consumption substantially larger).

From the current answers I can conclude: don't set the gas limit too high (so the 10-20%-higher-than-the-estimate-rule sounds good?)

About the gasPrice: I did some experiments and saw that MetaMask uses the value the dapp sets and CoinBaseWallet ignores it. So maybe letting the wallet (and if possible the end-user) decide is the way to go?


texts: web3j - Unable to determine sync status of node

texts:
I have setup a private ethereum node in my laptop using below command.

geth --datadir=./chaindata/ init ./genesis.json
geth --datadir=./chaindata/ --rpc console

The chainId in genesis.json is set to 10 to avoid connecting to main ethereum network. web3j java library is used to send some ether to another account.
   Web3j web3j = Web3j.build(new HttpService());
    log.info("Connected to Ethereum client version: "
            + web3j.web3ClientVersion().send().getWeb3ClientVersion());

    Credentials credentials =
            WalletUtils.loadCredentials(
                    "password",
                    "path-to-wallet-file");

    log.info("Sending 1 Wei ("
            + Convert.fromWei("1", Convert.Unit.ETHER).toPlainString() + " Ether)");
    TransactionReceipt transferReceipt = Transfer.sendFunds(
                web3j, credentials,
                "to-account",
                BigDecimal.ONE, Convert.Unit.WEI)  // 1 wei = 10^-18 Ether
                .sendAsync().get();

What is the root cause for the below exception ?
java.util.concurrent.ExecutionException: org.web3j.ens.EnsResolutionException: Unable to determine sync status of node


texts: negative numbers passed to view functions are treated differently to negative numbers passed to transaction functions

texts:
Using solidity 0.4.18 I have the following contract:

contract MyContact {

    mapping(address => uint) private balances;

    modifier positiveNumber(uint number) {
        require(number > 0);
        _;
    }

    function deposit(uint amount)
      external
      positiveNumber(amount)
    {
      balances[msg.sender] += amount;
    }

    function hasFunds(address depositor, uint amount)
        external
        view
        positiveNumber(amount)
        returns (bool)
    {
        return balances[depositor] >= amount;
    }
}

I have the following tests (trimmed for relevance)

it('punter can\'t deposit negative amount', async () => {
  await assertThrows(myContract.deposit(-1, { from: punter }))
})

it('negative amount fails', async () => {
  await assertThrows(myContract.hasFunds(punter, -1))
})

The first test passes.

The second test fails.

If I try a test like

it('zero amount fails', async () => {
  await assertThrows(myContract.hasFunds(punter, 0))
})

That test passes.

It seems that with a view style function the -1 is not actually being seen as a negative number.

Is there something special about view functions that would cause this to happen, or am I scapegoating?


texts: Internal Compiler Error: Unknow Magic Member

texts:
I am trying to compile a contract using truffle and I am not able to find what this error is related to.

EggFactory.sol

pragma solidity ^0.4.19;

contract EggFactory{

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits; //10000000000000000

    event NewEgg(uint eggId, uint dna);

    struct Egg{
        uint dna;
        uint createdAt;
        bool hatched;
    }

    Egg[] public eggs;

    mapping (uint => address) public eggToOwner;
    mapping (address => uint) ownerEggCount;

    function createEgg(uint _dna) public{
        uint id = eggs.push(Egg(_dna,now,false)) - 1;
        eggToOwner[id] = msg.sender;
        ownerEggCount[msg.sender]++;
        emit NewEgg(id, _dna);
    }

    function generateRandomDna() private view returns (uint){
        // Get the now time, concatenate it with the last blockhash and hash it
        uint rand = uint256(keccak256(now, block.blockhash));
        return rand % dnaModulus;
    }

    function createRandomEgg() public{
        require(ownerEggCount[msg.sender] == 0);
        uint randDna = generateRandomDna();
        createEgg(randDna);
    }
}

EggHatching.sol

pragma solidity ^0.4.19;

import "./EggFactory.sol";

contract EggHatching is EggFactory{

    uint hatchTime = 1 days;

    function hatchEgg(uint eggId) public {
        require(msg.sender == eggToOwner[eggId]);
        require(hasHatched(eggId) == true);
        eggs[eggId].hatched = true;
    }

    function hasHatched(uint eggId) internal view returns (bool){
        return ((now - eggs[eggId].createdAt) >= hatchTime);
    }

    function getEggType(uint eggId) internal view returns (uint){

    }
}

I am aware that the logic of the contract in itself might be flawed in some aspects.


texts: geth shows last block 0, but on import says all blocks present

texts:
I'm trying to restore a corrupt geth DB to a previous version, when I run geth it says

I1109 17:36:34.009514 core/blockchain.go:213] Last header: #0 [d4e56740…] TD=17179869184
I1109 17:36:34.009547 core/blockchain.go:214] Last block: #0 [d4e56740…] TD=17179869184
I1109 17:36:34.009555 core/blockchain.go:215] Fast block: #0 [d4e56740…] TD=17179869184

So I try to import from the backup I have but I see:

I1109 17:36:34.205342 cmd/utils/cmd.go:171] skipping batch 0, all blocks present [88e96d45 / dcdb0ade]
I1109 17:36:49.454992 cmd/utils/cmd.go:171] skipping batch 1, all blocks present [d43fb926 / 5f91e535]
I1109 17:37:14.511707 cmd/utils/cmd.go:171] skipping batch 2, all blocks present [fee1f84b / 1d3fe05c]
I1109 17:37:35.379504 cmd/utils/cmd.go:171] skipping batch 3, all blocks present [132d70a6 / dc2d938e]

I assume the issue is a corrupt db, as if I just leave it to run it says Block synchronisation started but then does nothing.

Do I need to re-sync from scratch?


texts: Can I stop geth when it is halfway done and restart it without loosing all the first half of data?

texts:
I have started geth (fresh install) using this command:
geth --datadir "my/path"
I'm halfway done with sync and would like to restart my PC.
Will I loose all the data accumulated so far or not?
And when I restart the PC, do I have to pass in the --datadir argument again?


texts:
From what I understand, as a miner, I can set whatever gas price I want. So for my test private ethereum network I set, in geth, for my miner a gas price of zero.

I tried doing a transaction from an account with a balance of 0 but I got an error that the account balance is too low.

So why does it fail? Is the gas price somehow adjusted automatically by geth.


texts: How to store private data on blockchain application using a database?

texts: I'm doing a project on healthcare data management Dapp. My project contains the actors as the doctor, patient and hospital. Actors have the attributes them self like name, id, age, hospital registration number and more. The project have the functionalities that are adding actors and updating actors. i'm using the IPFS to store the files related to the each actor as an off-chain storage. My question is how to store the private data of each actors? Storing the data on ethereum blockchain cost much amount of gas. Are there any ways to store the data on any off-chain database? Let me clear about how and what are the databases i can use to store the data as off-chain.


texts: Is it possible to use negative gas to execute a Reentrant attack using .send()?

texts:
Haven't tested it out but I think in theory this could work. It might work somehing like this:

An attacker first writes a lot of data to storage so there is data to be deleted.

Using .send() in the contract to be attacked the attacker gets his fallback function called and frees up space with delete() so he gets more gas to work with than actually should be possible leaving him with enough gas to execute an Reentrant attack.

Is this even possible? And if not, why not?


texts: How to interact with a contract function through another contract?

texts:
I have this function on my MultiSigWallet

function submitTransaction(address destination, uint value, bytes data)
    public
    returns (uint transactionId)
{
    transactionId = addTransaction(destination, value, data);
    confirmTransaction(transactionId);
}

I want to use this to send a transaction to another contract and interface with a function. How do I prepare the data field ahead of time to make sure it works?

The idea behind this, is I want to have children contracts owned by this MultiSigWallet where I submit transactions to interact with the child contract which need approval by signers of the multisig.


texts:
Until today, I thought the transactions are just gathered until big enough to construct a block. Once it is constructed, the ethereum miner will race to find a secret nonce, and the block will be available on the main network.
But today, while reading the book "Mastering Ethereum" by Andreas and Gavin, I come up with the following sentence. "In a few seconds, the new transaction will be mined by the Ropsten miners".
Now the question is, what is mined? Is it each transaction, or each block?
Once I send ether to account x, is this transaction will go to an unverified block or what? How this process exactly works? What about smart contracts? Do it needs to be verified as well before appearing on blockchain?


texts: A error: Use “truffle” to deploy the smart contract to testrpc

texts:
The version used is as follows:
Truffle v5.1.61 (core: 5.1.61)
Solidity v0.5.16 (solc-js)
Node v14.15.4
Web3.js v1.2.9
EthereumJS TestRPC v6.0.3
Before "truffle migrate", I modified the "truffle-config.js" file to:
module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" // 匹配任何network id
    }
  }
};

Then, enter the command "testrpc" to start a blockchain network:

Enter the command "truffle migrate", it shows that it failed：

, and the testrpc network crashed:

I don't understand what is happening here.


texts: Can't get my functions in my contract to run (Solidity)

texts:
With the following, I attempt to test it, but nothing happens when I do my set (and therefore my get). No error, no output... nothing. :(

Am I missing something obvious?

pragma solidity >=0.4.22 <0.6.0;

contract MyPLMPOC {

    string private myContractName;
    uint private myContractLength;

    function setContractName(string memory myNewContractName) public {
         myContractName = myNewContractName;
    }

    function getContractName() public  returns(string memory)  {
        return myContractName;
    }

}


texts: Contract reverted in ropsten - Sending ether via contract

texts:
I was trying to send ether via contract and tested in remix

pragma solidity ^0.4.0;
contract Ballot {

   function sendRequestToPay( uint256 etheramount1,address receiver) payable{

                  receiver.transfer(etheramount1);
     }
 }

Internal transaction was successfully executed over ropsten

And I tried same function with nodejs but contract is reverted.

JsFile

Paycontract.deployed().then(function(instance){

 var registerInstance = instance;
 var amt = 1;
 var receiver = '0x...' //Address

 return registerInstance.sendRequestToPay(amt,receiver,{from: inwallet,gas: 4000000,value:web3.toWei(0.8,'ether')})
    });


texts: Verifying signed typed message hash on-chain

texts:
I've seen many instances of verifying signed messages in which the hash to be verified gets passed as an argument. I need to first recreate the hash on-chain, before running ecrecover on it. However, when I keccak256 hash the same thing I hashed off-chain, I'm getting a non-match.

Here's my web3 code, where I create the hash off-chain:

let prepend = keccak256(ethers.utils.defaultAbiCoder.encode(
      [ 'string' ],
      [ "\x19Ethereum Signed Message:\n32" ]
    ));

    let message = ethers.utils.defaultAbiCoder.encode(
      [
        'address', 'string', 'uint256'
      ],

      [
        contracts.accessControls.address, 'Generate authorization code', this.state.spaceId
      ]
    );

    let msg = keccak256(prepend, message);
    await accessControlContract.commitSignatureHash(indexOfUser, this.state.spaceId, msg);

    web3.eth.sign(msg, context.account, (err, res) => {
      if(err){
        console.log(err);
      } else{
        this.setState({userSecretCode: "register " + this.state.spaceId + context.account + res});
        console.log(this.state.userSecretCode)
      }
    });

And here's my solidity code where I try to recreate the same hash on chain and then run ecrecover on the sending address:

    function commitSignatureHash(uint256 index, uint256 space, bytes32 hashToVerify) public {
        require(whitelistForSpace[space][index] == msg.sender);
        latestCommittedHashByAddressBySpace[space][msg.sender] = hashToVerify;
        timeStampByAddressBySpace[space][msg.sender] = now;
    }

    function verifySignature(address userRegisteringSpace, uint256 space, uint8 v, bytes32 r, bytes32 s) public view returns (bool){
        bytes32 hashToVerify = keccak256(
            abi.encodePacked(
                address(this),
                'Generate authorization code',
                space));

        bytes memory prefix = "\x19Ethereum Signed Message:\n32";
        bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hashToVerify));

        //making sure it recreates a previously committed hash
        require (prefixedHash == latestCommittedHashByAddressBySpace[space][userRegisteringSpace]);

        return userRegisteringSpace == ecrecover(prefixedHash, v, r, s);

msg (created off-chain) doesn't seem to be matching prefixedHash (created on-chain)


texts: Are there any barriers to implementing an ethereum node as a chrome or firefox extension?

texts: Is it possible to create a Firefox or Chrome extension which ran either a full node or light node?


texts: Understanding a simple online contract which seems not functional

texts:
I am writing to understand the functionality of this contract (https://etherscan.io/address/0x1f14b77e9f4844889fa63bc1e5180c8b90ec18db), this does not look even "functional" to me.

Here is the decompiled output this contract with JEB3:

contract DecompiledContract {
    function start() {
        *0x40 = 0x60;
        var0 = msg.data.length;

        if(var0 != 0x0) {
            var0 = (uint256)$msg.sig;

            if(var0 == 0x41c0e1b5) {
                kill();
            }

            if(var0 == 0xe5225381) {
                collect();
            }
        }

        if($msg.value > 0x0) {
            var2 = msg.sender;
            uint256* var6 = *0x40;
            *var6 = $msg.value;
            emit Deposit(*0x40, var6 + 1 - *0x40);
        }

        stop();
    }

    function kill() public payable {
        __impl_kill();
        stop();
    }

    function collect() public payable {
        __impl_collect();
        stop();
    }

   function __impl_kill() private {
        var1 = storage[0x0];
        int256 var0 = var1;
        var1 = msg.sender;

        if((address(var0)) == (address(msg.sender))) {
            var1 = storage[0x0];
            suicide(address(var1));
        }
    }

    function __impl_collect() private {
        var1 = storage[0x0];
        int256 var0 = var1;
        var1 = msg.sender;

        if((address(var0)) == (address(msg.sender))) {
            var1 = storage[0x0];
            var2 = address(this);
            var2 = balance(address(var2));
            uint256 var5 = *0x40;
            var4 = call(0x0, address(var1), var2, var5, *0x40 - var5, var5, 0x0);
        }
    }

}

It seems to me that this contract is performing some fund collection (like shown in the fallback function), and when the owner calls the collect function, the fund will all be transferred to the owner.

However, the major confusion is that there is no deposit operation. I tried to search for EVM opcode sstore in the disassembled output, but just cannot find one. Without a sstore, how can it deposit to the global storage? Am I missed anything here?


texts:
listen ip option in cpp-ethereum always takes default address 0.0.0.0 not the one we specify.

I give the following command

$./eth --upnp off --listen-ip 127.0.0.1

output is

  cpp-ethereum, a C++ Ethereum client

  cpp-ethereum 1.3.0    By cpp-ethereum contributors, (c) 2013-2016.
  See the README for contributors and credits.

  Transaction Signer: XE893RTKL7TK90RQSR0JDUW5981HUK0HZ0
  (2128dfc7-a653-26ff-4648-8cb224b7ed84 - 00e5ad83)

  Mining Beneficiary: XE893RTKL7TK90RQSR0JDUW5981HUK0HZ0
  (2128dfc7-a653-26ff-4648-8cb224b7ed84 - 00e5ad83) Foundation:
  XE55PXQKKK4B9BYPBGT1XCYW6R5ELFAT6EM
  (00000000-0000-0000-0000-000000000000 - de0b2956)

  Node ID:
  enode://f234d190c693fcc1ed8b13720fc3cee794b6579a35667af707b2cdab311bff4555f7022915f1a2a28da7d583ea9dacdff4e99b68bcfa243b1999c007ca62f601@0.0.0.0:10303

  JSONRPC Admin Session Key: N/sibgczkwQ=

  Port numbers are getting changed not the ip address. \

  In main.cpp, there is no default 0.0.0.0 initalized for listenIP.

What is the solution for this?