texts:
We want to create a simple smart contract:
After the click of a "pay"-button, you have to pay automatically 0,01 ETH to our wallet and you can visit after the confirmend transaction a website/link/content.
Used Browser: Mist

Thank you for your help for us beginners to create our first smart contract.


texts: How to pass a blank bytes calldata into a solidity function call?

texts:
I have a function that looks like this:
function foo(uint _someVar, bytes calldata _data) public {
    ...
}

Then I make a call to it from another function with "" as _data:
foo(123, "");

"" seems to be the default way to pass blank bytes. However, I get this truffle compilation error:
TypeError: Invalid type for argument in function call. Invalid implicit conversion from literal_string "" to bytes calldata requested.

I have tried to declare and pass variables, but it all comes down to trying to assign blank calldata bytes. Any tips on how to do this?


texts: Get total supply of any ERC20 token in Solidity

texts:
I'm a new developper on Solidity and maybe this is a trivial question but it is a crucial point for my project.
Is there any way to get the total supply of any ERC20 token (WBTC, and others) on Solidity ? Should I use an oracle ? Or do you have any other idea that I would not have though of ?
Thank you very much !


texts: How to create a temporary account for testnet with funds?

texts:
I'm a newbie in using the ethereum wallet.

After I completely installed and downloaded data for the testnet I create a new account but my new account has nothing (0.00 Eth).

It lead to I can't do anything by this account. I try to create a new contract but it is hopeless (the account you want to send from is empty).

Please help me create a new account (temporary with a little Ether) for the testnet.

I'm using the Etherum Wallet and deploy the contract with the UI. Please, give me some instructions for this.


texts: window.ethereum is always null (with metamask installed)

texts:
I'm trying to create a 'connect to metamask' button using their tutorial but the "window.ethereum" variable is always null even if metamask is installed / unlocked.
I'm not quite sure where to go from here. It seems metamask is supposed to inject Ethereum into the browser
Using chrome as shown below


texts: Truffle migration takes too much time and dont migrate

texts:
0

Hi i am trying to migrate contract by using getch on oracle virtual box ubuntu. Although 1_initial_migration.js deploying it shows Block: 0 Seconds:16743 and it is not completed to deploy and also there is a 2_deploy_contract.js.Normally is it taking much time or deploy in a minute? What's wrong?Why it is not finished 1_initial_migration.js deploying and starting deploy 2_deploy_contract.js?

truffle migrate --reset --network rinkeby

Here is contract:

  pragma solidity 0.4.2;

  contract Election {
  // Read/write candidate
  string public candidate;

  // Constructor
  function Election () public {
   candidate = "Candidate 1";
  }
 }

migrations.sol

  pragma solidity >=0.4.21 <0.6.0;

  contract Migrations {
  address public owner;
  uint public last_completed_migration;

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

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

   function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
   }

   function upgrade(address new_address) public restricted {
     Migrations upgraded = Migrations(new_address);
        upgraded.setCompleted(last_completed_migration);
   }
 }

1_initial_migration.js

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

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


texts:
I want to get the block number based on the transactionhash from filter,however, when I add the following codes to my project,I found it strange because sometimes it automatically transfer the money twice and sometimes I have to transfer a second time in order to see it returning the transaction hash.

besides,I can't get the block number back in the filter.
What's wrong ?

function TransferTest() {
    alert("START TO TRANSFER")
    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    var abiArray=[
        {"constant":true,"inputs":[],"name":"minter","outputs":
            [{"name":"","type":"address"}],"payable":false,"type":"function"},
        {"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},
        {"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"type":"function"},
        {"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"send","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Sent","type":"event"}
    ];
    var object=web3.eth.getTransactionReceipt("0x327fa3ecb7f9312119201995714c6c94a92accfa1643810b2bd3ee6c4f3a038e");
    var conAddress=object.contractAddress;
    var Mycontract=web3.eth.contract(abiArray);
    var MyConIns=Mycontract.at(conAddress);
    var uAddress=document.getElementById("uAddress").value;
    var tarAddress=document.getElementById("tarAddress").value;
    var AKamount=document.getElementById("AKamount").value;
    var success=web3.personal.unlockAccount(uAddress,"carochan123");
    alert(success);
    MyConIns.send(tarAddress,AKamount,{from:uAddress});var filter=web3.eth.filter("pending");
    filter.watch(function(error, result){
        if (!error)
            alert("monitor");
            alert(result);
        var block = web3.eth.getBlock(result, true);
        alert(block.number);
    });

    alert(MyConIns.balances(tarAddress));//50,150,170,260,270,300,320,330,360,370,380,390,410,420
    alert(MyConIns.balances(uAddress));
}


texts: Which laws have to be followed for an ICO/STO in Europe?

texts:
Which laws have to be followed for an Initial Coin Offering / Security Token Offering in Europe?

P.s.: Don't worry, the purpose of this question is NOT to rely on the answers solely. Consultation of Lawyers is an absolute must for any kind of business incl. ICO/STO, but it doesn't hurt to gain knowledge from the community.


texts: Android webj3 "insufficient funds for gas * price + value" exception

texts:
I'm trying to send ether in my Android app between 2 addresses which were opened using Metamask.io
There is a balance of 2 ethers in "from" account.
Here the code

        Web3j web3 = Web3jFactory.build(new HttpService("https://rinkeby.infura.io/MY ACCOUNT"));

        Credentials credentials = Credentials.create(privateKeyRopsten);

        TransactionReceipt transactionReceipt = Transfer.sendFunds(
                web3, credentials, <TO ADDRESS>,
                BigDecimal.valueOf(1.0), Convert.Unit.ETHER).send();

When I run it I get

  java.lang.RuntimeException: Error processing transaction request:
  insufficient funds for gas * price + value


texts: How to test if a transaction create a specific event using the trace api?

texts:
I need to frontrun a transaction on a specific contract only if does a specific thing which is fired as an event once included in a block.
So how to get the event based on current contract state of an unconfirmed raw transaction or unconfirmed transaction hash using my full archival node?


texts: How can I restore a mnemonic seed with one missing word?

texts:
Anyone know how to restore an ethereum wallet from a seed that's missing only one word?

I'm able write a program that will narrow down the possible seeds to like 1500 candidates which are considered valid, but I'm not exactly sure what the next step is.

Each seed has an infinite number of addresses associated with it to my understanding, so how do I find which one has my wallet? Is there a way to search the hierarchy of each seed for my address in this lifetime? Is there something I'm misunderstanding about how HD wallets work?


texts:
Is it possible to modify Geth to only accept connections from peers within a certain distance of the node?
I was thinking it might be possible to have a script to drop connections beyond a certain location but was wondering if there’s something within Geth that will allow me to do this.


texts: Is the modulo operation cheaper in unchecked arithmetic?

texts:
The docs on Solidity v0.8.0 Breaking Changes mention that overflows are now checked by default:

Arithmetic operations revert on underflow and overflow. You can use unchecked { ... } to use the previous wrapping behaviour.

But it is unclear whether the modulo operation (%) classifies as an arithmetic operation. As per the docs:

It is not possible to disable the check for division by zero or modulo by zero using the unchecked block.

So my guess is that modulo shouldn't be faster in unchecked arithmetic. Is that correct?


texts: How do you start learning about blockchain programming?

texts:
I am new to this technology.
I have worked with C#,Javascript and JQuery to build web applications.

I have been reading about how to start building DApps and there is so much data about Ethereum, Blockchain, Solidity and Hyperledger. I'm confused.

Can anyone please guide me on how to get started with this?
What is the language used to build DApps?
What is the difference between Hyperledger and Solidity?
Can I use Visual Studio to build DApps?
I have read a lot about Hyperledger and find it awesome, how do I
start using it?


texts: Why use returns(bool) in a transfer function?

texts:
function transfer(address _to, uint256 _value) public returns (bool) {

        require(balanceOf[msg.sender] >= _value);
        require(balanceOf[_to] + _value >= balanceOf[_to]);
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        return true;
}

Do I need to use returns(bool)?


texts:
for USDT,

Is there any wallet or holding usdt coin? Is it is erc 20, what is the contract address? Which USDT popular, omni or erc20? these two equal?
Is there any USDT api to use? or USDT payment gateway?


texts: What is checklist for auditing a smart contract?

texts: Can anyone tell me the steps or points required to audit the smart contract? I want to audit a smart contact and i need checklist for that.


texts: Does the recent attack to "the DAO" means end of it?

texts:
However implementing the DAO and its smart contracts are incredibly exciting experiments, the recent attack to the DAO clearly suggested that the code is not safe and may or may not have more vulnerabilities.

Is this the end of DAO?

EDIT:
Don't get me wrong, bugs are inseparable part of a developers daily life and despite the convenient solution offered by Vitalik, is there any legitimate and effective way to secure the code (even more) and prevent such incidents from happening in the future?


texts:
I have the following setup of two internal and external functions. Is such a setup correct?
address public addr;

function addValue() external payable {
   _addValue(msg.value);
}

function _addValue(uint256 value) internal payable {
   addr.send(value);
}


texts: Can I create a new ethereum account using Infura like we do using web3.personal.newAccount();


texts: Deployment to ropsten through remix works but mainnet fails

texts:
I just tried to deploy a smart contract to the mainnet. The transaction failed:
Etherscan link

The error is

  Warning! Error encountered during contract execution [Reverted]

Before I tried to deploy this on the mainnet, I had tried it on Ropsten (same code), and it worked perfectly. The gas consumed on ropsten was 5,694,718. The gas limit set for the mainnet transaction was 6,000,000, but clearly the failure is not because of gas anyway, as the failed transaction consumed only 731,989.

Given the size of the transaction (and the unused gas in the transaction), I was expecting the gas used on the block overall to be less. The block gas limit was 7,959,257 out of which 7,976,645 was consumed (99.78%). Given that my transaction had more than 5,000,000 of unused gas, shouldn't the block's gas utilization by less as well?

Could that be a possible reason for the failure? That my contract creation never got to use all the gas it needed and the block gas limit got reached before? It would be strange behavior if that was the case.

I did try to debug the transaction in remix, but not very useful. The debugger loads but when I click on next, it doesn't even appear to hit the smart contract constructor.

Any thoughts on the problem would be very welcome.


texts: How can I set the timeout for web3 python function Eth.getTransactionReceipt and the ContractFunction.call?

texts:
I am polling the Eth.getTransactionReceipt and the ContractFunction.call to get the transaction receipt for a mass transaction submitted onto the Ethereum chain. I notices that I have a lot of CLOSE_WAIT to occupied opened files.
My code as below:
Transaction:
tx_hash = contract_instance.functions.setApprovalForAll(
    Web3.toChecksumAddress(a['set_operation_to_this_account_address']), b['approval']
            ).transact({'from': self.w3.toChecksumAddress(a['original_account_address']), 'gas': int(gas_estimate)})

Call:
last_token = contract_instance.functions.getId().call()

Check the file handle occupied:
>lsof -p 3146 |grep CLOSE
python3 20371 ubuntu  776u     IPv4             751767      0t0    TCP ubuntu:49060->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  777u     IPv4             716763      0t0    TCP ubuntu:41102->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  778u     IPv4             725121      0t0    TCP ubuntu:40790->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  779u     IPv4             631622      0t0    TCP ubuntu:35948->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  780u     IPv4             724478      0t0    TCP ubuntu:41798->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  781u     IPv4             752720      0t0    TCP ubuntu:49072->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  782u     IPv4             720853      0t0    TCP ubuntu:41484->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  783u     IPv4             722860      0t0    TCP ubuntu:41600->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  784u     IPv4             720880      0t0    TCP ubuntu:41640->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  786u     IPv4             632055      0t0    TCP ubuntu:35940->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  788u     IPv4             634447      0t0    TCP ubuntu:36712->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  789u     IPv4             749089      0t0    TCP ubuntu:49176->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu  814u     IPv4             723730      0t0    TCP ubuntu:41878->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu 1062u     IPv4             748998      0t0    TCP ubuntu:48724->192.168.54.154:https (CLOSE_WAIT)
python3 20371 ubuntu 1063u     IPv4             750865      0t0    TCP ubuntu:48952->192.168.54.154:https (CLOSE_WAIT)

Total count of CLOSE_WAIT:
lsof -p 20371 |grep CLOSE |wc -l
682
How can I set a timeout for each transaction call that these connection will not occupy the file handle in long period?
Environment:
Python 3.6.9
Web3 5.21.1
Geth 1.9.21
Maybe I would narrow down the issue by the setting of the middleware of the web3.py. How can I setup the timeout for each requests call in middleware layer in web3.py?
Anyone can help would be appreciated.
Thanks.


texts: Ethereum how to create account on parity hosted on Kovan network?

texts:
I have a parity node hosted on kovan network.
How to create account using web3py?
I used web3.personal.newAccount()=>which is giving error as no method found.

What are the api's available for parity?


texts: Web3, MetaMask, setprotocol.js - RPC Error: Invalid parameters: must provide an Ethereum address

texts:
I am following this Set Protocol tutorial. I am running into following error when running the code in the browser.
inpage.js:1 MetaMask - RPC Error: Invalid parameters: must provide an Ethereum address.

You can see my code in this Github repo:
JS:
import SetProtocol from 'setprotocol.js';
import BigNumber from 'bignumber.js';
import * as Web3 from 'web3';

// Kovan Config
const config = {
  coreAddress: '0x3ee64Fe0b9246Ae52845F01A79c4b3A6D252289a',
  exchangeIssuanceModuleAddress: '0x887E45236B280B33C743075ac11dD69E3c581697',
  kyberNetworkWrapperAddress: '0x4093415A2eA915EaacF44Ac08A42434aE6A9d4e5',
  protocolViewerAddress: '0x5754FA9d232812F817F5Ca58152Ad1E991e916dD',
  rebalanceAuctionModuleAddress: '0xeA510E982c92620A19475F8Dc777bAaa3c2A00F5',
  rebalancingSetExchangeIssuanceModule: '0xC2eF8799315E08f4ee08eA29913D2e51dba5aB78',
  rebalancingSetIssuanceModule: '0x91E1489D04054Ae552a369504F94E0236909c53c',
  rebalancingSetTokenFactoryAddress: '0xdc5B19c7085eBEE3AF84cf30418c0ECa11Ed1933',
  setTokenFactoryAddress: '0x952F78C33D3fb884C00b22e69B9119cd70582F80',
  transferProxyAddress: '0x61d264865756751392C0f00357Cc26ea70D98E3B',
  vaultAddress: '0x45Ab785b6c04f11b5e49B03d60f3642A8Ffe9246',
  wrappedEtherAddress: '0x8a18c7034aCEfD1748199a58683Ee5F22e2d4e45',
};

const injectedWeb3 = window.Web3 || undefined;
let provider;
try {
  // Use MetaMask/Mist provider
  provider = injectedWeb3.currentProvider;
} catch (err) {
  // Throws when user doesn't have MetaMask/Mist running
  throw new Error(`No injected web3 found when initializing setProtocol: ${err}`);
}
window.ethereum.enable();
var userAccount = null;
web3.eth.getAccounts(async function(error, accounts) {

        if (error == null && accounts.length > 0) {
          userAccount = accounts[0];
        }
});
web3.eth.defaultAccount = userAccount;
const setProtocol = new SetProtocol(provider, config);

const createStableSet = async function() {
    const trueUSDAddress = '0xAdB015D61F4bEb2A712D237D9d4c5B75BAFEfd7B';
    const daiAddress = '0x1d82471142F0aeEEc9FC375fC975629056c26ceE';

    const componentAddresses = [trueUSDAddress, daiAddress];
    const { units, naturalUnit } = await setProtocol.calculateSetUnitsAsync(
      componentAddresses,
      [new BigNumber(1), new BigNumber(1)],
      [new BigNumber(0.5), new BigNumber(0.5)],
      new BigNumber(1),
    );
    const name = 'Stable Set';
    const symbol = 'STBL';
    const txOpts = {
      from: '0x8FfB4E5E8C80BaD09f9Fa185a0b5F3ae1d9E5802',
      gas: 4000000,
      gasPrice: 8000000000,
    };

    const txHash = await setProtocol.createSetAsync(
      componentAddresses,
      units,
      naturalUnit,
      name,
      symbol,
      txOpts,
    );
    return await setProtocol.getSetAddressFromCreateTxHashAsync(txHash);
  };

  console.log(createStableSet())

HTML (I am using webpack to build the main.js which is included in the HTML):
<html>
  <script src="main.js"></script>
  <body>
    <div>
      Hello World!
    </div>
  </body>
</html>

I have MetaMask extension installed. The from address in txOpts is the address I copied from MetaMask by clicking on Account (it is an address on the Kovan Test network):

All the other addresses in the code, like those in const config are from the tutorial.


texts: What is the difference in the two mapping structures

texts:
Is the below mapping structure a legit way to create a restricted mapping, or is the latter best practice?
mapping(address => SomeStruct)[5] private structs;

and
mapping(address => mapping(uint256 => SomeStruct)) private structs;


texts: How to convert Ethereumj byte arrays to Strings?

texts:
Ethereumj gives a lot of byte arrays, when the equivalent would be a string in Bitcoin. A few examples (in Scala)

ECKey.getAddress // returns Array[Byte], need String

Transaction.getHash // returns Array[Byte], need String

Transaction.getNonce // returns Array[Byte], need Int (or BigInteger)

Are the Strings supposed to be Hex encoded byte arrays? So, for example, I would do:

val addr = Hex.encodeBytes(ECKey.getAddress)

val txHash = Hex.encodeBytes(Transaction.getHash)

val txNonce = new BigInteger(Transaction.getNonce)

Which of the above are right?


texts: .json files for contracts are not created

texts:
I am really new in ethereum and solidity and I am having hard time to figure out how to get the .json equivalent for contracts.

I have the Campaign.sol inside the contractsFolder. The Campaign.sol file has 2 contracts named CampaignMgr and CampaignFactory.

My package.json file looks like this:

{
  "name": "kickstarter",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "zake",
  "license": "ISC",
  "dependencies": {
    "fs-extra": "^9.0.0",
    "ganache-cli": "^6.9.1",
    "mocha": "^7.0.1",
    "solc": "^0.4.17",
    "web3": "^1.0.0-beta.26"
  }
}

My compile.js code is:

const path = require('path');
const solc = require('solc');
const fs = require('fs-extra');

const buildPath = path.resolve(__dirname, 'build');
fs.removeSync(buildPath); //removes folder and its contains

const campaignPath = path.resolve(__dirname, 'contractsFolder', 'Campaign.sol');

const source = fs.readFileSync(campaignPath, 'UTF-8');
const output = solc.compile(source, 1).contracts;

fs.ensureDirSync(buildPath); //checks if directory exists. if not creates for us

for(let ctrct in output)
{
  fs.outputJsonSync(
    path.resolve(buildPath, ctrct+ '.json' ),
    output[ctrct]
  );
}

It should output the 2 json files like :CampaignMgr.json and :CampaignFactory.json inside the build folder but I never get the json equivalent of the contract.

I hope someone will point out exactly what I am doing wrong. Please let me know if you need anything else in the code.


texts:
I noticed the generation of Hardhat local Etheruem network keys are found on the Mainnet.
Example:
After running npx hardhat node.
Accounts
========
Account #0: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80

The link of the same address in the Mainnet: https://etherscan.io/address/0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266
Any explanation?


texts:
Every time I stop and re-start Geth, I wait for it to discover peers. Can I instead export my list of currently connected peers and use them as bootnodes in my next start? I know this list will act as a central peer database but still, more peers should mean more safety, right? I would really appreciate a code snippet for this.

Thanks,


texts: What is the JSON-RPC method to call a contract's function?

texts:
I'm trying to figure out what exactly happens when a function of a smart contract gets called. Since all client communication is done through JSON-RPC I'm looking at their wiki to find which JSON-RPC function is called when you call a smart contract function.

Is this different from view functions to payable ones?
Or do all function calls use the JSON-RPC function eth_sendTransaction and include the function's name as hash in the data field?


texts: Contract cannot create new Contract in Quorum

texts:
My main contract called SurveyFactory creates new Survey forms:

pragma solidity = 0.5.9;

import './Survey.sol';
contract SurveyFactory {

    address[] public surveyList;
    address public Owner;

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

    function createSurvey() public returns(address surveyAddress){
        Survey survey = new Survey();
        surveyList.push(address(survey));
        return address(survey);
    }

    function getSurveyCount() public view returns(uint) {
        return surveList.length;
    }
}

I can get the address of the created contract fine - but it doesnt exist in my network when i search for it.

Code is tested to be working on Ropsten.


texts: Who is Oraclize? Is using their API dangerous?

texts:
I looked through the code of the oraclize api, and it seems that oraclize can swap out keyportions of the implementation at will. In particular, it looks like they can adjust the pricing for their API pretty much at will any time - so they could drain all ether from contracts that access their API quite easily.

Whom exactly are we trusting here by using their API? I didn't find any faces on their website.


texts: put address->int mapping values in array on geth command line


texts: Solidity if condition based mapping with multiple struct

texts:
I'm trying to map with more than one structs. First mapping contains common details need to be mapped to every item and then second mapping should be carried out according to the item type.

    pragma solidity ^0.4.11;
    contract MyContract {

     struct CommonDetails {
      string name;
      uint32 group;
      mapping (string => SpecificDetails1) items;
     }

     struct SpecificDetails1{
      uint32 capacity;
      string owner;
     }

    struct SpecificDetails2{
     uint32 capacity;
     string owner;
    }

    mapping (address => CommonDetails) commonMapping;
    mapping (string => address)specificMapping;

    function setName(string _name, uint32 _group){

     commonMapping[tx.origin] = CommonDetails(_name, _group);

      if (_group == 1){
       // add SpecificDetails1 along with existing common details
       // if _group == 2 then add SpecificDetails2
     }
    }

   function getName() constant returns(address, string, uint32) {

     return (tx.origin, commonMapping[tx.origin].name,
     commonMapping[tx.origin].group);
     // also want SpecificDetails in getter function
    }

Initially, common details should be mapped to every item and then according to the input (for the group), 2nd struct should be mapped.

I have tried to create an array within struct and then push the specific details to that array but no joy.

My question is how can we perform 2nd mapping to another struct that is based on the input getting from the initial mapping?

If this is not possible within the single contract, can we do this importing this contract function into another contract and then perform 2nd mapping?
And also how to get the output of both mapping in getter function, also.

Any guidance would definitely be appreciated!


texts: why this simple function cause out of gas error on TestRPC?

texts:
thanks for any suggestions.

function withdraw() public {
    if(votes[msg.sender].voteRound == curRound){
        numTotalVotes = numTotalVotes - votes[msg.sender].numVotes;
        numVoteAddrs--;

        while(votes[msg.sender].numVotes > 0){
            delete votes[msg.sender].voteRecs[votes[msg.sender].numVotes - 1];
            votes[msg.sender].numVotes--;
        }
        votes[msg.sender].voteRound = 0;
    }
    else{
        votes[msg.sender].numVotes = 0;
        votes[msg.sender].voteRound = 0;
    }


texts:
I downloaded go-ethereum .aar file from here :

https://geth.ethereum.org/downloads/

For my Android phone for invoking functions of my smart contract.

But I don't know how to use this file?


texts:
I want to map an address to two different field. which one is correct or better ?

Approach 1 :

mapping(address => uint256) balances_En;
mapping(address => uint256) balances_PW;

and to return its balance :

return balances_En[_owner]
return balances_PW[_owner]

Approach 2 :

struct Balances {
    uint256 balances_En;
    uint256 balances_PW;
  }
mapping(address => Balances) balances;

and to return its balance :

return balances[_owner].balances_En
return balances[_owner].balances_PW


texts: openzeppelin,VM Exception while processing transaction: revert

texts:
using openzeppelin-solidity to create crowdsale.

Then I use this statement to Buy Token:

MyCrowdsaleInstance.sendTransaction({
   from: purchaser[1],
   value: web3.utils.toWei("0.5", "ether"),
   gas: "220000"
})

And I got the error:

    Error: Returned error: VM Exception while processing transaction: revert
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request.js:318:1)
    at XMLHttpRequest._setReadyState (C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request.js:208:1)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request-event-target.js:34:1)
    at XMLHttpRequest.request.onreadystatechange (C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\web3\~\web3-providers-http\src\index.js:96:1)
    at C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\packages\truffle-provider\wrapper.js:112:1
    at C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\web3-eth\~\web3-core-requestmanager\src\index.js:140:1
    at Object.ErrorResponse (C:\Users\zx\AppData\Roaming\nvm\v10.15.1\node_modules\truffle\build\webpack:\~\web3-eth\~\web3-core-helpers\src\errors.js:29:1)

my version：

openzeppelin-solidity: "^2.1.3"
Truffle v5.0.17 (core: 5.0.16)
Solidity v0.5.0 (solc-js)
Node v10.15.1
Web3.js v1.0.0-beta.37

contract code:

// MyToken.sol

pragma solidity ^0.5.0;

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

contract MyToken is ERC20, ERC20Detailed {
  uint public INITIAL_SUPPLY = 10000000000;

  constructor(string memory _name, string memory _symbol, uint8 _decimals)
    ERC20Detailed(_name, _symbol, _decimals)
    public
  {
      _mint(msg.sender, INITIAL_SUPPLY);
  }

}

// MyCrowdsale.sol

pragma solidity ^0.5.0;

import './MyToken.sol';
import "openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";

contract MyCrowdsale is Crowdsale {
  constructor(
      uint256 rate,    // rate in TKNbits
      address payable wallet,
      MyToken token
  )
      Crowdsale(rate, wallet, token)
      public
  {

  }

}

// 2_deploy_token.js

const MyToken = artifacts.require("MyToken");
const MyCrowdsale = artifacts.require("MyCrowdsale");

module.exports = function(deployer, network, accounts) {
  const _name = "My Token";
  const _symbol = "MTK";
  const _decimals = 2;

  const rate = 1;
  const wallet = accounts[0];
  return deployer.then(() => {
    return deployer.deploy(MyToken, _name, _symbol, _decimals);
  }).then(() => {
    return deployer.deploy(
      MyCrowdsale,
      rate,
      wallet,
      MyToken.address
    );
  })
};


texts:
Here's my solidity:

contract Oracle {
  mapping(uint => uint) oracle_values;
  modifier onlyOwner {
    require(msg.sender == owner);
    _;
  }

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

  function StoreDocument(uint _key, uint _value) public onlyOwner() {
    oracle_values[_key] = _value;
  }

  function RetrieveData(uint _date) public constant returns (uint data) {
    return oracle_values[_date];
  }
}

and my simple Javascript test.

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

var startDate = 1;
var endDate = 2;
var startVal = 1000;
var endVal = 2000;

contract('Oracle',function(){

  it("Store Values", function(){
    return Oracle.deployed().then(function(instance){
      instance.StoreDocument(startDate,startVal);
      instance.StoreDocument(endDate,endVal);
    }).then(function(instance){
    assert.equal(instance.RetrieveData(startDate),startVal,"Start Value incorrect");
    assert.equal(instance.RetrieveData(endDate),endDate,"End Date incorrect");
    });
   });

I keep getting the error 'cannot read property of RetriveData'...which is odd since StoreDocument is found.

As you might be able to tell, it's kind of my first Truffle test, so any tips or even good resources would be much appreciated!


texts: How to send ERC20 automatically from contract to beneficiary upon receiving

texts:
I want to send both ether and ERC20 automatically from contract address to beneficiary. Following is the code that I've written to send ether -

contract FundTrans {
    address owner;
    constructor () public {
        owner = msg.sender;
    }
    mapping (address => uint256) balances;
    function () payable private {
       owner.transfer(msg.value);
    }
}

I don't know how this will work for erc20. And if there are any improvements or correction in the current code please do give me suggestion.

Thanks in advance


texts:
I want to guarantee that user has enough Eth to execute back().

When you set little amount of eth in msg.value, there are no revert.
However, if you set almost of all Eth you have, the revert is occurred.

Even if you have enough Eth msg.value + Gas fee, the revert is occurred.

Why?

You can try this in Remix.

Choose Environment
Choose Account which has 100 Eth
Set Value to 90 ether.
Execute back and revert.

Why?

    pragma solidity ^0.4.24;

    contract Back is Ownable {

      using SafeMath for uint;

      modifier affordPay() {
        require(msg.sender.balance > msg.value, "You don't have enough eth!!");
        _;
      }

      function back() external affordPay() payable {
        msg.sender.transfer(msg.value);
      }

    }


texts: How to make user sign up and login on my decentralized application?(on production it should work without metamask)

texts:
Assuming that user who is going to signup is not having any ethereum account so how can I generate a public, private key and address for ethereum and make use of it to make further transactions.
Users of my portal are not expected to have one ethereum account.


texts: Wrong address derived from the private key

texts:
I try to create and sign a transaction using ethereumjs-tx, as follows: (same code as in here, except the private key)

var Transaction = require('ethereumjs-tx')
var tx = new Transaction()
tx.nonce = 0
tx.gasPrice = 100
tx.gasLimit = 1000
tx.value = 0
tx.data = '0x7f4e616d65526567000000000000000000000000000000000000000000000000003057307f4e616d6552656700000000000000000000000000000000000000000000000000573360455760415160566000396000f20036602259604556330e0f600f5933ff33560f601e5960003356576000335700604158600035560f602b590033560f60365960003356573360003557600035335700'
var privateKey = new Buffer ('8ad6...........................................................', 'hex')
tx.sign(privateKey)
console.log("tx.from = "+tx.getSenderAddress().toString('hex'));

For privateKey, the first argument I supply is the value of "ciphertext" in my private key file (64 characters). However, in the last line, the address generated does not match my account's address. Am I doing something wrong?

My address is on testnet. Is this library only valid for the mainnet? I don't think so, moreover, I think private key files are interchangeable among the two networks, but I'm not sure.

Thanks for any help,

Update

According to this answer, the text I copy-pasted from the keystore file is not the private key, but its encrypted version with my passphrase. Decrypting it leads to the question How do I get the raw private key from my Mist keystore file?


texts:
I am trying to update a value in a struct that is mapped. I tried updating a value in the smart contract, it asked me to confirm the transaction but when I check the value it doesn't seem to change please help as I'm new to solidity
My smart contract

contract Project {
    string public name;
    uint public postCount = 0;
    uint public docCount = 0;

    mapping(uint => Doc) public Docs;

    struct Doc {
        uint id;
        string title;
        string content;
        address author;
    }

    event DocCreated(
        uint doc_id,
        string title,
        string content,
        address author
    );

    event DocUploaded(
        uint doc_id,
        string title,
        string content,
        address author
    );

    constructor() public  {
        name="project";
    }

    function uploadDoc(string memory _IPFShash, string memory _title) public {
        //upload documents to IPFS get hash then save hash on to blockchain
        docCount++;
        //make a doc
        Docs[docCount] = Doc(docCount, _title, _IPFShash, msg.sender);

        //Trigger Event, solidty provides a way for users to track events and test
        emit DocCreated(docCount, _title, _IPFShash, msg.sender);
    }

    function updateDoc(uint _id, string memory _IPFShash, string memory _title) public {

        for (uint i = 0; i <= docCount; i++) {
            if(Docs[i].id == _id){
                Docs[i].content  = _IPFShash;
            }

        //Trigger Event, solidty provides a way for users to track events
        emit DocUploaded(_id,  _title, _IPFShash, msg.sender);
        }

    }

}
************************************************************************************
//im calling this with this react script
    updateDoc(id, content, title) {
        this.setState({ loading: true })
        this.state.project.methods.updateDoc(id, content, title).send({ from: this.state.account })
            .on('receipt', (receipt) => {
                console.log('loaded')
            })
        window.location.reload()
    }


texts: Relation Between 'testrpc', 'embark simulator', 'embark run development' and 'Intelij idea'

texts: I am very much confused on the relation between these four different stuffs (testrpc, embark simulator, embark run development, inellij idea ) . I have installed these all on Ubuntu . My question is how these are related to each other . There are different documents regarding these stuffs but I didn't found  understandable  relations on them .


texts: Enabling truffle compile optimizer does not change the deployment gas cost

texts:
I am trying to deploy my contract by enabling the optimizer to see how much I can save from the gas costs.

I am using truffle for the deployment. In truffle I enable the optimizer by the following setting in truffle-config.js:

  compilers: {
    solc: {
      version: '^0.5.0',
      settings: {
        evmVersion: 'byzantium' // Default: "petersburg"
      },
      optimizer: {
        enabled: true,
        runs: 500
      }
    }
  }

To compile the contracts and deploy them again I execute:

truffle compile --all

and

truffle migrate --reset --network develop

However, both with optimizer enabled or disabled I get the exact same number gas used when deploying:

   > gas used:            2199134
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.04398268 ETH

So I thought, maybe there's nothing to optimize. But interestingly, if I try the optimizer in Remix I see changes. I use the default compiler 0.5.12+commit.8809ece9 in Remix:

Without optimization in Remix:

 gas    2037733 gas
 transaction cost   2037733 gas
 hash   0xd4d34170c7c234cea900dcad62ac....

Turning optimizer on:

 gas    1531138 gas
 transaction cost   1531138 gas
 hash   0xb5f2bb985e0dfd29b1947c14fc949bab314...

I suppose there's something wrong with truffle or I can't command truffle to recompile with the optimizer. What could be the issue?

Edit:

I've tried adding a deliberate error to the truffle-config.js to see if truffle recognizes the new file and it works, it throws an error.

Removing build/ folder between compile and deploys had no effect.

I also checked bytecodes by enabling and disabling the optimizer and the they are exactly the same.

Very interestingly a day later, the total gas consumed for deployment changed. In this case, the optimizer was enabled initially. So I tried rebooting and disabling the optimizer but did not observe any change in bytecode or deployment costs.

   > gas used:            1857253
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.03714506 ETH

Edit 2
Another thing I tested is if the compile --all command works, i.e. if truffle indeed force compiles even if the code does not change. To do that I've ran 6 compile&migrates. Each time I included an else block or removed it, or enabled or disabled the optimizer, or both. The optimizer runs 1500 times.

|                        | Test 1  | Test 2  | Test 3  | Test 4  | Test 5  | Test 6  |
|------------------------|---------|---------|---------|---------|---------|---------|
| Else block included?   | Yes     | Yes     | No      | No      | Yes     | No      |
| optimizer enabled?     | No      | Yes     | Yes     | No      | No      | Yes     |
| Deployment cost in ETH | 0,04766 | 0,04766 | 0,04709 | 0,04709 | 0,04766 | 0,04709 |

This shows compile --all is not the issue as Test 5-->Test 6 yields the same ETH cost: forcing to compile optimized by changing the contract code and enabling optimizer at the same time results same as just changing the contract code.

Edit 3

Tried changing the EVM version in truffle-config.js. The deployment costs do change. It's only enabling the optimizer that does not cause any change at all.


texts:
I've been looking for a javescript/nodejs package that would take a passphrase as input and generate a public key. But I need it to produce the exact same public key with the exact same passphrase - meaning, based on what I've figured from my research, it needs to use the same salt and seed every time.

With that in mind, so far I haven't been able to find such a package. Pretty much all the packages I've found generate a random seed and a random salt every time they generate a new key, so they don't meet my needs. I did find eth-lightwallet, but I run into an error when trying to run it - "can't find encStr of undefined". Here's the code:

var lightwallet = require("eth-lightwallet");
var salt = 'xgs7or/CAKh8I7cwhAicoXg1pBYXeouc+nzdVZ0PQXs=';
var secretSeed = 'category change resist inspire dove rocket hotel gadget return cream nut receive';
var x = "1234567890098765432112345678900987654321";

lightwallet.keystore.deriveKeyFromPasswordAndSalt(x, salt, function (err, pwDerivedKey) {var ks = new lightwallet.keystore(secretSeed, pwDerivedKey, "m/0'/0'/0'", salt); ks.isDerivedKeyCorrect(pwDerivedKey)})

Can you help me out? remember, I need it to produce the exact same public key when it's given the same passphrase.


texts:
I have a service where users can buy my product. Besides paying by card, I want to be able to allow users to pay in ETH. I think that it will correctly generate addresses for each user so that it is possible to follow the balance.On the sever I have run geth, and users get their addresses via the rpc request. But if someone is hacked server, he can withdraw all amounts. How can I can I provide secure wallet?

Any suggestions would be much appreciated.


texts: Why function defined in parent contract uses parent contract's variable instead of using variable from derived/child contract?

texts:
So i have a code that really confuses me
pragma solidity ^0.6.0;

contract A {
    uint private x = 123;

    function getVariable() public view returns(uint) {
        return x;
    }
}

contract B is A {
    uint x = 234;
}

From the code above when I deploy the contract B and call getVariable function which it inherited from contract A it returns 123 instead of 234, why is that?
and how to make the function getVariable() use contract B's variable instead?


texts: How to specify the Gas price for ICO contract

texts:
I am writing a ICO contract in truffle using openzeppelin

I used the below code in the truffle.js and I am trying to launch in mainnet. When I tried this I could see that the transaction is using the 100Gwei which is too high.

Question :

How much is the minimum gas and gasPrice for an ICO using open Zeppelin
If we are not going to give the gasPrice, will it set to 100 Gwei as default ?
Please let me know the best values for these to parameters "gasPrice :" and "gas:"

 The below transaction hash which showing the Gas Price: 0.0000001 Ether (100 Gwei)

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

truffle.js

module.exports = {

// See http://truffleframework.com/docs/advanced/configuration
  // to customize your Truffle configuration!

networks: {

mainnet: {
  provider: infuraProvider('mainnet'),
  gas: 400000,
  network_id: '1'
}

},

solc: {
optimizer: {
  enabled: true,
  runs: 200
}
}

};


texts:
Can somebody please help me? Created and deployed a smart contract and now ETH is stuck in it and won’t show in the creator’s account. any way to get it using the creator’s PK? Need help so badly, please. Thanks a lot in advance!
CONTRACT ADDRESS: 0x2193B9F2B5E5051E41C32c71B25587D6A6f045C8
You may also reach me at cryptojiru@gmail.com


texts: An Ethereum application that I want to use talks about needing "gas" to run.  What is gas, and where do I get it?


texts: How do you get events from a function in another contract?

texts:
I have two contracts :

// contract #1
contract eXample {
// intizializer
  function eXample{
   .....
  }
//creating the Event
  event MyEvent(uint x,uint y,uint z);
  function doSomething{
    .....
// calling the event inside doSomething function
   MyEvent(x,y,z);
  }
}

contract contractCaller {
  ....
// creating an instance of contract #1
  eXample instance = eXample(address)
 // calling fonction from contract #1 inside contract #2 method.
  function exampleFunction{
    instance.doSomething
  }
  // everytjing inside eXamplefunction is working. Everything inside instance.doSomething IS working. Only issue is the Event not triggering.
  ....
}

I'm using function from "eXample" in "contractCaller" everything works fine but one thing. When calling instance.doSomething from the 2nd contract i'm not returned any Event from the 1st contract in either mix/ on the blockchain.Obviously i have watchers,etc.

Is it normal ?
Should i make custom Events on my 2nd contract for functions on the first contract ?

How do you guys usually proceed ?

Edit better example since i messed up the first one :

contract metaCoin {
  mapping (address => uint) public balances;
  function metaCoin() {
    balances[msg.sender] = 10000;
  }
  event ExampleEvent(uint x);
  function sendToken(address receiver, uint amount) returns(bool successful){
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    ExampleEvent(balances[receiver]);
    return false;
  }
}

contract coinCaller{
  function sendCoin(address coinContractAddress, address receiver, uint amount){
    metaCoin m = metaCoin(coinContractAddress);
    m.sendToken(receiver, amount);
  }
}

When calling CoinCaller.Sendcoin. ExampleEvent won't trigger even with a watcher on the MetaCoin Contract.


texts: Please Help. Fail with error 'Min return not reached'

texts:
Does anyone know how to solve this? This is the first time I use Metamask to swap ShibaInu, however it's failed.
https://etherscan.io/tx/0xa9a150efcb8ed43cdac2c30ff4a7c7ea551716d2b8449326f66d6826fea99507


texts: Can a full mining node choose to keep a transaction for itself and pass it in the next mined block?

texts: the idea is if a malicious mining node choose to keep a transaction for itself and not propagate it to the network until the same node find a block and post that transaction in it, so the node will be able to pick the timestamp and the block number for that transaction ? and exploit a time-dependency functions inside a smart contracts.


texts: Using getStorageAt() on mapping(address => uint64[])

texts:
Given the contract variable mapping(address => uint64[]) public foo, can anyone help me access the data using web3?

Assuming we have the account address (0xF89...) and that foo is in slot 5, I can access the length of the array using:

key   = '00000000000000000000000xF895a7D153d80A52aE9C32C30400e000censored'
index = '0000000000000000000000000000000000000000000000000000000000000005'
let varAddress = web3.sha3(key + index, {"encoding":"hex"})   // k . p
let res = web3.eth.getStorageAt(contractAddress, varAddress);

But I haven't been able to figure out how to access the data in the array itself.

I've been trying to decipher the relevant section in Layout of State Variables in Storage, and this article was also helpful, but can't quite get it. Any help?


texts: How dynamic data structures works in storage space?

texts:
Storage variables are allocated statically and I understand that. I am curious then how dynamic data structures (like mappings) works if they can grow and shrink during contract's life-cycle but memory for them is allocated only once (when contract was deployed)?

(Feel free to correct me if I misunderstood something.)


texts: How to get pending transactions with using geth or other client?

texts:
I would like to get pending transactions with using geth.

And I tried to use 'web3.eth.pendingTransactions' on geth console.
So the geth returned '[]'.

> web3.eth.pendingTransactions
[]

But I visited Etherscan's pending transactions page.

They could display pending transactions.
It was displayed 'A total of 74,945 pending transactions found' and the transactions list.

Why can they gain pending transactions with elapsed time ?
Is this possible with using geth or other client ?
Or is this the software of their own developing ?

I'd like to get pending transactions with using geth via web3.js (or with using other client via other node.js library).


texts:
I am trying to use the send on a certain block feature with parity wallet.
I am on windows 7 and installed parity and successfully have it running in the background with the --warp option (I can see the terminal running in background). When I go to send eth I get the following window:
Parity Signer: Pending
I tried everything in this post with no luck
Simple ether transfer from parity wallet

My ether is now stuck in the wallet. any help would be great thanks.


texts: How many bootnodes are hardcoded into Ethereum clients?

texts:
Bootnodes are supposed to act as entry points for new nodes into the Ethereum network. How many such bootnodes are hard-coded into Ethereum clients?

Also, Who maintains these bootnodes and what happens if they stop functioning?

P.S. An year ago, it was mentioned that there are 3 hard-coded bootnodes.


texts: For what data does Ethereum use Memory Database, and for what does it use Level Database

texts:
Ethereum uses two databases Memory database and Level Database. Is data stored in MemoryDatabase different than LevelDb? In what cases is one database used over other?

The question is different from -Which database(s) do the ethereum clients use and why?
That question answers why LevelDb is used. This question is about how MemDB and LvlDb are different, why they are used, is the data stored in both databases different?


texts:
I am trying the sendSignedTransaction in Ropsten and I assigned the value of gas limit and gas price:

gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))

but I got this error :

(node:18596) UnhandledPromiseRejectionWarning: Error: Returned error: transaction underpriced

what's my mistake?

how can I assign these value as a correctly?

thank you


texts: Is there something like "metrics" and "monitor" modules for Kovan?

texts:
I would like to monitor some parameters for Kovan and Rinkeby clients. Geth provides a monitor module that works with Rinkeby specifying --metrics when launching the client, and attaching to the client by geth monitor --attach=http:127.0.0.1:8545 parameter. I'm unable to do the same with Kovan, which is launched using parity. This https://github.com/paritytech/parity-ethereum/issues/572 makes me think something similar could be implemented.

Any help would be appreciated.


texts: Do I need to encrypt the keystore file(s)?

texts:
When I run cat on one of the files in the keystore directory I see things like id, mac, etc. but I do not see private key.

Is it safe to send the keystore file unencrypted over the internet?

If the private key is in the file, which one is it and can I simply keep a copy of the private key and restore everything from only the private key?

Thanks


texts: Wouldn't a smart contract that deals with regulated markets need legal paper work to be legal?

texts:
By regulated markets I mean: finance, gambling and insurance, but also others.

So let's say, you have your DAC (is that still common terminology?) and let's say you figured out some oracles that feed the DAC with real world events so that the DAC can function.

But the DAC is operating in a regulated market. What is the legality of this thing?

Are the developers required to file paperwork?
Are the oracles, presumably people "employed" by the DAC, to feed it with real world events, required to file paperwork?
Are the clients of this DAC required to file paperwork?

I know this is still a gray area, but I welcome any relevant information.

Note: I noticed the terminology regarding oracles has changed. I am using "oracle" to mean any input of data from real world to the DAC.

Jurisdiction: EU and US


texts: Importing Parity/OpenEthereum private keys to Geth: got zero balance

texts:
I have to migrate to Geth from Parity/OpenEthereum as the latter completely stopped syncing for me.
First of all I tried to copy one of my private keys exported with parity_exportAccount() - which appears to have a format pretty similar to Geth into Geth keystore:
$ cp myaccount.json ~/.ethereum/keystore/UTC--2020-09-11T05-44-30.451420645Z--0x1234561234561234561234561234561234561234

Now I see my account in Geth JS console - and I even can unlock it with web3.personal.unlockAccount(). But whenever I'm trying to call web3.eth.getBalance(), it always returns 0 - as well as web3.eth.getTransactionCount().
Of course, I have already ensured that my account has non-zero balance on etherchain.org. I'm also sure that my Geth instance is in sync.
What should I do in order to make Geth recognizing my imported wallet's balance? Do I have to run something similar to Bitcoin-Core's -reindex option, or I'm doing something completely wrong? In the latter case, which procedure should I follow to correctly migrate?


texts: Token distribution in smart contract? Safemoon et al

texts:
The SafeMoon (and copycats) doing the rounds on BSC right now have a mechanism to distribute additional tokens to token holders over time.
I'm curious as to how this works. Presumably having it in the token contract every transaction would run up big gas fees, and I can't see any mechanism in the contract for doing so.
Here's the contract - https://tokensniffer.com/contract/0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3
I'm not sure if I'm missing something obvious or there's some other means of distro? Can anyone advise?
Thanks


texts: Is it possible to review the 'payload' of a signed transaction string before posting it?

texts:
Some wallet apps let you generate a signed transaction if you do not have access to the internet on a device or if you want to have it ready to send at a later time.

Is it possible to decode that string so that you can at least verify the recipient address as well as the amount to be sent to ensure there are no typos or bugs in the wallet app before it's posted?


texts: Compiling and deploying Registrar.sol in private network

texts:
I created a contract using go-ethereum console, I want to deploy registrar in private network. I found out a way to compile and deploy in https://github.com/ethereum/dapp-bin/tree/master/registrar

But I don't know how to compile contract: Registrar.sol.


texts:
Describe the bug
I am trying to call the public variable "workCount" from a smart contract using web3
Steps to reproduce:
const work = new web3.eth.Contract(ABI,Address)

const workCount = await work.methods.workCount().call()

Expected behavior
I am expecting these two lines of code to return the value of workCount
Actual behavior:
Once I run the application I get the following error:
Uncaught (in promise) TypeError: work.methods.workCount is not a function

if I change the code to the following:
const workCount = await work.methods.workCount.call()

then this error is shows up:
Uncaught (in promise) TypeError: Cannot read property 'call' of undefined

Contract Code:
pragma solidity ^0.5.0;

contract workReg {
  uint public workCount = 0;

  struct Work {
    uint id;
    string authorName;
    string workType;
    string description;
    uint amount;
  }

  mapping(uint => Work) public works;

  constructor() public {
    createWork("Heba","Book", "IP blockchain book", 100);
  }

  function createWork(string memory _authorName, string memory _workType, string memory _description, uint  _amount ) public {
    workCount ++;
    works[workCount] = Work(workCount, _authorName,_workType, _description, _amount);
  }

 function getID() view public returns(uint){

    return  works[workCount].id;
}

 function getworkType() view public returns(string memory){

    return  works[workCount].workType;
}

 function getdescription() view public returns(string memory){

    return  works[workCount].description;
}

function getAmount() view public returns(uint){

    return  works[workCount].amount;
}

}


texts: If I wanted to host a site that used the web3 api, would I need it to interact with the blockchain?

texts:
I want to host a site to interact with Web3 clients (MetaMask, etc.). I want my site to be able to send transactions, etc. to the clients through the Web3 API for educational purposes.

I don't care if the transactions don't go through, but does my site actually need to have a local blockchain instance running to allow me to produce transactions for people using MetaMask?


texts: How to use Web3Js to sign a message in a react native mobile app

texts:
I am very new to Ethereum. I have requirement to sign the app using Web3JS in my React native mobile App.

I used this link to get web3js working properly.
But I am not sure how to connect to wallet in mobile app. Please guide. Thanks.


texts: How strong are the checksums in Ethereum addresses?

texts:
2 options for Ethereum addresses which have checksums are ICAP and EIP55.  Are there others?

For each option, how strong are the checksums?  What is the chance that a typing mistake (or mistakes) will still lead to a valid Ethereum address?


texts: Why is my web3.eth.getBlock("pending", true) not working as intended?

texts:
So I was playing around with the web3, but having problem to get the transactions from a block (following https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetblock)

var BlockPromise = web3.eth.getBlock('pending', true);
console.log("Block TX: " + BlockPromise.transactions[0]);

I would expect to get a transaction. However, I am only getting a [object Object]

What is my mistake?
FYI: I do not have a coding degree.


texts: Parity installed. How to convert to ethereum classic chain?

texts:
I have recently purchased some ETC (ethereum classic tokens). I wanted to stored them in Parity. I have installed the Parity (Homestead?-same). Then I tried to convert to ETC chain by CD>parity--chain classic.

I get the message "Parity is not recognised as an internal or external commands operable program or batch file". What should I do? As I am new I appreciate very much if you can give me a step by step guide. Thank you.


texts: Transaction rejected anytime I try to interact with a smart contract, what is wrong?

texts:
it seems like a very simple contract, but everytime I tried to send some ETH to the smart contract, it says transaction rejected. I did include '''address payable''' in the code, so what is wrong?
'''
pragma solidity 0.5.17;

contract Bet {

uint256 public betSum;
address payable public owner;

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

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

function checkSum() public view returns (uint256) {
    return betSum;
}

function withdrawEther(uint256 amount) external payable onlyOwner {
require(address(this).balance>=amount, 'Error, contract has
 insufficent balance');
owner.transfer(amount);

}
}

'''


texts: What are the available options (March 2021) for bridging tokens across the chains?

texts:
Actual problem in mind
I would like to release a token for the Island DAO.
I'm worried that ETH gas prices are prohibitively expensive - if I use ETH, the smaller guys will not come.
But ETH is the chain with the most amount of capital - if I don't use ETH, the bigger guys will not come.

That is why I would like to have best of both worlds from the ground up

Be available on Ethereum mainnet
Be available on other, much more affordable chain

Projects in the space

Binance bridge: https://www.binance.org/en/bridge
AnySwap bridge: https://anyswap.exchange/bridge
XDAI omni bridge: https://omni.xdaichain.com/
ETH / BSC / Terra shuttle: https://github.com/terra-project/shuttle
UPDATE. Yet another bridge: https://burgerswap.org/

Additional consideration: Oracles and other parts of DeFi ecosystem?
That is on the ETH chain only, BSC does not have native oracles deployed to the mainnet.


texts:
When constructing the path for a node in a wallet tree, the default value for cointype is 60 for ethereum.

Why is that?


texts: Why does geth import block entries, receipts and headers when chainstate is up to date?

texts:
I initially ran geth --fast to sync the blockchain.

Now at ~163GB, each time I restart geth (without fast), and do geth attach -> eth.syncing it starts from currentBlock:0. I do have --cache=1024 set. Sample output after some time of syncing:

> eth.syncing
{
  currentBlock: 2406901,
  highestBlock: 5243532,
  knownStates: 3323202,
  pulledStates: 3295634,
  startingBlock: 0
}

Logs

elapsed=7.064ms   number=3124877 hash=65ce7a…d78803 size=511.42kB ignored=0
INFO [03-12|19:10:53] Imported new block headers               count=960  elapsed=73.505ms  number=3130944 hash=22a327…6bdc80 ignored=0
INFO [03-12|19:10:53] Imported new block receipts              count=839  elapsed=108.746ms number=3125716 hash=6cbb1f…acdcb2 size=4.81mB   ignored=0
INFO [03-12|19:10:53] Imported new block receipts              count=1203 elapsed=111.895ms number=3126919 hash=9bd7d9…f05e79 size=5.52mB   ignored=0
INFO [03-12|19:10:53] Imported new block headers               count=1152 elapsed=162.272ms number=3132096 hash=8f513f…592be3 ignored=0
INFO [03-12|19:10:53] Imported new block headers               count=192  elapsed=21.768ms  number=3132288 hash=b1bc5b…56f68b ignored=0

Why is this happening? Is it actually re-syncing the blocks or just loading/importing blocks into memory? How can I force it to pick up where it left off instead of going through this process each time?

edit: For some reason my startingBlock is always 0, which I think might be the crux of the issue.


texts: Only see the last item of struct using for loop in web3.js

texts:
I don't understand what mistake I did in my code. I created a folder before and I was successfully see the correct result of smart contract. For more clarify ,
Actually I want to see the struct result from my smart contract to webpage through web3js. I was able to see the correct result before. But now I'm unable to see the exact result. It's just show me the last item of struct.
Here is my code:
index.js
for(var i=1; i<=2; i++){

    contract.methods.getInfo(i).call().then(function(view){

        var distributionResults = $("#distributionResults");
        distributionResults.empty();

        var centerSelect = $('#centerSelect');
        centerSelect.empty();

        var id = view[0];
        var name = view[1];
        var ppeCount = view[2];

        console.log(id+" "+name+" "+ppeCount+"\n"); //here I got the correct result.

        var template = "
" + id + "	" + name + "	" + ppeCount + "
"
        distributionResults.append(template); //inside this I got only last item

        var centerOption = "<option value='" + id + "' >" + name + "</ option>"
        centerSelect.append(centerOption); // got only last item

    });
}

index.ejs

                      ID
                      Name of Authorized Center
                      Balance of PPE

smart contract
pragma solidity ^0.5.1;

contract MyContract{

    //Model of PPE
  struct Center{
    uint id;
    string name;
    uint ppeCount;
    address receiver;
  }
  mapping(uint => Center) private centers;

  //store center count
  uint public centerCount;

  // For public view

  struct PublicView{
      uint id;
      string name;
      uint ppeCount;
  }
  mapping(uint => PublicView) public _view;

  //constructor
  constructor() public{
    addCenter('Health Ministry',A1);
    addCenter('Division',B1);

  }

  uint  balance;
  uint  baln;

  uint  bonus;

  //add center
  function addCenter(string memory _name, address _receiver) private {
    centerCount++;
    centers[centerCount] = Center(centerCount, _name, 0, _receiver);
  }

  function distribution(uint _centerId,  uint _amount) payable public{

      require(_centerId >0 && _centerId <= centerCount);

      if(_amount<100){
        revert('Sorry you have to send atleast 100 ppe');
      }

      distributors[msg.sender] = true;
      centers[_centerId].ppeCount+=_amount;

      countDown++;
      sender[countDown]= msg.sender;

      if(_centerId == 1){
        balance+=_amount;
        bonus+=100;
        _view[_centerId] = PublicView(_centerId, 'Health Ministry', balance);

      }
      if(_centerId == 2){
        baln+=_amount;
        bonus+=100;
         _view[_centerId] = PublicView(_centerId, 'Division', baln);

      }
      emit distributionEvent(_centerId, _amount);
  }

    function getInfo(uint index) public view returns(uint, string memory, uint){
        if(_view[index].ppeCount == 0){
            return (centers[index].id, centers[index].name, centers[index].ppeCount);
        }
        return(_view[index].id, _view[index].name, _view[index].ppeCount);
    }

}


texts: Strange behavior referencing struct objects in local scope

texts:
Trying to work with a linked list I came across this strange behavior. Here the code

contract Test{

  struct Node{
    uint x;
    uint linked; //index to next
    bool    nil;

  }
  Node [] public nodes;

  function Test(){
      nodes.push(Node(59,1,false));
      nodes.push(Node(100,2,false));
      nodes.push(Node(0,0,true));
  }

  function remove(uint nodeIdx){
      Node node = nodes[nodeIdx];
      Node linked = nodes[node.linked];
  }

}

If I call remove(1) I should expect to see node equal to {100,2,false}, but in the debugger I got the following

Or in other words, node.x is valued with the length of the nodes array. I wonder why

Moreover,

calling remove(anotherIndex) gives same results.
declaring local var Node storage node=nodes[nodeIdx] gives same result


texts: Events not working in Trust wallet or Metamask

texts:
Recently, I've developed an Dapp using pure vanilla js and it's contract is currently deployed on etherscan.When someone buys a token, it should increment..Everything's working fine but in the trust wallet(A mobile dapp browser) doesn't seem to call events..
My Dapp is heavily rely on events..
window.addEventListener('load', async() => {
  if (window.ethereum) {
    const web3 = new Web3(window.ethereum);
    try {
        const result = await window.ethereum.enable();
        if (result) {
            return web3;
        }
    } catch (error) {
        er(error)
    }
} else if (window.web3) {
    const web3 = window.web3;
    return web3;
} else {
    er(
        "Non-Ethereum browser detected. You should consider trying MetaMask!"
      );
    }
});

var buy_events = contract.Buy({ buyer: web3.eth.coinbase }, function(error, log) {
if (!error) {
    $.ajax({
        type: 'POST',
        url: 'referral',
        data: {
            buyer: log.args.buyer,
            token: log.args.tokenToTransfer.c[0],
            tokentra: log.args.tokensTransfered.c[0],
            hash: log.transactionHash,
            ref_bal: log.args.referralBal.c[0],
            events_be: log.event,
        }
    });
  }
});
 buy_events.stopWatching();

Solidity
event Buy(
     address indexed buyer,
     uint256 tokensTransfered,
     uint256 tokenToTransfer,
     uint256 referralBal
 );

Ps: I'm using injected web3 by metamask


texts:
I've recently started to use Truffle to automate/speed up my development.

As I'm still getting the grasp of it I've come up with a barrier when trying to use INFURA for migrations.

INFURA nodes don't answer to blockFilter requests and as so migrations in Truffle don't work as stated in their Truffle + INFURA integration post.

Any ideas on how to make this work besides changing Truffle's code to polling instead of receiving events? :)

EDIT: After searching for any solution to validate deployment of contracts I just settled for Augur's great public node that exposes filter methods.


texts:
I have no experience with solidity and haven't yet found any introductory guide that doesn't assume considerable prior knowledge, so I admit I'm struggling somewhat. If there was a true beginners guide around that would indeed be fantastic.

Anyway - the "token" and "crowdsale" sample code on the ethereum foundation website, I've managed to hack and chop up and get things working as I intended, by a process of change-that-and-see-what-happens.

I wonder if someone could point me towards any kind of example for locking tokens until the creator unlocks them. I presume that this can be achieved with a bit of code that somehow adds that characteristic to the token, in the token creation contract. There would need to be an exception for the "crowdsale" contract, of course. And then, what, would the creator send some kind of message to the contract in order to trigger the unlocking?

(NB: I gather that there are very good existing contracts on github such as under the Zeppelin project, but I'm afraid that since they come with no explanation beyond a file name, nor any real guidance as to how to use them, I really have no idea what to do with them or how to modify for my needs, or what exactly they do in the first place!)

Many thanks,


texts: Why would the gas cost be so high on a simple contract?


texts:
Seems like there are many related questions ex: here, but I still can't believe it is not supported in remix or am I misunderstanding it? seems like it is supported in production.

struct Test {
    address receiver;
    string date;
}

mapping(address => Test[]) public testInfo;

function getTestInfo(address _account) public constant returns (Test[]) {
    return testInfo[_account];
}

Is there anyway to execute that code and return an array of Test?


texts: Is There any way to check if the entered key is having a corresponding value in a mapping or not?

texts:
Suppose In a banking system many people are enrolled (managed through mapping )
     mapping (address => bool) enrolled;

And only those can deposit who are enrolled in the bank.

Can I check if the msg.sender exists as a key in the above mapping?


texts: How to get eth network hash rate from Etherscan API?

texts: I have looked through all of the docs (https://etherscan.io/apis) and couldn't find how to get this from their APIs, yet they display this number in multiple places on their site. Was hoping for some guidance.


texts: How can I use a proxy contract with ethers.js?

texts:
I'm trying to test a contract via a proxy, but I don't know how to create an instance of a the contract proxy to call the delegate functions.
I'm using typescript, ethers.js with hardhat
The contract Adder have two function called addOne and theCounter which adds one and returns the current value of the counter respectively.
how can I call addOne on the proxy contract so the fallback function fires?
here is the test I'm trying to write :
import {expect} from 'chai'
import {ethers} from 'hardhat';

describe("Proxy", () => {
  it("should call addOne on delegate", async () => {
    const Delegate = await ethers.getContractFactory("Adder");
    const Proxy = await ethers.getContractFactory("Proxy");

    let adder = await Delegate.deploy(0);
    let proxy = await Proxy.deploy();

    await adder.deployed();
    await proxy.deployed();

    await proxy.functions.upgradeDelegate(adder.address);

    // TODO : how can I call the function addOne() on proxy???

    expect(await adder.theCounter()).to.equal(1);

  })
});

this is the code of the proxy:
pragma solidity <0.8.0;

// SPDX-License-Identifier: MIT

contract Proxy {

    address delegate;
    address owner = msg.sender;

    function upgradeDelegate(address newDelegateAddress) public {
        require(msg.sender == owner);
        delegate = newDelegateAddress;
    }

    fallback() external {
        assembly {
            let _target := sload(0)
            calldatacopy(0x0, 0x0, calldatasize())
            let result := delegatecall(gas(), _target, 0x0, calldatasize(), 0x0, 0)
            returndatacopy(0x0, 0x0, returndatasize())
            switch result case 0 {revert(0, 0)} default {return (0, returndatasize())}
        }
    }
}

and the adder:
pragma solidity <0.8.0;

// SPDX-License-Identifier: MIT

contract Adder {
    uint public counter;

    constructor(uint init) {
        counter = init;
    }

    function addOne() public returns (uint) {
        counter++;
        return counter;
    }

    function theCounter() public view returns (uint) {
        return counter;
    }

}


texts: How is caller's data related to bytecode?

texts:
I know that smart contract is deployed as bytecode.
When we call a function from application, we use the encoding with the help of ABI and we get some bytes. let's say 220 bytes.
These are the bytes we send in data property of the transaction to the smart contract.
So, our bytes have gotten to smart contract.
Question 1) is it the EVM who will take transaction's data(which in bytes) and then look at the bytecode and then figure out how transaction's data is related to which part of the bytecode and then figure it out ?


texts:
I tried to declare string inside my function but it doesn't work.

How to declare string inside function?


texts: Where to place in Zeppelin crowdsale variables

texts:
In various tutorials and previous releases of zeppelin, variables like _rate were explicit in the code.  Now, however, these are left in a function (SampleCrowdsale), and I'm not sure what I'm supposed to do with that.

https://github.com/OpenZeppelin/zeppelin-solidity/blob/bd84db735deb958064dd954c2994b0b44f142812/contracts/examples/SampleCrowdsale.sol

All the tutorials simply have you define all the variables, then create the coin.  In this new version, are we somehow calling the function "SampleCrowdsale()" outside of the contract itself?  If so, how would one go about doing that. Or are we plugging in the variable values right here?

I'm sure there's some basic overarching idea that I'm missing here, so apart from specifics on how to get this to work, it would be great to understand the overall idea.

Thanks in advance.


texts: How can I stake ETH in Ethereum 2.0 network to earn staking rewards? How much ETH to I need? How much I can earn? How long do I need to wait to get my reward?


texts: How do I filter an event by the hash of the transaction that generated the event?

texts:
I read the following in Andreas Olofsson's answer:

  Events can also be filtered by the hash of the transaction that generated the event

Would someone please post an example of how to do this with oo7-parity.js, web3.js  or ethjs ...

I've not found any particularly helpful examples in the the docs


texts: "Intrinsic gas too low" when deploying contract on the testnet

texts: I get the error message "Intrinsic gas too low" when trying to deploy my contract on the testnet. Pic is my screenshot. I had set the fee slider to max (1.005 Ether). My account balance is 5.9 ether.


texts:
Noob miner here,

Does anyone mining on Dwarfpool know if they have updated to the forked code (ETH), or are we still mining Ethereum classic (ETC)? I currently use Poloniex as my intermediary wallet and they launched the ETC as a separate wallet address.

If i am mining on dwarfpool and the account is pointing to my ETH wallet but we are mining ETC will I loose this mined ETH in the transfer process?


texts: How to prevent modifying blockreward in geth code?

texts:
I found below variables in geth file 'consensus/ethash/consensus.go'

      var (
         FrontierBlockReward       = big.NewInt(5e+18) //..
         ByzantiumBlockReward      = big.NewInt(3e+18) //..
         //..
       )

I have a question about it.

  If I'm a miner and I modify BlockReward(e.g. 10 ether) as I want and
  rebuild the code and participate in main-net, when I succeed mining,
  can I receive modified-BlockReward?

  Otherwise, how to handle this problem? and is there source code in
  geth to  handle it?

Very thank you for your favor


texts: How do newHeads and event subscriptions behave on past reorgs?

texts:
Based on the geth documentation, I understand that a subscription on both newHeads and logs will emit all new heads and events that come from a reorg. However, I couldn't find what the behaviour is when reorg occurs after the client subscribed, but forking from a block before the one of the subscription.

For example:

1.
A -> B -> C
Client subscribes after block C

2.
A -> B -> C -> D -> E
Client receives heads and events from D and E

3.
A -> B -> C -> D -> E
 \-> B'-> C'-> D'-> E'-> F'
Reorg after block A

In the scenario above, on step 3:

Will the client receive the newHeads for just D',E',F', or B',C' as well?
Will the client receive the events from just D',E',F', or B',C' as well?
Will the client receive the removed events for just D,E, or B,C as well?

Thanks!


texts:
I have established a private network and connected with 2 nodes. And I opened the mist using terminal with the command

  "open -a /Applications/Mist.app --args --rpc/usr/local/Cellar/test1/geth.ipc "

mist shows a test network rinkbey I changed as solo network now it shows private-network but I am not connected with these 2 nodes. And when I start mining blocks are not increasing and ethers shows 0


texts: Will this work and be truly cold: Offline cold storage using Bootable USB

texts:
I want to generate a cold wallet very securely without having to buy a new computer that will always be offline and while I am waiting for a hardware wallet on back order.

Please validate and/or challenge my thinking here I am new to ETH and digital currencies:

Download some lightweight linux distro & Github Ethereum to run offline
Turn computer offline
Install the lightweight linux distro onto USB
Turn off computer and boot from USB
Put Github Ethereum onto running linux using second USB port
Generate ETH account
Store private key and creds on the linux distro USB
Make 1-2backups of the private key/creds on separate encrypted USB keys

Is this overkill? Are there gaps in this approach if my computer is already compromised?

Interested to hear your thoughts.


texts: "truffle test" says "assert.rejects" is not a function even it is Node 10

texts:
As per the official documentation, assert.rejects was added since Node v10.0.0.

Also, the node console confirms that:

even though, truffle test throws this error:

 TypeError: assert.rejects is not a function

Because I wrote this snippet in my unit-tests:

  await assert.rejects(async () => {
    await this.contract.createToken(...info, 1, {from: accounts[0]});
  });


texts: Synchronisation failed Invalid old chain

texts: I got this error "Synchronisation failed: Invalid old chain" I tried geth removedb and geth upgradedb but I got the same error again any help please?


texts: Like e.g I created a token and sent it to the wrong contract address how to burn the token from the wrong contract address


texts: Ethereum web3.eth bitcoin move equivalent?

texts:
Is there a Bitcoin "move" equivalent for Ethereum web3.eth ?

In Bitcoin:

move
<fromaccount> <toaccount> <amount> [minconf=1] [comment]
Move from one account in your wallet to another

(https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list)


texts: how do token exchanges work with the limited smart contract methods?

texts:
Looking at the source code for various token implementations (e.g. here and here) They have the following API:

// presume can only be "called" by owner.
Transfer(address to, number amount)

// sender (exchange) must be authorised by owner
Transfer(address from, address to, number value)  {
     require(balanceOf[from] >= value);
    balanceOf[from] -= value;
    balanceOf[to] += value;
}

// presume can only be called by the owner.
authorise(address broker, number value)

If Bob owns 1000 tokens, and wants to sell them, presumably he sets a sale price (e.g. £1 per token) on an exchange (e.g. kraken, bittex)

If Jenny wants to purchase 50 tokens at £1, then the exchange can match this up.

Prior to the exchange, presumably the following takes place:

Bob registers his account (not wallet) with the exchange. He gives them his public key, e.g. 0x123
Jenny registers her account public key with the exchange, e.g. 0x456
Bob authorises the exchange (which also has an account) to transfer 1000 tokens*

Presumably the following flow takes place for the exchange?

Jenny deposits £50 into her account with the exchange (although many exchanges don't seem to support this) from her bank incurring bank charges.
exchange deducts £50 from Jenny's fiat balance held locally (not in blockchain)
Exchange issues transfer(bob, jenny, 50)
Exchange waits for X confirmations?
put the money into Bobs fiat account held at the exchange
Bob withdraws the money into his bank account or similar (incurring bank charges)

Questions:

Is the above flow correct?
If the exchange only receives X-1 confirmations, did the token transfer take place, and what does the exchange do with the money now?  Give it to Bob, or back to Jenny?
In the transfer function, it checks from has enough tokens, then deducts the amount.  What happens if this method is called twice at the same time? Potentially we have the situation that both check the balance is ok, then both deduct the amount, leading to a negative balance or similar. Are these methods synchronised (so only one user can be calling the function at a time)? I assume not because of the "The DAO" theft issue. In which case does Ethereum rely on assertions to catch Concurrency issues?  If so does it "rollback" the credit to Jenny (I haven't seen any code for this). I assume this is made worse by the fact that the order of application of transactions is not guaranteed.
There is no record on the blockchain of the monetary value of the transaction right?  It is only recorded in the exchange.
Does the exchange get its fees by taking some of the tokens (so jenny gets less than 50)?


texts: It is always ok to assume sequential block number order?

texts:
I am writing a visualisation application; I need to get transactions from multiple blocks from the blockchain. However, I am not sure how the numbering of uncles and blocks works. Since Geth client is very slow to query 1000 blocks, I am slowly scrapping data from Geth client and caching it into MongoDB. I currently query the initial block using either its number or hash and then make subsequent queries using block.parentHash, recursively. For a large number of blocks queried in such fashion hurts MongoDB's performance. So if I could assume that block numbers are sequential in order, I could just request 1000 blocks straight away from MongoDB and speed up my application.

So could you please explain how the block number and uncle numbers differ and given 3,500,000 starting block, where I need 10,000 preceding blocks in the chain could I use the $gte and $lt operators to query blocks from 3,500,000 to 3,490,000 and be assured that no uncles will be present, or do I have to rely on block.parentHash?


texts: calling method from another contract throws Revert

texts:
I have a smart Contract "RecommendContract" contains this method:

 function addVacancy(address sender, bytes32 vacancyId, uint256 incentive) external  {

        Vacancy vacancy = vacancies[vacancyId];
        vacancy.incentive = incentive;
        vacancy.owner = sender;

        emit NewVacancy(vacancyId, incentive, sender );
    }

when I cal this method using web3 and nodejs it works fine.
but when I call it using another smart contract it throws an errer : Revert

 function receiveApproval(address _sender, uint256 _value,
        address _tokenContract, bytes data) public {
        RecommendContract recommend = RecommendContract(0x4B3F6Bda49BdF8786554af1aD97D773C450375F0);

         uint8 serviceSelector = extractSelector(data);
          if (serviceSelector == 3) {
            // addVacancy
            emit LogEvent("ADD VACANCY SERVICE");
            bytes32 vacancyId = extractBytes32(data,1);
            bytes32 vacancyId = keccak256(data);
            uint256 incentive = extractUint256(data,33);
            recommend.addVacancy(_sender, vacancyId, _value);

        }

    }

NB: when I remove the ligne recommend.addVacancy(_sender, vacancyId, _value); it works.


texts:
I'm using Meteor and have installed eth-lightwallet by typing

meteor npm install --save eth-lightwallet

and

meteor npm install --save ethereumjs-tx

However, when I import lightwallet from "eth-lightwallet" in my client/main.js

the console shows this error message

/Users/johnhckuo/.meteor/packages/templating-compiler/.1.3.0.nkq99n++os+web.browser+web.cordova/plugin.compileTemplatesBatch.os/npm/node_modules/meteor/promise/node_modules/meteor-promise/promise_server.js:177
      throw error;
      ^

TypeError: Cannot set property '/Users/johnhckuo/Desktop/Block-Farm/app/node_modules/ethereumjs-tx/package.json' of undefined
    at Resolver._resolvePkgJsonMain (/tools/isobuild/resolver.js:320:9)
    at Resolver._resolve (/tools/isobuild/resolver.js:123:25)
    at /tools/isobuild/resolver.js:75:19
    at Entry._reallyRecompute (/Users/johnhckuo/.meteor/packages/meteor-tool/.1.4.2_5.bj91mp++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/optimism/lib/entry.js:215:26)
at Entry._recomputeIfDirty (/Users/johnhckuo/.meteor/packages/meteor-tool/.1.4.2_5.bj91mp++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/optimism/lib/entry.js:179:17)
at Entry.recompute (/Users/johnhckuo/.meteor/packages/meteor-tool/.1.4.2_5.bj91mp++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/optimism/lib/entry.js:46:20)
at Resolver.optimistic [as resolve] (/Users/johnhckuo/.meteor/packages/meteor-tool/.1.4.2_5.bj91mp++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/optimism/lib/index.js:50:18)
at ImportScanner._resolve (/tools/isobuild/import-scanner.js:466:36)

I've tried using Meteor 1.2, 1.3 and 1.4, but this error keeps popping out

Any suggestions is appreciated guys !


texts:
I have the same problem as in 'How to apply pyethrecover.py on v3 .json/transfor v3 .json to .v1' referenced here, but in trying the answer's code, I am finding that the Crypto package is not being recognized.

I installed 'Crypto' from within PyCharm and it reports installing (i.e. notification and event logs), but the IDE still shows this it as an 'Unresolved Reference' and produces the error below while running utils.py:

try:
    from Crypto.Hash import keccak
    sha3_256 = lambda x: keccak.new(digest_bits=256, data=x).digest()
except ImportError:
    import sha3 as _sha3
    sha3_256 = lambda x: _sha3.keccak_256(x).digest()

AttributeError: 'module' object has no attribute 'keccak_256'

What am I missing? I am using Python 2.7.10 in PyCharm. Thanks.


texts: Error: "No usable mining devices" despite benchmark is ok

texts:
I am new here, and this is my first question.
I have just installed ethminer on ubuntu 20.04 and it seems that everything is ok in the settings:

The command  ethminer --list-devices  gives

ethminer 0.19.0-17+commit.ce52c740
Build: linux/release/gnu

 Id Pci Id    Type Name                          CUDA SM   Total Memory
--- --------- ---- ----------------------------- ---- ---  ------------
  0 03:00.0   Gpu  GeForce GTX 1070              Yes  6.1       7.37 GB

Running a benchmark with the commad ethminer -G -M 0 works well

Moreover clinfo gives the following

Number of platforms                               1
  Platform Name                                   NVIDIA CUDA
  Platform Vendor                                 NVIDIA Corporation
  Platform Version                                OpenCL 1.2 CUDA 11.2.109
  Platform Profile                                FULL_PROFILE

Nevertheless when I try to really run ethminer  by typing for example:
ethminer -G --report-hr -P stratum1+tcp://XXXXXXXXXXXXXXXXXX.@eth-eu1.nanopool.org:9999

then I get:
ethminer 0.19.0-17+commit.ce52c740
Build: linux/release/gnu

Error: No usable mining devices found

Do you have any idea on what is happening here?


texts:
How does hosted wallets works, Anyone can write about it step by step?

I have noticed, Companies who provides hosted wallets stores all funds of their users and users are just provided deposit address. And when you check balance of your address then your balance is shown as $0.00 even if you have big amount in your wallet.

Does it work like this? And why our balance is shown as 0.00 in the explorer?

How to setup Ethereum hosted wallet?


texts: How to use Solidity solc to compile A.sol that imports B.sol file?

texts:
I know how to install solc via "npm install --save solc"
then use solc.compile to compile one sol file. But now I've got A.sol file that imports B.sol file, and when I run node compile.js, no error in my terminal, but no json file is generated!

But when I use the same compile.js to compiile B.sol, it works. Why??? How to fix this importing feature in Solidity sol files??? Thank you.


texts:
Newly Infura site has been changed its interface.

Before that all methods of our client program was successfully working, but now when I logon to Infura, all whitelists has been removed. I added our contract addresses to  it, then .call method is working proper, but unfortunately .send method is not working.

How can I solve this problem? Do you have any similar experience?

P.N: I am using web3.js v1.0.0


texts: Why was RLP chosen as the low level protocol encoding algorithm?

texts: Is this an ad-hoc decision? Why RLP? Is it specifically suited to something?


texts: What is an empty account if the state root is not empty?

texts:
"State-bloat" attacks led to an empty account being defined as an account that has zero balance, nonce and code.

There was a disagreement on EIP 161:

  I disagree. An account should be considered empty when the code,
  nonce, balance and state root is empty.

Is it possible to have an empty account with a non-empty state root?  What is the difference between requiring the state root to be empty or not?


texts: How to export the extended public key out of a Ledger Nano S?

texts:
In order to provide secure use-once addresses to an application as a application developer I would like to export the public master key from a Nano S. Then I could derive many public keys from it and assign it to customers on request.

How can you optain the extended public key? In the Ledger bitcoin UI this is possible but for Ethereum?


texts:
Let's take two variable:

uint256 public smalldata = 50000;
uint256 public data = 500 * (10**6) * 10**18;

The first on prints:

BN {
  negative: 0,
  words: [ 50000, <1 empty item> ],
  length: 1,
  red: null
}

But second one prints this:

BN {
  negative: 0,
  words: [ 0, 34604957, 24241406, 1654, <1 empty item> ],
  length: 4,
  red: null
}

What do the "words" mean? How it's calculated?

When I use data.toNumber() it gives following error:

Error: Number can only safely store up to 53 bits

But smalldata.toNumber() gives 50000.

How to print the correct value of data?


texts: What is the purpose in asserting 'msg.data.length == 64 + 4'?

texts:
In a contract used for testing Gnosis MultiSigWallet, I found this piece of code:

/*
 * This modifier is present in some real world token contracts, and due to a solidity
 * bug it was not compatible with multisig wallets
 */
modifier onlyPayloadSize(uint size) {
    require(msg.data.length == size + 4);
    _;
}

/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
/// @return Returns success of function call.
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32)
    public
    returns (bool success)
{
    require(balances[msg.sender] >= _value);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    Transfer(msg.sender, _to, _value);
    return true;
}

The documentation of the onlyPayloadSize modifier is extremely unclear to me.

Can somebody please explain the following:

What exactly is the purpose of this modifier?
Why is it used only in the trasnsfer function?
Why is it used with a specific size of 64 (2 * 32)?
Why is this modifier present only in a test contract, and not in the actual MultiSigWallet contract? Does this by any chance imply that I should add this modifier in every contract in my system, designated for access only via an instance of the MultiSigWallet contract? If I don't have any such contract with a standard transfer method (i.e., an ERC20 contract), can I rest assure that I don't need this modifier anywhere else in my system?

Thank you!


texts: Combined transactions executed together?

texts:
If I'm correct the nonce is responsible for the order transactions are executed.
Let assume you have two transactions T1 & T2. T1 depends on T2. So I want to have an order T1 then T2. This is done by giving T1 the nonce and T2 nonce + 1. (please correct me if that is false)

Now in some case, there might be the situation that T2 depends also on the state of a contract. So I want to make sure that T1 is executed only then T2 can be executed. Is there a way to do this?

So actually to make sure T1 & T2 are included in the same block. I think that could be done by a costume contract but not sure if there is a better or kind of standard solution to it.

Thanks a lot for any advice!

PS:
Example: I want to buy something. T1 deposit money (or make approval) to a contract. T2 buy something using the contract.

Real Example: I want to buy a token on Ether Delta. T1: deposit. T2: Buy token. It doesn't make sense to deposit if someone was faster and bought that token for the given price already.


texts: HI, can i get live Ether to USD price in my smart Contract ? I want to keep a hardcap in USD. is it possible to do so?

texts:
I want to make a function for my ICO to calculate ethers collected so far and convert them into USDollars.
I wanted to hard cap my ICO in USDollars.
Is it possible to do so ?
I am using Solidity to create my ICO smart contract


texts: How do I get a merkle proof (stateHash) from the merkle patricia trie?

texts:
So I understand how a patricia trie works, it's a trie using 0 to f as root nodes, and it also removes empty nodes to make leafs and extensions.

What I don't get is how the stateRoot hash is made.

From what I read, the stateRoot is a hash of the root nodes, but he root nodes contain every other nodes, so wouldn't it require the entire state to make/verify it?

And let's say it only contains the root nodes, without their children, well that's always 0 to f, so it would always be the same.

How do I calculate a proof of this stateHash?

Is the stateHash even a merkle proof?

How is their any computation or data requirement savings like there is with the bitcoin merkle tree proofs? Do I need the entire Ethereum state to calculate the stateRoot/state proof? How do light clients work?


texts:
using --fast does not download the full blockchain only the blockheaders ,then
if --fast is used to sync geth in ethereum node, can it be used for mining??
will it mine same as a node synced normally?


texts:
Let`s say I need to store and manipulate collection of complex data in the smart contract. There maybe complex rules defining who and how can change an item. There maybe be several millions of items in the collection.

There are 2 ways how that logic can be implemented

Using child contract:

contract DataItem {
    bytes32 key;
    string value;

    function DataItem(bytes32 k, string v) {
        key = k;
        value = v;
    }
}
contract DAppInterface {
    mapping(bytes32 => address) public dataItems;

    function addDataItem(bytes32 k, string v) external {
        dataItems[k] = new DataItem(k, v);
    }
}

Using struct:

contract DAppInterface {

    struct DataItem {
        bytes32 key;
        string value;
    }

    mapping(bytes32 => DataItem) public dataItems;

    function addDataItem(bytes32 k, string v) external {
        dataItems[k].key = k;
        dataItems[k].value = v;
    }
}

What is advantage of using one vs another approach? What are the guidelines for picking one vs another?


texts: What would be the actual gas cost of a mapping and are there any size limitations?

texts:
I want to get an estimation of how much it would cost to store arbitrarily many elements in a mapping of the form BYTES32 -> BYTES32.
I see here that a STORAGEADD operation costs 20000 gas,
which I believe is the instruction to add an element to a mapping (is    it correct?).

The gas price today is 20 gwei, so 20 * 10^9 wei which gives me a total of 20000 * 20 * 10^9 * 10^-18 = 0.0004 ether ~  0.0048 USD (with 1 ETH = 12 USD).

Is it correct and is there any limit to how many elements I can put into the mapping (disregarding gas price limitations)?


texts:
This is contract I plan to implement multi send, so I can send multiple transactions to people. Here is my code

 pragma solidity ^0.4.11;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;

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

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

  function transferOwnership(address newOwner) onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
    }
  }

}

contract ERC20Basic {
  uint public totalSupply;
  function balanceOf(address who) constant returns (uint);
  function transfer(address to, uint value);
  event Transfer(address indexed from, address indexed to, uint value);
}

contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) constant returns (uint);
  function transferFrom(address from, address to, uint value);
  function approve(address spender, uint value);
  event Approval(address indexed owner, address indexed spender, uint value);
}

contract Airdropper is Ownable {

    function multisend(address _tokenAddr, address[] dests, uint256[] values)
    onlyOwner
    returns (uint256) {
        uint256 i = 0;
        while (i < dests.length) {
           ERC20(_tokenAddr).transfer(dests[i], values[i]);
           i += 1;
        }
        return(i);
    }
}

Is it going to work if I deploy this, is it really going to take tokens from my account to be able to distribute to different addresses?

This is my original contract: https://bitbucket.org/trbsi/ethcontract