texts:
I'm quite new to Solidity and want to fill an array with 240 structs.

I have a struct:

    struct Country {
      string name;
      uint level;
      uint attackPower;
      uint defensePower;
      uint price;
   }

And an array:

    Country[] public countries;

I want to fill the array with Countries on deployment but when I try to do that as such my gas runs out and the contract can't even be deployed (even when not calling the function). What is the correct way of achieving my goal?

function createCountries() public{
    countries[0] = Country("AW",1, 100, 100, 1);
    countries[1] = Country("AF",1, 100, 100, 1);
    countries[2] = Country("AO",1, 100, 100, 1);
    countries[3] = Country("AI",1, 100, 100, 1);
    countries[4] = Country("AL",1, 100, 100, 1);
    countries[5] = Country("AX",1, 100, 100, 1);
    countries[6] = Country("AD",1, 100, 100, 1);
    countries[7] = Country("AE",1, 100, 100, 1);
    countries[8] = Country("AR",1, 100, 100, 1);
    countries[9] = Country("AM",1, 100, 100, 1);
    countries[10] = Country("AS",1, 100, 100, 1);
    countries[11] = Country("AQ",1, 100, 100, 1);
    countries[13] = Country("TF",1, 100, 100, 1);
    countries[14] = Country("AG",1, 100, 100, 1);
    countries[15] = Country("AU",1, 100, 100, 1);
    countries[16] = Country("AT",1, 100, 100, 1);
    countries[17] = Country("AZ",1, 100, 100, 1);
    countries[18] = Country("BI",1, 100, 100, 1);
    countries[19] = Country("BE",1, 100, 100, 1);
    countries[20] = Country("BJ",1, 100, 100, 1);
    countries[21] = Country("BF",1, 100, 100, 1);
    countries[22] = Country("BD",1, 100, 100, 1);
    countries[23] = Country("BG",1, 100, 100, 1);
    countries[24] = Country("BH",1, 100, 100, 1);
    countries[25] = Country("BS",1, 100, 100, 1);
    countries[26] = Country("BA",1, 100, 100, 1);
    countries[27] = Country("BL",1, 100, 100, 1);
    countries[28] = Country("BY",1, 100, 100, 1);
    countries[29] = Country("BZ",1, 100, 100, 1);
    countries[30] = Country("BM",1, 100, 100, 1);
    ... 210 more of these...
}


texts: keystore file without password of account can be a problem?

texts: In mist you create an account and you provide password. Now your keystore files have been accessed by unauthorized people but not your password which is in your head and only there. Can your ethers be stolen using only those files?


texts:
Beginner in solidity and i'm trying to send ether from an address to a contract. I've tried transferring ether using the Remix compiler test accounts.

pragma solidity 0.4.25;

contract sendether{

     function receiveEther() payable public{
     }

     function sendEther(address _address) payable public{
         uint value = 5 ether;

         _address.transfer(value);
     }

}

I made a simple code to accept ether from an address and send ether to an address.

What i'm not sure is, if i made a Dapp, can i just send ether from my wallet and not execute the receiveEther() function. If no, how can i accept the ether from an address?


texts: Too many variables with production contract

texts:
We have a contract that is in production already and has a getPerson() function. This is a public function that returns 12 uint256 values. We are attempting to call this function from another contract as follows:

function _getPerson(uint256 _personId) private returns (uint256) {
    uint256 a;
    uint256 b;
    uint256 c;
    uint256 d;
    uint256 e;
    uint256 f;
    uint256 g;
    uint256 h;
    uint256 i;
    uint256 j;
    uint256 k;
    uint256 l;

    (a, b, c, d, e, f, g, h, i, j, k, l) = personContract.getPerson(_personId);

    return a;
}

But we get the following compiler warning on the line that we call getPerson:

Compiler Error: Stack too deep. Try removing local variables.

Is there any way to get around this? Redeploying isn't the contract is a pretty bad option for us as there is a lot of data to move over.

Also, I don't quite understand why I have this issue as the limit should be 12 and the contract I'm calling does work fine when it returns the tuple of size 12.


texts:
okay so i am making a mobile application where i want to place  the ERC20 wallet with that application ? so my question is :

is it possible to do this ?
how much will it be secure ?


texts:
Suppose I have a very simple block with one transaction whose hash is:

0xce70a6b3ae683183e9c4d7c5a22ed5e2cf1f82a38fa67acaa24124b42b258b4a

And when I run eth.getBlock I get the following transaction root:

0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421

Assuming I have the keccak256 function, how would I verify this root is correct? I.e. how do I build and encode the transactions trie?


texts: will I change the ABI when using a Proxy pattern?

texts:
I would like to ask you a question about the Proxy Patterns. Suppose I published an erc20 token contract(version1) and also I am using Proxy contract. If I change or add a new function the this logic contract (version2). will I change the ABI (version1's ABI)? I saw it didn't change in a few places when the upgrade process.. I'm confused...

Thank you,


texts: The fee to interact with my contract is extremely high

texts:
I have an smart contract, the clasic crowdfunding contract where you send ether and receive tokens.

I want to send 0.1 from my wallet to make a test, but once I write the contract address, the information of the fee goes to 1.3 ether. I think that it is too much, for any contract!

I want to know where is the problem:

1) At my contract?
2) At my wallet?
3) Probably nowadays the gas prices are very high and that fee is normal but I think that hardly can be.

I believe it isn't the contract because I have tested pasting different addresses from different contracts and it is always the same, the fee skyrockets.

Could the problem be that I synced my wallet in light mode? I have no more ideas. Probably it is something very simple.


texts: How risky is it to ask a dev to deploy smartcontract for you?

texts:
I’m currently in the process of hiring a dev to develop my token and my smartcontract and deploy it.

Will he need my ETH private key to do it ?
Can he change the destination of the funds once the contract is deployed ?

Thank you


texts: Why shouldn't my application handle private keys for my users?

texts:
I'm in the early stages of planning the architecture of our Dapp, and one of my concerns is the barrier to entry of requiring the user to already be using Metamask or Mist. My understanding so far is that these are required to execute contracts on the blockchain because they know the users' private keys, and can hence sign transactions on behalf of the user.

That's all very well, but for users who are new to blockchain, I would like to be able to set up an address/key pair and let them get started immediately. I would happily encourage them to subsequently move to their own wallet. If I'm only storing the new keys on the client, which is open source and externally audited, is this really less trustworthy than using Metamask?


texts:
Error: could not unlock signer account

Using web wallet to manage accounts in browser. But getting the above error when calling a function of a smart contract. This happen after updating the web provider with a different keystore.

Updating the Web3 Provider:

// Hack to provide backwards compatibility for Truffle, which uses web3js 0.20.x
Web3.providers.HttpProvider.prototype.sendAsync =
    Web3.providers.HttpProvider.prototype.send;

var web3Provider = new HookedWeb3Provider({
   host: "https://mainnet.infura.io/[TOKEN]",
  transaction_signer: keystore
});

this.web3.setProvider(web3Provider); //Will overide MetaMask Injected Provider!

Calling some method:

  await deployedDApp.someFunction(
    param1, param2, param3, 0
    , { from: web_wallet_account, gas: 1000000 }
  );

Note: I do not want to unlock the account on the node. I just want to use a keystore that is generated in the web using eth-lightwallet. However, web3._provider.transaction_signer is already set well and have the address of my web wallet account.


texts: How to get the timestamp from the latest event on the etherscan.io apis

texts:
How to get the timestamp from the latest event on a contract using the etherscan.io api ?

I'm using the getLogs call this way:
https://api.etherscan.io/api?module=logs&action=getLogs&fromBlock=6572886&toBlock=latest&address=xxx&apikey=xxx

Seems you need to use the fromBlock=xxx toBlock=xxx arguments but I can't figure out a convenient way to know if an event happened in the last day for example.


texts: Whisper protocol: Version conflict between geth and ethereumj

texts:
I am trying to use whisper in a permissioned network with both geth and ethereumj nodes. The Java nodes detect the capability shh version 2 of their geth peers, but only check for nodes with capability shh version 3 to add to the Whisper object's peer list. Thus the peer list remains empty and the Java nodes miss all Whisper messages.

Does ethereumj still support version 2 at all, does geth support or plan to support version 3?

Is there any way to configure ethereumj or geth to support different versions of the protocol? (Either client just seems to have an option to disable/enable whisper - the --shh command line option for geth, the capabilities option in ethereumj.conf - but no further whisper-related configuration options)


texts: Solo mining run out of HDD space miner found solution is everything lost?

texts:
I have only one rx 580 card and just setup solomining on my pc without any advanced settings bios changes etc My OS is Windows 10

100% noob here so please be more descriptive with your answers

What happened is that I installed geth on C driver which had 11GB left (I did not even think about space issues... )

I had two promts open ones was for geth always updating the block chain I think (had many green letters) and on the other promt the miner was running (etherminer)

I know that solomining is like trying to win a lottery etc but I just experimented excactly as an alternative to buying a lotto ticket :P

The strange and very happy thing is that when I sat today watching the console of the miner(it was running since yesterday ) I FOUND A SOLUTION!!!!!

The bad thing is that geth stopped prompting green letters long before that and that I run out of space so question:

a) Did I lose my reward because I run out of space for geth before finding the solution?

b) If no then how can I retrieve the reward and how can I send it to a more user friendly wallet so that I can see how many ethereum I have? (I set up Etherscan and metamask <- a few minutes ago, I did not link them with geth prior to finding a solution or after finding it)

c) Can I just transfer the geth folder to an other HDD with more space and call it a day? Or do I need to reinstall it there and create a new account?


texts: I am trying to develop an ICO using Etheroll's as a template. Why won't it compile?

texts:
Please see here, line 13 is not compiling in Mist. Can anyone help me understand what is going wrong?

You can see that it worked, obviously, for Etheroll when they performed their ICO.

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

I have made some mods to the code, but even if you directly copy and paste the original from that etherscan link above into remix, you will see that it fails to compile.

What is going wrong here?


texts:
Do blocks on the ethereum chain contain any information about who/what/where a block was discovered?

If so, where in the metadata is this information held?


texts: geth equivalent of bitcoin-cli listtransactions

texts:
For some reasons I failed to google any way of listing all transactions involving my account, just as when you do 'bitcoin-cli listtransactions' in Bitcoin.

Is there any simple way to do what I want to do, without involving any external sites or any code snippets longer than 3-4 lines of code?


texts: geth console not displaying rinkeby eth balance

texts:
I'm running geth 1.10.3 locally by running 'geth --rinkeby'.
I then run geth console with:
'geth --rinkeby attach ipc:\.\pipe\geth.ipc'
eth.coinbase is set to the account I am looking at.
When I run:
eth.getBalance(eth.coinbase);
or
web3.fromWei(eth.getBalance(eth.coinbase), 'ether')
...all that is returned is 0.
I have checked the address on rinkeby.etherscan.io, and it has the expected amount of eth. The latest synced block displayed by 'eth.syncing' is past the transaction block numbers in etherscan. I have imported the account into metamask and see the expected amount of eth.
When I check the address on etherscan.io, it does look like there is an account with 0 ether. Could I somehow be connecting the console to the main network instead of rinkeby?


texts: Have key store file and password - how can I access my ETH without Mist/Geth

texts: Maybe a Noob question. I have the text file from the keystore folder. I have the password. How can I access my funds without using Mist/Geth? These are not working on my computer. Is there an online option to import the wallet. If I input the strings from the file in myetherwallet.com it will only show empty other accounts. Also I did not need to enter my password. Where can I find the encrypted key string in the file.


texts: ERC721Token super._mint calls addTokenTo from the top level implementation

texts:
Based on Shawn's answer,

  super._mint calls addTokenTo from the top level implementation (ERC721Token).

How does this work?

super._mint calls _mint from ERC721BasicToken
reads line addTokenTo
calls top level addTokenTo from ERC721Token
reads line super.addTokenTo(_to, _tokenId);
executes addTokenTo from ERC721BasicToken
comes back to addTokenTo in ERC721Token and executes the rest (ownedTokens)

Is this flow correct? and how come #2 doesn't call addTokenTo in ERC721BasicToken and calls top level addTokenTo?


texts: Custom list of client/node for private chain - Consortium blockchains

texts:
I've been reading on making a custom private chains here , here , here,here and here .

It's pretty clear how to create a custom chain and having remote client connect to the node with this :

geth attach                   # connect over IPC on default endpoint
geth attach ipc:/some/path    # connect over IPC on custom endpoint
geth attach http://host:8545  # connect over HTTP
geth attach ws://host:8546    # connect over websocket

But that's just a client connecting to the node.And not exactly another client running it's own node of my chain.

I'm wondering if it's possible to have a custom list of client(which are nodes) that can connect / use/ run a node of my privatenet but making it impossible for people outside that list from doing it.

Should that be done externally ? by restricting ip ? or can it be done any otherway? more internally ?

Any info / link for doing so is very welcome.

TLDR: I want a private chain with node 1 connected to node 2 connected to node 3 but managing who can connect to whom so that my data stays private but still need to be verified by multiple nodes to be included , much like what vitalik describe as a Consortium blockchain , here


texts:
I get this error when I run the geth upgradedb command:

I0317 08:29:57.792433    4202 chaincmd.go:137] Upgrading blockchain database
I0317 08:29:57.792491    4202 database.go:71] Alloted 16MB cache to /home/'my_user_name'/.ethereum/chaindata
Fatal: Could not open database: resource temporarily unavailable

Though the first time I run the geth --console command, my machine synced with the Ethereum Blockchain.

What Im I missing?


texts: strange that after much searching, i havent found even one piece of info out there which clearly elaborates on how the events are manipulated in drizzle. From what i understand, the event names (and options) are specified in the Drizzle Options object. But the event array that is received in the drizzleState is a collection of logs from all events. How can we properly filter only certain event types, collected starting from block 0 to 'latest', and select only logevents that satisfy custom conditions pertaining to log values, and inject them into components? any example code would be appreciated.


texts:
My deployed contract called successfully only by "function invocation" through web3 or Remix. But it always failed when I sending funds to the contract.

I thought that only requirement that contract has payable function but maybe it is not enough?

Contract looks like:

contract GetRandom is usingOraclize {
    event newRandomNumber(bytes);

    function GetRandom() {
        oraclize_setProof(proofType_Ledger);
        update();
    }

    function __callback(bytes32 _queryId, string _result, bytes _proof) oraclize_randomDS_proofVerify(_queryId, _result, _proof) {
        // if we reach this point successfully, it means that the attached authenticity proof has passed!
        if (msg.sender != oraclize_cbAddress()) throw;

        newRandomNumber(bytes(_result));
    }

    function update() payable {
        uint N = 7; // number of random bytes we want the datasource to return
        uint delay = 0; // number of seconds to wait before the execution takes place
        uint callbackGas = 200000; // amount of gas we want Oraclize to set for the callback function

        // this function internally generates the correct oraclize_query and returns its queryId
        bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas);
    }
}


texts: how transaction in block-chain is validated

texts: Please explain complete procedure/journey how transaction in block-chain get validated by miners, From broadcast of transaction to become part of new block.


texts:
i'm trying to buy $TRY token with my code. It's BSC token. The problem is when i send money to the contract i don't receive any token :/
The contract i'm trying to buy :
https://bscscan.com/token/0xc12ecee46ed65d970ee5c899fcc7ae133aff9b03
I'm coding in python using Web3 wrapper : https://pypi.org/project/web3/
 signed_txn = w3.eth.account.sign_transaction(dict(
        nonce=w3.eth.getTransactionCount(MY_WALLET),
        gasPrice=int(w3.eth.gasPrice*1.5),
        gas=200000,
        to=w3.toChecksumAddress('0xc12ecee46ed65d970ee5c899fcc7ae133aff9b03'),
        value=w3.toWei(amount, 'ether'),
        data=b'',
    ),
        'PRIVATEKEY',
    )

I tried with the contract address :
https://bscscan.com/tx/0xb9652d6f36d22a13a5fc877ade45d7f1c882eec80fd224c87949284793f6fe1a
Payment is OK but i don't receive any token.
I also tried with the pancake routers :
https://bscscan.com/tx/0xc89b620fc08c37dec87f1daa0d79cb1a01f2f0e7b9c200e6fcaf52c66ebe5297
But i got an error "A  status code indicating if the top-level call succeeded or failed (applicable for Post BYZANTIUM blocks only). I don't understand it.
My account detail (only 4 transactions) :
https://bscscan.com/address/0x033f7eea8799696ff46293cf8d84903a6aeeab05
Do you have any idea about how i can buy or sell this token with code ?
Manually i do it with pancakeswap. There is also an ETH $TRY token with same address but i got same problem ...


texts: How to i display information from a smart contract on my wordpress website

texts: I want to display specific information from a smart contract on the main ether network on a wordpress website i can't seem to be able to do that, all tutorials only show test networks. the smart contract is already running on the ether network.


texts: Instantiate web3 to work with the real Ethereum network

texts:
I know how to instantiate web3 to work with a local test network:

var web3Instance =  new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

How do I change this code to connect to the real network?


texts:
I want to send payment to base account once i receive ethers in my account. How do I achieve that. I saw many of them referring to etherscan.io sends email once you receive a payment. How can I process it further from code?

Unable to comment on How can I get notification from geth when I receive ether?

Hence raising a new question.


texts: Undefined results for "web3.eth.accounts" in truffle console

texts:
truffle(development)> web3.eth.accounts[0]

gives output as "undefined"

truffle(development)> web3.eth.accounts

instead of showing all accounts details  gives the below output

Accounts {

currentProvider: [Getter/Setter],

_requestManager:

RequestManager {

 provider:

  HttpProvider {
    host: 'http://127.0.0.1:7545',

    httpAgent: [Agent],
    timeout: 0,

    headers: undefined,

    connected: true,

    send: [Function],

   ......blah...blah

but...

truffle(development)> web3.eth.getAccounts

is working. please help


texts:
I want to know, for example, I am passing 1KB of data to the function in the smart contract, and save the 1KB data in the smart contract through the storage variable. I want to know how much storage resources of my local computer are actually consumed after I use the smart contract to store 1KB of data? What is the relationship between the size of the data saved by the smart contract and the size of the actual computer storage resource consumption? The method I currently think of is to store 1KB multiple times, and then calculate the change in the size of the local Geth folder.
Hope you can help me!Thanks!


texts: Newb Geth Command Line question about sending transactions to other nodes

texts:
I have installed geth on linux, created a wallet, and was running my own node.

After upgrading, I am way behind, only on block 3700000 ish.

Is there a way I can send ethereum from my geth cli wallet using a public node of sorts?

I guess I could import my private keys to some other wallet and use their node, but was looking for a better solution.


texts: Is there a way to find an account's current transaction nonce?

texts: I need to know my transaction nonce because I am doing fancy stuff with contract addresses (which are the keccak hash of my address + my transaction nonce). Is there a way to find this through the JavaScript console?


texts: Cannot connect to the Web3 provider when rpccorsdomain is on

texts:
I am getting the message:

 Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

When I specify:

--rpccorsdomain "http://localhost:8000"

I am following also this thread but I have no solutions. I am

Not connecting to remix via Http
Changing the order of the parameters
changing between localhost and 127.0.0.1 (because apparently it makes a difference when connecting the etherparty block explorer)


texts: I developed this Entity relationship Attribute Diagram for the Ethereum erc 20 erc 1155 and erc 721 . Can anyone help find errors or misplaced details

texts:
I developed this ERA in order to compare the 3 token families, but I am not sure I am  misplacing or missing something.
Any suggestion or correction will be greatly appreciated .
Ricardo Borges dos Santos


texts: Try running MyCrypto with my local node!

texts:
i want connect my local parity nodes with Mycrypto i flowed this tutorial to built my two nodes https://wiki.parity.io/Demo-PoA-tutorial.html
than i try to flow this tutorial to connect it to Mycrypto https://support.mycrypto.com/networks/run-your-own-node-with-mycrypto.html

im still straggling with connect my nodes to Mycrypto i need some help plz
both my nodes work fine in terminals and they connected together and have users addresses and i can send eth from one to another fine by terminals.

so what is chain ID i tryed to add Enode URL and its not work i dont know how to connect that

thank you


texts:
I have a smart contract that allows for several different user to batch tx's for their ERC20 Token distribution.
In this SC the user send some ether to the smart contract, and some tokens.

I want the user to be able to withdrwaw the tokens it doesnt use for which im using:

///@notice  Distributes a constant quantity of tokens to all the specified addresses.
///@dev Distribution will only occur when a distribute function is called, and passed the correct parameters, it is not the smart contracts job to produce the addresses or determine the ammount
///@param index The airdrop token to withdraw based in the the array in which is saved
///@param _amount  The amount to be withdrawn from the smart contract
function withdrawTokens(
    uint index,
    uint _amount
)
    public
    onlyOwner
{
  Airdrop memory airdrop = airdrops[index];
  airdrop.tokenSC.transfer(owner,_amount);
}

To withdraw the tokens, which works like a charm.

When withdrawing ether though. I need to be able to keep track how much ether they have spent so far.

Any idea how to go on about this?


texts: How to parse through the logsBloom of a block or transaction using solidity

texts: Currently trying to figure out how to parse through the logsBloom portion of block and transaction headers using solidity. I've researched the topic so far and have come to the understanding that RLP encoding will be required to transfer the data to the blockchain where it will be decoded by your contract, but have been unable to figure out the next steps.


texts: Refunding gas fomula in Ethereum yellow paper

texts:
After execution of the transaction by miner, the transactor is refunded a remaining gas. it is explained in section 6 of Ethereum's yellow paper.
When calculating the amount to be refunded gas, the following formula is used.

In the picture above, how can i understand the formula 64.
When g' means remaining gas after execution of the transaction,
What does mean the second term of left side of the equation?


texts: How do I share my Ethereum smart contract address to a third party for uploading data into my private blockchain

texts:
My smart contract address looks like this (altered): 0xb2dd088039f7b608b300e8fa14c2e0.
Please advise if there is an Ethereum explorer in which private data can be shared by logging in through the smart contract address. Thanks.


texts: Do miners undergo a sunken cost of attempting to verify an invalid transaction signature?

texts:
In the case of an 'invalid' transaction whereby the state transition of the execution is deemed to conflict in some way and reverts, the transaction itself is actually valid; gas is consumed, tx included in the block with the affected gas payment deduction.
The intrinsic gas of 21000 exists here as the baseline cost for a transaction (the cost for verifying the ECDSA signature over the transaction) and is the minimum amount charged in any transaction. If the transaction is not valid due to an incorrect signature (malformed or else), the miner rejects the transaction completely, it does not enter the tx pool and is not propagated through the network.
However in this case of an invalid transaction signature, the miner has to attempt to verify the transaction and regardless of failure or success, the computation is spent. Could someone not flood the network with malformed transactions, the miner none the wiser, and force wastage of computational resources on verifying fake signatures?
If that is the case is the verification step of a miner to deem a transaction valid/invalid a sunken cost?
If this is expected, why even charge the intrinsic gas other than to recoup previously wasted (network-wide) computational resources at an arbitrary rate of 21000 gas per successful tx?
Or have I misunderstood the computation that the miners perform prior to adding transactions to the tx pool?


texts: How to get an ERC20 token listed in etherscan.io

texts:
In etherscan.io, under the TOKEN drop down menu, there is a list of tokens,
and it is indicated that they all are ERC20 standard tokens

1) How do they get listed? Do we have to register a new ERC20 token somewhere or are they automatically recognized by etherscan?

2) If I add an extra function to an ERC20 standard contract, for example:

  function mint(uint256 _amountToMint) {...}

Is the new contract still an ERC20 contract ?


texts: Automating user data storage on a blockchain

texts: I have a smart contract that contains a function to store data onto the blockchain. The function stores two integer variables to the blockchain. Now, I can manually store the values from the remix-ide but the problem is I have to store multiple values to the blockchain. Suppose the fields are First Name and Last Name, then I have to store the values, again and again, multiple times. Is there any way to automate this process?


texts: Can't transfer balance from contract to parent contract

texts:
I'm having trouble transferring remaining funds from a Contract to it's controlling Contract Factory. I'm trying to do the following.

Create a new Service with Factory->createService()
Add funds to the Service contract with Service-addFunds()
Execute the Service through Factory->executeService()

And I get the following error when running the executeService function on the Factory contract.

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

Factory contract

pragma solidity ^0.4.18;
import "http://github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";
import "./Service.sol";

contract Factory is Ownable {

    mapping(string => address) services;

    event DidExecuteService(address contractAddress);

    modifier ValidateString(string str) {
        require(bytes(str).length > 0);
        _;
    }

    function Factory() public {}

    function createService(string name) public onlyOwner ValidateString(name) {
        address assetAddress = new Game();
        services[name] = assetAddress;
    }

    function executeService(string name) public onlyOwner {
        address contractAddress = services[name];
        Service(contractAddress).execute();
        emit DidExecuteService(contractAddress);
    }

    function getContract(string name) public view returns (address) { return services[name]; }

    function countContracts() public view returns (uint) { return 0; }

    function getBalance() public view returns (uint) { return address(this).balance; }
}

Service Contract

Transfers to addresses from the recipients wallets pass but the contract fails to transfer remaining funds from the Service contract back to the Factory, the owner/msg.sender of the function.

pragma solidity ^0.4.18;
import "http://github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";
import "http://github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol";

contract Service is Ownable {

    using SafeMath for uint256;

    event DidMakePayment(address player, uint256 value);
    event DidAddFunds(uint amount, uint balance);

    function Service() public {}

    function execute() payable public onlyOwner {
        uint amount = address(this).balance;
        // ERROR: Rollover to Factory
        owner.transfer(amount);
        emit DidMakePayment(owner, amount);
    }

    function addFunds() payable { emit DidAddFunds(msg.value, address(this).balance); }

    function getBalance() public view returns (uint256) { return address(this).balance; }
}


texts: How to compile solidity code in Kali Linux

texts:
I have tried to install the remix IDE for compile my codes in solidity, since for some reason the remix IDE don't open online. I executed the codes bellow and give that errors. Sorry anything grammatical errors, i am Brazilian and haven't domain of the English idiom.

This error happen every time execute 'npm start' for open remix IDE offline.
I'm despaired because of this, anything help is welcome!

EXECUTED THAT CODES IN BASH

git clone https://github.com/ethereum/remix-ide.git
git clone https://github.com/ethereum/remix.git

cd remix
npm install
npm run bootstrap

cd remix-ide
npm install
npm run setupremix
npm start

AND OBTAINED THAT ERRORS

[serve   ] [Fri Jun 21 2019 23:21:29 GMT-0300 (GMT-03:00)] "GET /build/app.js" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
[serve   ] [Fri Jun 21 2019 23:21:29 GMT-0300 (GMT-03:00)] "GET /build/app.js" Error (404): "Not found"
[serve   ] [Fri Jun 21 2019 23:21:29 GMT-0300 (GMT-03:00)] "GET /favicon.ico" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
[serve   ] [Fri Jun 21 2019 23:21:29 GMT-0300 (GMT-03:00)] "GET /favicon.ico" Error (404): "Not found"
[serve   ] [Fri Jun 21 2019 23:21:29 GMT-0300 (GMT-03:00)] "GET /favicon.ico" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"

WHEN I TRY OPEN REMIX IDE IN BROWSER IT'S BELLOW HAPPEN

Yes, without anything in screen...


texts: Error :current provider doesn't support subscriptions : using ganache, web3 1.0.0

texts:
how to solve the error :

  The current provider doesn't support subscriptions: HttpProvider at
  Subscription.subscribe

while using web3 1.0.0 and ganche


texts:
I'm getting my feet wet in this blockchain world and looking to build a dapp based on Ethereum for maintaining an inventory of products. About 400,000 items that can be updated, removed or added to by anyone on who connects. My initial idea is to store product images and details in swarm (the detail would be a json object with about 100 nodes) and then store the swarm hashes in blocks instead of transactions (or something like that)

My question is, is there any way to query for products that match certain things? For instance, "location" and "type" are examples of some of the things stored in the json hash. If I were to put some of the "searchable" fields into the blockchain, would that be something I could query? (ie: I want to end up with all of the swarm hashes that represent items matching my simple query.


texts: It possible to hard fork a private network without resyncing chain from scratch?

texts:
I am able to hard fork my private chain into first Constantinople and than to Istanbul, please see the answer for it.

My approach is:

I have updated geth to its highest version
I have kept the go-ethereum/params/config.go file as it is
I have updated the genesis.json file by adding "constantinopleBlock": 2862930, "petersburgBlock": 2862930, and "istanbulBlock": 3831182. Block numbers are selected based on my chain.
I have removed the chain. sudo rm -rf chaindata lightchaindata
Initialized my chain by started it with geth init
Finally, I have started my chain, which started to sync from 0th block

I have tried this without removing the chain but it did not work. So from scratch since genesis block should be updated, I am syncing the chain from 0th, block which is very uniefficient.

[Q] I was wondering is it possible to hard fork a private network without resyncing chain from the 0th block? This approach is inefficient to sync few GB all over again for all the nodes on the network.


texts: Smart Contract firing send ether transaction that's not in the contract

texts:
I need some help with my smart contract, here's the smart contract code

pragma solidity ^0.4.18;

contract UserToken {
    mapping (bytes32 => uint8) public tokenBalance;

    bytes32[] public userList;

    // Constructor
    function UserToken(bytes32[] userName) public payable {
        userList = userName;
    }

    // Returns the total votes a candidate has received
    function totalTokensFor(bytes32 user) view public returns (uint8) {
        require(validUser(user));
        return tokenBalance[user];
    }

    // Increments the token count of user
    function buyToken(bytes32 user, uint8 token) public {
        require(validUser(user));
        tokenBalance[user] += token;
    }

    function validUser(bytes32 user) view public returns (bool) {
        for(uint i = 0; i < userList.length; i++) {
          if (userList[i] == user) {
            return true;
          }
        }

        return false;
    }
}

I have a geth node connected to rinkeby and running on my ec2 instance in AWS, from there I've created the eth account address and then imported the JSON file to metamask.

Now this is the problem, whenever I call the function "buyToken", it fires four transactions

The first transaction is this https://rinkeby.etherscan.io/tx/0x3206678cdd6fdcfc4eddf3871002b77320d5e83f3bb5f9e2d9c0c0aa9bbc8817

An ether transfer to another address w/c is not in the contract, and the ether it transferred was 2.994817 Ether, again not in the contract, thus making the next three transactions disappear since there’s not enough balance in the account, original account balance was 3 ether.

Here's the code that calls the BuyToken

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var userContract = web3.eth.contract(ABI);
var userInstance = userContract.at(contract address)

$("#buy_button").click(function(e) {
    let tx_hash = userInstance.buyToken("John", 3);
    e.preventDefault();
});

My question is why is this happening? There aren't any ether transfer code in my contract so what's the possible cause of this?

Thanks


texts: Preventing manipulation of random number generation for casino contract

texts:
I'm reading through the accepted answer to this question on securely creating random numbers for multiplayer blockchain-based casino games.  I don't understand the reason for step 4: "Users send their hash to the contract, along with ether greater than or equal in value to the value of the random number."

Why should the amount they send have to be greater than or equal to the value of their random number?

Is there anything wrong with each player simply sending in their "bet" (i.e. the amount they choose to gamble), and forfeiting it if they refuse to reveal their N?  The amount they gamble can serve as their security deposit: they simply drop out of the game and stand no chance of winning the jackpot (consisting of the sum total of all players' bets) if they don't reveal their N.


texts: is it possible to steal my ether when I unlock it?

texts:
is it possible to steal my ether when I unlock my account? The private key is stored in my local storage. I am running geth on my PC.
How can someone make transaction with my account? without my private key?
I checked that the endpoint port is not opened.
But someone has stolen my (ropsten) ether.
you can check this account (the persone who stole my ether, but seems others too..)

https://ropsten.etherscan.io/address/0x6ef57be1168628a2bd6c5788322a41265084408a

What else should I check for my PC (running geth node) ?


texts:
I've been running geth for about 2.5 days so far, and I'm trying to work out why it's taking so long to sync.

It's downloaded ~40Gb of the blockchain (up to block #2379173 if I'm interpreting the output correctly) and is running at consistently <25% CPU, often less. The IO load varies a lot but is on the order of 5-10MB/s, if that was purely for downloading and writing the blockchain data, it would take about half a day, rough estimate. This implies that the IO load is not for writing the chain to the disk. The network load is tens of KB/s, and my connection can handle a lot more than that. This means there's some MB/s of IO (writing) which is neither network chatter nor a net disk write.

The bottleneck clearly isn't the CPU, and the these numbers don't support IO as the bottleneck either. So why is it taking so long?


texts: Out of gas error even for simple one string set

texts:
I have been struggling with this exception and am literally stuck in development:
 "Error: Returned error: VM Exception while processing transaction: out of gas"

I removed all the code and just trying to set a simple struct with one string with some modifier checks and deploying using truffle develop to localhost.

The problem is that basic uints and single strings are setting and working, but If i make the function by just adding a few modifiers, the function fails with out of gas exception.

How can we develop if even simple functions fail out of gas?

UPDATE: the code below

I have a simple smart contract deployed on the local truffle env using migrate. I am using react-components package to work with the smart contract.

So my issue is that simple getters and setters are working, but when I try to run a method with 2-3 arguments I am getting this exception.

My truffleconfig is as follows:

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "app/src/contracts"),
  networks: {
    develop: { // default with truffle unbox is 7545, but we can use develop to test changes, ex. truffle migrate --network develop
      host: "127.0.0.1",
      port: 8545,
      network_id: "*",
      gas: 6921975,
      gasPrice: 25000000000
    }
  },
  solc: {
        optimizer: {
            enabled: true,
            runs: 200
        }
    }
};

And in my react component I am calling like this:

Testing Poni

      This is a initial test to create Poni

      Stored Value:
      <ContractData
        drizzle={drizzle}
        drizzleState={drizzleState}
        contract="PoniOwnership"
        method="getMyPonies"
      />

    <ContractForm drizzle={drizzle} contract="PoniOwnership" method="createPoni" />

My solidity functions are like this:

function createPoni(string memory _code, string memory _imgLink) public onlyOwner poniIsUnique(_code){

    uint randDna = _generateRandomDna(_code);

    //!!pass imgHash here also later
    _createPoni(_code, _imgLink, randDna);
  }

function _createPoni(string memory _code, string memory _imgLink, uint _dna) private {

    uint id = ponies.push(Poni(msg.sender, _code, _imgLink, _dna, 0, true)) - 1;

    poniToOwner[id] = msg.sender;
    codeToId[_code] = id;
    ownerPoniCount[msg.sender] = ownerPoniCount[msg.sender].add(1);

    emit NewPoni(id, _code, _imgLink, _dna);
  }

struct Poni {
    address owner;
    string code;
    string imgLink;
    uint dna;
  }

I have tried to additionally send gas from the drizzle react-component as options are given here: https://www.trufflesuite.com/docs/drizzle/react/react-components, but it throws errors saying function is not payable. I am not able to figure out how to deal with this exception.

UPDATE
i was able to deploy smoothly to the rinkeby network, and create my token using the console and check for the value being inserted properly. I am at a loss understanding why truffle ganache wont work and keep throwing this gassy message!


texts: Is there a good way to calculate a ratio in Solidity (since there is no float/double)?

texts:
I've looked into the following answers, but have not found what I am looking for.

How can I perform float type division in solidity?

How can I represent decimal values in Solidity?

How does Ethereum cope with division of prime numbers?

Any help is appreciated.


texts: Convert DAO extraBalance to Ether or Bitcoin

texts:
I'm a noob in cryptocurrencies and still hold some DAO_extraBalance tokens in MyEtherWallet. I want to convert these DAO_extraBalance tokens into Ether tokens (ETH) or Bitcoins (BTC).
I've browsed through some old messages and found that support to convert DAO_extraBalance tokens to ETH or BTC halted via MyEtherWallet, Jaxx and Poloniex.

Furthermore, other options are quite complex, such as issuing an ExtraBalDaoWithdraw contract via:
https://etherscan.io/address/0x755cdba6AE4F479f7164792B318b2a06c759833B#code.

I hope anyone can help me out with a step-by-step procedure - for dummies - how to convert DAO_extraBalance to ETH or BTC. A YouTube video with such a procedure would also help.
Thanks in advance.


texts:
Why is the cost of memory non-linear, while the cost of storage is linear?

I wonder why the cost function of memory vs. storage differ? While storage is associated with a constant cost, this is not the case for memory. Why is that?


texts: what happen if mining while receive a new transaction

texts: If a miner is mining and receives a transaction with the same nonce and a higher fee, will the miner stop and replace the transaction?


texts: is there an easy way to get the full state of a contract?

texts:
I'm developing a quite complex contract with many state variables of all kinds. (mappings, arrays, uint, strings, bytes, etc).

For testing, it would be very useful to get a JSON (or similar) with the full state of the contract in a given moment.

I would like to know if there is an easy way to get this state from geth or web3.

Some thing like:

var currentState = web3.eth.getFullState([Contract address]);

It would be very good if this method works for any contract of any kind.


texts:
Based on documentation it should be possible to create new contract from contract

contractAddress = new OwnedToken(name);

When I invoke this method from contract, the address I receive seems to be normal address and not contract.

Is this even possible (I remember I read somewhere that only normal accounts can send contract creating transactions)?


texts: Call an existing python code inside a solidity smart contract

texts: I want to call some existing code (written in Python) inside my Ethereum smart contract (written in solidity). Is it possible to do that? if so, how can we do it?


texts: Test array values if key/value exists - Does not work

texts:
I have a problem with the following contract.
When I deploy it, normally on calling the function addBalance() it should go into the false. But instead, it completely does not work and I get the following message. What's wrong?

  VM error: invalid opcode. invalid opcode      The execution might have
  thrown.   Debug the transaction to get more information.

How can I find out if a key does not exist? Contract:

pragma solidity ^0.4.24;

contract MembersContract {

    struct Member {
        uint balance;
        address member;
        bool exists;
    }

    Member[] public members;

    constructor() public {
        members.push(Member(0, 0x0, true));
    }

    function addbalance(uint _balance) public returns(bool _success){
        if(members[1].exists == true) {
            members[1].balance = 400;
        }
        else {
            return false;
        }
    }

}


texts: How to get amount of ERC20 tokens sent in tx from tx hash? (Web3.js)

texts:
I have tx hash and I would like to see how much ERC20 tokens was sent in this transaction.

How can I do this with web3.js?

Thank you.


texts: Is it possible to store structs in a Mapping or any dynamic memory structure in my Solidity SmartContract?


texts: Mining on Ropsten/Testnet - Not Working Post Hard Fork

texts:
Ever since the ropsten hard fork and upgrading to geth 1.7.0, I am unable to mine for test ether.

Geth
Version: 1.7.0-stable

Before the hard fork, I could manage to mine a few blocks each day.  Post hard fork, haven't been able to mine a single block.
Is there a new setting or config required on geth?


texts: How to find an ether account I sent to from CoinBase

texts:
I had some Ethereum. I originally bought at Coinbase, but after hearing talk about keeping a separate wallet for your digital currency I transferred them to another place.

That was a year ago. I wrote my receive address down, but I switched computers and don't remember where my Ethereum account is.

I have a record of the send from Coinbase, but I don't remember where I sent my ETH.

Can anyone please provide some suggestions?


texts: Can I use my private key and pw to access MyEtherWallet on a new CPU? If so, how?

texts:
My hard drive pretty much melted because Dell laptops suck.  I saved my private key and would like to access myetherwallet from a new computer.  When I enter the private key on its own as a "Keystore File (UTC / JSON)" it wont accept it.  I assume thats because it needs to be in a specific format.  Can I format a Notepad file so it will accept my private key?  If so, how?

Thanks in advance


texts:
Is there a formula that I can use to calculate current network congestion of Ethereum network or any other crypto currency ?
I tried to search for it but couldn't find anything on it.

Thank you,


texts:
I created and deployed two contracts successfully (with confirmation) using truffle migrate like so:

module.exports = function(deployer) {
    deployer.deploy(ReentrancyPot).then(async () => {
        deployer.deploy(ReentrancyAttack, ReentrancyPot.address);
    })
}

The second contract has a dependency on the first like so (excerpt from ReentrancyAttack.sol)

contract ReentrancyAttack {
    ReentrancyPot public pot;

    function ReentrancyAttack (address _pot) public {
        pot = ReentrancyPot(_pot);
    }
}

I'm using a test for the first contract and it is successful, however, the second contract is showing as not deployed (truffle.js is configured to point to port 8545)

var ReentrancyPot = artifacts.require("./ReentrancyPot.sol");
var ReentrancyAttack = artifacts.require("./ReentrancyAttack.sol");
var Web3 = require('web3');
var web3 = new Web3(Web3.givenProvider || 'ws://localhost:8545');

require('chai')
 .use(require('chai-as-promised'))
 .should();

contract('ReentrancyPot / ReentrancyAttack', function(accounts) {

    it("pot should support deposits and withdrawals", async () => {
        let pot = await ReentrancyPot.deployed();
        let attack = await ReentrancyAttack.deployed();
    })
})

I'm getting the following error after running truffle test:

Error: ReentrancyAttack has not been deployed to detected network
(network/artifact mismatch)


texts:
I'm collecting temperature data from user on-chain. However, since cant get exact (live) time through my html code connected via testrpc to the blockchain I do so.

Where post click a button, html code complies to starts sensing and recording data as well as displaying time of so.

My question here is, is there a way where I can for example send an email with a screen shot of the html page since it has the data needed as well as time? Or save it locally as a file?


texts: ERC20 Smart Contract not visible on Ropsten

texts:
While trying to deploy my erc20 contract on ropsten,I am not able to see transaction at https://ropsten.etherscan.io

Steps I followed

1) My Config file :

networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },

    ropsten: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "3",
      gas: 500000
    }
  }

2) Copied my ropsten network address using mnemonics from metamask to Ganache.

3) Ran following command

truffle migrate --network ropsten --reset

4) Contract got deployed successfully with following output

Using network 'ropsten'.

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x758038b5f32e08870b65c39d7fb8b2413e310b76437141920035d32eb071fb24
  Migrations: 0x619c935ee4bb707412fe5cd14063548ef1fca453
Saving successful migration to network...
  ... 0xe588beec7c7ab9e71dd38792a439b5b15d00cb14c2f444512bcb5b2025681dd2
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Replacing Migrations...
  ... 0xe625770acec3c060804c8a1e03396b9349074c4c8fd9cb11cb14cc14b1fb0a82
  Migrations: 0x7336ef499b79fd25f8aa688c4ea9a0335b33a8f9
Saving successful migration to network...
  ... 0x714203dca5e0481fbab2a31cff7800b9c8db1bef28a03c04c21cdbc512497f0e
Saving artifacts...

Anything I am missing here. Thanks in advance


texts:
I am trying to generate a java wrapper class for a solidity contract, I have compiled the file and have the abi and bin file, but when I run the command as follows:
web3j solidity generate PR_sol_ballot.bin PR_sol_ballot.abi -o .\Web3App\src\main\java -p com.project.contracts
``` I get an error saying "unmatched arguments from index 2" I have tried searching this but can't find anything that clearly explains what this error is or how to fix it. I am using web3j version 1.4.0 and the compiler is solidity v 0.5.0 (solc-js)


texts: How put address (from ganache-cli client) as a parameters in constructor

texts:
Always, when I try to send parameters for the constructor function I use a migration file and where I´m trying to deploy the contract, add the parameters...Something like that:

var OVXET = artifacts.require("./OVXET.sol");

module.exports = function(deployer) {
    deployer.deploy(OVXET, 1000000000, "OVXET", "OVX", accounts[1], accounts[2]);
}

But in this case...how I have to send the accounts? I want the same accounts that I am using the test files. Have I to incorporate a var initialized with web3.accounts?

Solution:

var accounts = web3.eth.accounts;

Is there another way to implement this task?


texts:
I am trying to get latest blocks data and gets all the transaction IDS inside the block and send that transaction IDS array to an api server. I am using this command in geth console :

 eth.filter('latest').watch(function(err, result){console.log(result)})

Is there a way in which a script will run 24/7 in geth console(get attach) and run the above command to get latest block data and send the transaction IDS array to an api server? Any ideas/help is greatly appreciated, Thanks!


texts:
I am using Embark version 2.1 .I have used the command 'embark ipfs' but it returns the following error.

/usr/local/bin/ipfs
/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/solc/soljson.js:1
(function (exports, require, module, __filename, __dirname) { var  Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var  moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x) {process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=

ReferenceError: build_dir is not defined
at IPFS.deploy (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/ipfs.js:16:37)
at Object.ipfs (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/index.js:265:10)
at Command.<anonymous> (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/cmd.js:136:17)
at Command.listener (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:301:8)
at emitTwo (events.js:106:13)
at Command.emit (events.js:191:7)
at Command.parseArgs (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:615:12)
at Command.parse (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:458:21)
at Cmd.process (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/cmd.js:19:11)
at Object.process (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/index.js:31:9)

How can i solve this issue?


texts: Requiring a specific type of token in smart contract

texts:
Newbie here. For practice, I'm writing a smart contract where multiple users can pool funds. E.g. 3 users can contribute 100 DAI tokens to the contract. At the moment, the smart contract does nothing more than tracking the contributors.
How do I ensure the contract only accepts tokens of a specific kind (e.g. DAI)?
My code so far is rudimentary:
pragma solidity ^0.8.0;

contract Pool {

    struct Contributer {
        uint id;
        address wallet;
        uint contribution;
    }

    mapping(uint => Contributor) public contributors;

    address public admin;
    IERC20 public which_token;

    constructor(address _daiAddress) {
        admin = msg.sender;
        which_token = IERC20(_daiAddress);// pointer to DAI
    }

    function contributeToPool(address _from, uint _amount) {
        //require(type of token same as which_token??);
    }

}

Specifically, have a look at contributeToPool().


texts: when and who executes the ethereum transaction

texts:
Although this question is asked and answered several times, I'm still confused about who executes the ethereum transaction and when? I want to know the right answer (if possible with proof from the official papers):

1) the sender executes it first and send it to all the network in order to verify it and finally include it in a new block?

2) the sender creates a new transaction broadcast it to the network until it reaches the miner that 1) verifies it, 2) includes it in a new block, 3) executes the transactions of the new block, and 4) finally sends the block to the rest of the network which verifies it and executes its transactions (also, I want to know here if the "rest of the network" executes the transactions of the new block or simply update their states).

Is there anyone that can give the right answer.


texts: how to deal with race condition and execution times of a contract?

texts:
I'm a ethereum beginner. I can't understand some of its concept.

for example, a contract should be executed by everyone on the network as a way to verify a block.

what about synchronization among all executions of the same program?

suppose I write a program to transfer $10 from my account to a friends as a penalty if I lost his book.

in this case, I only want one $10 transferred. but if my contract will be executed multiple times, then how to prevent multiple transfer?


texts: Duplicate events firing in a Web3 listener

texts:
I'm experimenting with plugging Ethereum into a React web application, using this nice tutorial repo as a basis (thanks to uzyn): https://github.com/uzyn/ethereum-webpack-example-dapp

I'm connecting successfully to the local TestRPC 3.0.3 instance, have a Solidity 0.4.8 "MyToken" contract deployed and am mining a contract function called "transfer" successfully. I know the transfer is running just once from the updated account balances but I'm getting two instances of the "Transfer" event coming up in my browser console. If I take out the line emitting the event, I get nothing in the console.

Could anyone suggest why that is? Thanks!

I'm calling this contract function which emits an Event:

/* Send coins */
function transfer(address _to, uint256 _value) {

    if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
    if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
    balanceOf[msg.sender] -= _value;                     // Subtract from the sender
    balanceOf[_to] += _value;                            // Add the same to the recipient

    Transfer(msg.sender, _to, _value);                   // Notify anyone listening that this transfer took place
}

With this code block:

  MyTokenContract.transfer.sendTransaction(
    web3.eth.accounts[1],
    100,
    (error, result) => {
      if (error) {
        console.log(`Error occurred: ${error}`);
        return;
      }

      const accountOneBalance = MyTokenContract.balanceOf(web3.eth.accounts[0]);
      const accountTwoBalance = MyTokenContract.balanceOf(web3.eth.accounts[1]);

      console.log(`accountOneBalance: ${accountOneBalance}`);
      console.log(`accountTwoBalance: ${accountTwoBalance}`);
    }
  );

And I have this Web3 code listening for contract events:

MyTokenContract.allEvents((error, event) => {
if (error) {
  console.log(`Event error: ${error}`);
  return;
}

const eventName = event.event;
const accountFrom = event.args.from;
const accountTo = event.args.to;
const amount = event.args.value;
console.log(`Event '${eventName}' from account ${accountFrom} to ${accountTo} of ${amount}`);

});

When it runs, I get two events logged in my Chrome console:

accountOneBalance: 249900
accountTwoBalance: 100
Event 'Transfer' from account 0xdd0efd8df206cb598bda146ae567f5d398436226 to 0x7497ac386ae2e1eb58210d08e6c401b56417e04d of 100

Event 'Transfer' from account 0xdd0efd8df206cb598bda146ae567f5d398436226 to 0x7497ac386ae2e1eb58210d08e6c401b56417e04d of 100


texts: Homomorphic encryption with Ethereum compatible chains

texts:
Are there any blockchains or even Ethereum mainnet contracts that would offer homomorphic encryption primitives and example code?
A sample use case would be homomorphic secret sharing that is needed for a secret ballot voting.


texts: Mist 0.7.3: how long does it take to sync and how much data do I need to download?

texts: I just installed Mist 0.7.3 and would like to know how long does it usually take and how much data does it download as of today. What other alternatives are there to Mist if I dont want to download the entire blockchain.


texts: Is it possible that Ganache can handle a private key without an "0x" prefix, but Parity cannot?

texts:
I am trying to sign and send a transaction as follows:

let signedTx  = await web3.eth.accounts.signTransaction(options, PRIVATE_KEY);
let txReceipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
...

The PRIVATE_KEY variable is a 40-character long hexadecimal string, without an 0x prefix.

The options variable is an object containing to, data and gas fields.

My code completes successfully on Ganache, but when I run it on a fully-synced Parity node connected to ropsten, I get the following error:

Insufficient funds.
The account you tried to send transaction from does not have enough funds.
Required 8000000000000000 and got: 0.

My account definitely has more than 0 ether on ropsten (see https://ropsten.etherscan.io/address/0x1c492da58f6396be2880576cc513c5b108450429), and I can even verify it locally (via web3.js):

let balance = await this.web3.eth.getBalance("0x1c492da58f6396be2880576cc513c5b108450429");
console.log(balance);

So here is the thing.

I was able to resolve this problem by adding 0x at the beginning of the PRIVATE_KEY variable.

Hence my question - is it possible that web3.eth.accounts.signTransaction runs differently on Ganache and on Parity?

Thank you!


texts: To which remote ethereum nodes does Metamask plugin send signed transactions? and are they exposed to denial of service attacks?

texts:
So Metamask allows in it UI to connect to different ethereum nw  (public/ testnet) right.

Do who is maintaining these peers?
Can I trust these peers?.
If so, can I setup similar service on my machine without subjecting my machine to DOS attack and affecting my machine? How can I do this?


texts: Do different clients use different amounts of gas?

texts:
I'm trying to understand clients/nodes a bit can someone help clarify the below for me.
My understanding is that each client implements the EVM in their own way.
Smart contracts are written in Solidity, then compiled(right term?) into bytecode. Inside the clients implemented EVM the bytecode is interpreted into opcodes, and each opcode has a set gas cost.
Do all the clients convert bytecode to the same opcodes? Essentially is there any difference in gas efficiency between clients?


texts:
I have a (noob) question on the usage of transfer and send. I have seen that transfer is equivalent to

 require(x.send(k));

When I use send() I know that I have to check whether there was an error during the execution and then handle it like:

   if(!x.send(y)) {
    //...
   }

1) In case there is an error, do I have to write revert() inside the block? To be more specific, since send allows the usage of 2300 gas, in case changes are made inside the receiver contract fallback function, are they reverted automatically?

2) If I use transfer() I don't have to check for errors right? If something goes wrong all code executed is reverted and the remaining gas refunded(I think).

Cheers!


texts: adding number of miners in an existing ethereum network

texts: I am using geth and power shell to develop an ethereum network. I have an existing network with 3 nodes where 1 is mining. Now i want to increase number of miner nodes. How can we do it.


texts: Suppose I have an array of addresses which I append to somewhere in the contract. Do the miners (or anyone else) have a way of figuring out what the variables holds in terms of data? In other words, who can see the addresses in the array?


texts:
As per my understanding contract`s own address is the address which we assign to owner of contract using msg.sender.
But I saw this question on SE where it was described that a contract can access its own address using address(this) , but when i compiled following script
 address owner;
function test (string _name)public view returns(bool){

    owner = msg.sender;
    return owner == address(this);
}

i get boolean result as false.
So What is the difference between msg.sender and address(this).


texts: error: VM Exception while processing transaction: revert SafeMath: subtraction overflow on migrating crowdsale conract

texts:
I am developing the token sale Dapp using openzepplin-solidity version 2.3.

While migrating, I got the following error.

  Returned error: VM Exception while processing transaction: revert SafeMath: subtraction overflow -- Reason given: SafeMath: subtraction overflow

I am using

Truffle v5.0.22 (core: 5.0.22)
Solidity - 0.5.0 (solc-js)
Node v10.16.0
Web3.js v1.0.0-beta.37

Here is the link of my Dapp on Github.
I have 2 crowdsale contracts and 1 token contract.

SimpleToken.sol

pragma solidity 0.5.0;

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

contract SimpleToken is ERC20Detailed, ERC20 {
    uint256 public totalSupply_;
    mapping(address => uint256) balances;

   constructor(string memory _name, string memory _symbol, uint8 _decimals,   uint256 _amount)
   ERC20Detailed(_name, _symbol, _decimals)
   public {
    require(_amount > 0, "Amount has to be greater then 0");
    totalSupply_ = _amount * (10 ** 18);
    balances[msg.sender] = totalSupply_;
    emit Transfer(address(0), msg.sender, totalSupply_);
    }

}

And following is

PresaleCrowdsale.sol

pragma solidity 0.5.0;

import "../client/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "../client/node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "../client/node_modules/openzeppelin-solidity/contracts/crowdsale/validation/WhitelistCrowdsale.sol";
import "../client/node_modules/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol";

contract PresaleCrowdsale is WhitelistCrowdsale, AllowanceCrowdsale{
    constructor(uint256 _rate, address payable _wallet, ERC20 _token, address _tokenWallet)
    Crowdsale(_rate, _wallet, _token)
    AllowanceCrowdsale(_tokenWallet)
    public {  }
}

I can successfully migrating the token contract but while migrating the crowdsale contract I got the error in safeMath subtraction overflow

Following is the migration file

const SimpleToken = artifacts.require("SimpleToken.sol");
const PresaleCrowdsale = artifacts.require("PresaleCrowdsale.sol");

  module.exports = (deployer, network, [owner]) => deployer
 .then(() => deployer.deploy(PresaleCrowdsale, 10000, owner, SimpleToken.address, owner))
 .then(() => SimpleToken.deployed())
 .then(token => token.transfer(PresaleCrowdsale.address, '100000000000000000'));

EDIT
Add 2nd Migration file and transfer is not working. got the same error

  revert SafeMath: subtraction overflow -- Reason given: SafeMath: subtraction overflow

const SimpleToken = artifacts.require("SimpleToken");
const GenericCrowdsale = artifacts.require("GenericCrowdsale");

module.exports =  async (deployer, network, [owner]) => {
await deployer.deploy(SimpleToken, "Tooploox", "TPX", 18, 21000000);

const now = Math.floor(Date.now() / 1000);

const day = 24 * 60 * 60;

const openingtime = now;

const closingtime = openingtime + 2 * day;

const rate = 1000;

await deployer.deploy(GenericCrowdsale, openingtime, closingtime, rate, owner, SimpleToken.address);

console.log("Transfering Token...");

const token = await SimpleToken.deployed();

await token.transfer(GenericCrowdsale.address, "20000000000000000000000000", {from: owner});
};

Please help me


texts: if statement evaluate incorrectly when calling contract from another contract on Remix

texts:
I have a simple piece of code but I can't not get it to work correctly.

pragma solidity ^0.4.18;

contract Interface {
     function transfer(address _to, uint256 _value) public returns(bool);
     function balanceOf(address _owner) public constant returns(uint256);
}

contract SolidContract is Interface {
    address owner;
    mapping(address => uint256) balances;
    function SolidContract() public {
        owner = msg.sender;
        balances[owner] = 100000;
    }
    function transfer(address _to, uint256 _value) public returns(bool) {
        if (balances[msg.sender] >= _value) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;
            return true;
        }
        else {
            return false;
        }
    }
    function balanceOf(address _owner) public constant returns(uint256) {
        return balances[_owner];
    }
}

contract TestCallingContract {
    Interface c;
    function TestCallingContract(Interface _c) public{
        c = _c;
    }
    function transfer(address _to, uint256 _value) public returns(bool) {
       return c.transfer(_to, _value);
    }
    function balanceOf(address _owner) public constant returns(uint256) {
         return c.balanceOf(_owner);
    }
}

When I call transfer from TestCallingContract, the if statement if (balances[msg.sender] >= _value) is always evaluated to false and therefore the transaction cannot go through. If I remove the if statement then everything works. Any idea how to fix this?

Thanks!

Chris


texts: How a json-rpc client can tell that a transaction it's sent has been rejected?

texts:
Judging from https://github.com/ethereum/wiki/wiki/JSON-RPC
the api client can synchronize on events such as:

Transaction is received/pending: eth_gettransactionbyhash returns non-null with block number null
Transaction is included in a block - eth_gettransactionbyhash returns non-null with block number non-null
Transaction has been executed as a part of accepted block: eth_gettransactionreceipt returns non-null

But if I sent a transaction that turned out to be invalid - how do I know it's failed, is there anything to wait for/react on?

UPD: There are kinds of errors that prevent transactions from even being included e.g. Insufficient balance for transfer (for the first transfer, not the nested ones issued by contracts), nonce too low/high. By "invalid" I mean transactions that produce this kind of error.


texts: Is there an estimate of average (e.g. monthly) gas usage per user?

texts:
With the whole discussion around "network value", I'm wondering how much gas the average account uses on a periodical basis.

Let's say that the relevant account pool consists of any account that has interacted with the rest of the network in recent times, e.g. six months. Of course, any transaction goes, whether simple value transaction, contract deployment or contract call.

Is there a way to figure out the average gas used for any such account? Can also be total usage since inception of network if the alternative is too complicated.


texts: Why did MyEtherWallet remove the gas price slider?

texts:
Recently I tried to figure out how to set the gas price on MyEtherWallet, while sending to another wallet.  But I've come to the conclusion that for some reason, they've intentionally disabled the ability for users to control that--even though it used to be possible on the site.  Anyone have an idea of why?  Is there a way around it?

This decision of theirs cost me quite a bit of money several days ago, as my REP was stuck in their wallet while the price doubled overnight from $55 to $107.  I tried to transfer it out to an exchange so I could sell as fast as I could, but the network was very clogged and the default gas price was
too low (21 GWei).  I searched all over their site to find a way to increase the gas price, and found an entire help page on it.  The help page has a screenshot of an older version of the website, where there used to be a slider that allowed you to control that.  But this no longer exists on the site, as far as I can tell.  So I never did find a way--I had to just wait until the network got less busy, and eventually (an hour later) my transaction went through (after cancelling and resubmitting it several times).  By then the price had dropped to $84, so I missed out on a significant amount of profit.

Here is the screenshot they include in their help page:

And here is what the site looks like now (no slider):


texts:
I have data in  zeros and ones only, I want to tightly pack the data and store it to reduce the gas cost. Also I should be able to retrieve the original data from the tightly packed.

pragma solidity ^0.4.17;
contract TightPack {
    // gas 422749
    uint[] a;
    uint[] c;

    // function to pack
    function pack(uint[] b) public{
        uint l = b.length;
        delete a;

        // Extract first element and allocate a new slot
        for(uint i=0;i<l/256;i++){

            uint j = i * 256;
            uint temp = b[j] << 255;
            // b[i] = b[i] << 7;
           // Fill until new slot is full i.e 254 values
            for(j=j + 1;j < i * 256 + 256;j++){
                temp = (b[j] << (255 - (j%256))) | temp;
            }
            a.push(temp);
        }
        // if few values are reamining at the end, allocate a new one
        if (l%256 > 0){
           uint k= (l/256)*256;
            uint val = (b[k] << 255);
            for(k=k+1; k < l;k++){
                val = (b[k] << (255 - (k%256))) | val;
            }
            a.push(val);
        }

    }

    function unpack() public {
        uint l = a.length;
        delete c;
        // remove a value from array
        for(uint i = 0;i < l;i++){
            uint temp = a[i];
            // Parse the whole value to get 255 values
            for(uint j=0;j < 256;j++){
                c.push(temp >> (255 - j) & 1);
            }
        }
    }

    function get_packed() public view returns(uint[]){
        return a;
    }

    function get_unpacked() public view returns(uint[]){
        return c;
    }

}

The packing dosent work after 1000 values, while the unpacking doesn't work after 380 values.

What is the reason for this?


texts: In the events first parameter is coming empty

texts:
I am trying to send an when a method is executed, but in all the events of my contract , the first parameter is empty, even I send it.

 event priceAdded(bytes32,address);

And I am calling that using

 priceAdded(bytes32(price),msg.sender);

The event is created like this:

priceAdded{

"": "0x751a355e8021109e332e7283ef81710bda7ef174" }

Contract code:

pragma solidity ^0.4.0;
contract Check {

mapping (uint256 => uint256) CPTPrices;

event priceAdded(uint256,uint256);

// Methods related to CPT prices.
//To store the sugery price
function addPrice(uint256 CPT, uint256 price) {
    CPTPrices[CPT] = price;
    priceAdded(CPT,price);
} }


texts: how to retrieve function call address from deployed contract for usage with MetaMask send + transaction data?

texts:
I've deployed a contract into my testrpc network.

$ truffle deploy
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  Migrations: 0x9ec9e7fedb27068a70aedf453012bbced070d1e0
Saving successful migration to network...
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying CrowdFunding...
  CrowdFunding: 0x61a235a21078920353dbb719e7c1e6bd8c8e182b
Saving successful migration to network...
Saving artifacts...

How do I get the address for the function contribute (from the example code for https://dappsforbeginners.wordpress.com/tutorials/contracts-that-send-transactions/) that looks like this:

function contribute(uint campaignID) {
    Campaign c = campaigns[campaignID];
    Funder f = c.funders[c.numFunders++];
    f.addr = msg.sender;
    f.amount = msg.value;
    c.amount += f.amount;
}

I assume I need to get the function address, and then provide that as a parameters  inside the MetaMask send dialog under transaction data. I can send the eth as the amount, correct? Then, msg.value and msg.sender are provided as context to the call.


texts:
I would like to know the most safe procedure to split my ETH.
I have one ETH account with 15 ETH end one ETC account with 7 ETC.
After the fork both wallets had 10 ETH / ETC. I transfer 3 ETH to Poloniex, after that, both account had 7 ETH/ETC. Now after adding some ETH to my wallet my situation is 7 ETC and 15 ETH. If I transfer all ETH to Poloniex what happen? I have to do something else?

Thanks.


texts:
I want to run full ethereum mainnet node on ubuntu,

what dependencies are required to install and run geth on ubuntu?


texts: Information about peers is stored in a Kademlia-like Distributed Hash Table in my node. Where is it stored? I know that admin.peers command gives me a list of nodes but I want to see the actual structure of the table with all the information about peers. Is this possible?


texts: Are transactions to EOA included in a block guaranteed to be successful?

texts:
Regardless of the source of the transaction (externally owned address / smart contract) and the data included within the transaction, if the destination is an EOA and the transaction was included in a block, can I be sure that the funds were actually transferred without verifying the transaction receipt?

If I understand right, the criteria for intrinsic validity of a transaction (yellow paper, section 6 "Transaction Execution") enforce that enough gas for the transaction is provided if no smart contract is invoked, but I may have misinterpreted the meaning of g0 and v0.

I include the excerpt from the yellow paper I'm concerned about:

  The execution of a transaction is the most complex part of the
  Ethereum protocol:  it defines the state transition function Υ.  It is
  assumed that any transactions executed first pass the initial tests of
  intrinsic validity.  These include:

  (1) The transaction is well-formed RLP, with no additional trailing
  bytes;

  (2) the transaction signature is valid;

  (3) the transaction nonce is valid (equivalent to the sender account’s
  current nonce);

  (4) the gas limit is no smaller than the intrinsic gas, g0, used by the
  transaction; and

  (5) the sender account balance contains at least thecost, v0, required
  in up-front payment.


texts:
Started a miner a few months ago and it's going to pay out a block in the next day. Problem is I can't remember where I created the wallet.

Address: CbBb080bD1D4Ed47E665d9d24Fb56791632b929b

Any way to trace where I can login to wallet?


texts: solidity variables to store decentralized identities keys -- bytes32 sufficient for a ED25519 keys?

texts:
I am building a next generation decentralized identity solution. Would like to under which solidity variable is best suited to store decentralized identities keys -- bytes32 sufficient for a ED25519 keys?

Thank you.

Nathan Aw


texts: Generating a private key from a single mnemonic

texts:
I want to generate an Ethereum private key from a single word mnemonic. For example,
(1) I could use keccack256 online tool to transform a word to a private key. Would this be a valid key? Are there any other ways this could have been done?
(2) In the case of a 12-24 word mnemonic it is possible to generate a 512-seed from the mnemonic sentence which is used to generate a private key. How might this be done with only one word as seed ‘’phrase’’? I know this is possible since it has been done but I do not understand how. Would it be done in the exact same way the seed from the 12 word mnemonic is derived from?
So how is it possible to generate a private key from a single word. Is it possible only using case (1) or also case (2) and other?


texts: can not connect to infura service in web3.js?

texts:
i am working on the web3 1.0.0 -beta.36

my code is simple, to connect to infura service and fetch a transaction.

let rpcUrl = "https://mainnet.infura.io/ocCdekUYwOyLn7h7OlJM";
      var web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl));
      web3.eth.getTransaction("0xaf7bfec2f84b35a58e93ebdf688ba079721b2ac064d7adff520100352206472d")
          .then(txObj => {
            console.log( txObj); // logs "string"
        });

[sm]:1 ERROR Error: CONNECTION ERROR: Couldn't connect to node https://mainnet.infura.io/ocCdekUYwOyLn7h7OlJM.
    at Object.InvalidConnection (errors.js:31)
    at HttpProvider.send (httpprovider.js:94)

Why i could not connect the infura service?


texts: Cannot verify Contract - bytecode has small difference


texts:
Contracts are a special kind of accounts and I therefore suspect they have their own key pair (I could not verify this).

If that is the case, how, in Solidity, can I have a contract sign a piece of data and return the signature ?

nb: to verify the signature in solidity I would then simply need to verify that the account address is identical to what the ecrecover function returns;


texts: web3.eth.getAccounts() yields an empty array

texts:
I first  started geth:  geth --syncmode "light" --rpc --rpcaddr 127.0.0.1 --rpccorsdomain "*" --datadir ~/eth_blocks/ and then used: geth account new.

I verified that there is a new entry in ~/Library/Ethereum/keystore/.

Then when i run this code:

var Web3 = require('web3')
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545/'))
web3.eth.getAccounts(function(error, data) {
    console.log(data)
})

It logs an empty array: []

Why is it not outputting what is in the keystore?


texts:
I'm looking to use a debugger on my macOS to step through the process of mining. It would me better understand the programatic process of what the miners are doing.

I have a single small GPU on my mac. I tried building ethminer from the source and running in Xcode but my GPU doesn't have enough memory.

Does anyone know if I can somehow use a smaller DAG or is there another simple tool to help me do this?


texts: How to measure time in private network and to control mining process?

texts:
I am using private network with geth 1.7, and have some questions

1- To get the time of executing a function, i found some discussion about use of Data.getTime(), but i am wondering if anyone was successfully able to implement other methods such as performance.now() to measure time in geth commandlines? I tried but seems not defined function!!

2- how can i get the timestamp for a specific block if i knew the block number?

3- how can i mine only one block. For example, i send one transaction to the private network and then only mine one block containing that transaction. I found here some suggest to use while loop to check if there is no pending transactions and then stop mining. But i do not want this method, i would rather prefer to only mine one block.

Thanks in advance,


texts: Contracts invoked asynchronously are not packaged as transactions

texts: I use the sendAsync() method to call the contract asynchronously. If I loop through the method several times, without using get(), the number of packaged transactions is less than the number of calls, and data loss occurs.


texts: Safe implementation on Solidity 0.8.0 of a withdrawal and a refund

texts:
I'm here for asking of a SECURE way to implement on solidity 0.8.0 two functions:
1-Withdrawal() which sends all the ether of the smart contract to the owner address. My current implementation is:
//send the ethereum on this contract to the owner
function withdraw() external onlyOwner {
        address payable _owner = payable(owner());
        _owner.transfer(address(this).balance);
 }

2-Refund() which sends ether to the buyer of my token if the msg.value exceeds the cost of a single token. My current implementation is:
function createToken(xxx parameters) payable public {
        require(msg.value >= TokenCost, "not enough ether sent!");

        _createToken(xxx parameters);

        //refund user if he/she pays more than the singleCarCost value
        payable(msg.sender).transfer(msg.value - TokenCost);
    }

Thanks in advance!
Simone :P


texts: Is there a way to convert a decimal number to binary?

texts:
I am new to Solidity, so please, accept my apologies, if the question is really dumb.
I am trying to write two functions, one of which gets the uint256 and converts it to a binary number, and the other gets the binary input (if that's even possible) and returns a uint256.
Is such a conversion even possible?


texts: Is it possible to store an array of bytes (so something like bytes[])?

texts:
Edit

The original question below seems to work as expected. The issue happens with the call return data is empty. When the response is nothing, the code below fails.

The following works, but is there a better way to do it?

bytes[] memory val;
for(uint i = 0; i < item.length; i++) {
    (, bytes memory response) = addr.call.value(_value[i])(_data);
    if (response.length != 0) {
        val[i] = response;
    }
}

I am unable to figure out how to store an array of bytes. I understand that bytes is an array of byte1s, but I want to be able to store multiple bytes in an array? So ideally, I would be able to define bytes[], where each member of that array is a new bytes.

Some example code (which is not working) is:

bytes[] memory val;
for(uint i = 0; i < _value.length; i++) {
    (, bytes memory response) = addr.call.value(_value[i])(_data);
    val[i] = response;
}

This is reverting on val[i] = response;. Does anyone know why?


texts: How can i transfer erc 20 tokens manually in bulk?

texts: Can anyone help me with how to transfer tokens manually in bulk?as i have to transfer tokens to multiple ETH addresses but cannot waste time transferring it one by one.


texts:
I deployed this contract to send token to multiple address at the same time:

pragma solidity ^0.4.18;

contract distribution {

event Transfer(
        address owner,
        address addresses,
        uint _value
        );

mapping(address => uint) balances;

address private owner;

function distributeBlox(address[] addresses, uint256 _value)  {
    for (uint i = 0; i < addresses.length; i++) {
        balances[owner] -= _value;
        balances[addresses[i]] += _value;
        Transfer(owner, addresses[i], _value);
        }
    }
}

After the contract deploys I try to input the addresses that I want to send tokens to, usually

"0xd1c13af8D667bBd48F0dd09B61d19659860E656E"

works for inputing and address but since is in an array I was inputting like this:

["0xd1c13af8D667bBd48F0dd09B61d19659860E656E","0xF10257752c3451595e8cE12E 6770fBbbf598E6F6"],5000000.

But it keeps marking me

errored: Error encoding arguments: SyntaxError: Unexpected token “ in
JSON at position 2.

I've trying different ways of writing the inputs but nothing seems to work. Any help is more than welcome. Thank you


texts: Web Server Listen For When ERC20 Token Transferred

texts:
Is it possible to have a web server listen or know when a transfer has been made on a particular ERC20 Token Contract?

From what I researched, we are not able to make a HTTP request inside the contract's transfer method.

Is there some way for an external web server to "watch" the blockchain for when those custom tokens are transferred?

Thanks


texts: How to deploy a smart contract in a server?

texts: I have developed a smart contract and compiled it with solc and bin and abi fils have been generated. Now, I want to deploy this contract using web3js in a linux server. How can I do it?


texts:
pragma solidity ^0.6.0;

library Address {

    function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

Hi, please, advise me what is creating this error:)

ParserError: Expected ';' but got '{' (bool success, ) = recipient.call{ value: amount }(""); ^


texts: I created an ethereum account on the sale.augur.net page. And now I've finally downloaded and installed Geth as well. How do I import that account into Geth?


texts: Was the eth2 beacon chain merger sandboxed prior to launch?

texts: From what I understand eth is supposed to ultimately migrate with the eth2 beacon chain then there's supposed to be some cleanup of the chains and they integrate. Was this process actually sandboxed and tested prior to being implemented on mainnet? God forbid some old/legacy/placeholder code in the cleanup does something drastic and unintended.


texts: Restricted Access / Authentication for a Remote Geth Node

texts:
I have setup remote geth nodes that are constantly running as web3 providers to support my DApp.

What is the best way to restrict access to make sure that only authorized clients (my server) are connecting to this geth node?

For example, infura requires an access key for users: https://mainnet.infura.io/{ACCESS_KEY}.

How would I set something like that up for my geth node?

The RPC port of the geth node is 8545 and I am using an nginx reverse proxy to serve an SSL/TLS connection on port 443 since my DApp is secured (https).


texts:
I have to create a contract to distribute 1000 tokens to 1000 addresses (1 token each). I have no idea how to do this. Can someone please advise?

I know I must create a contract, but what code should I use? Is it possible to specify a gas limit for each transaction?

Also, what parameters do I need to configure for this to work when actually sending?

Apologies for my greenness


texts:
When I "truffle test" and the below runs, I get 1,3 as the output. How do I make everything happen in order, I want to force it to wait until dai is defined.

const DAI = artifacts.require("DSToken");

async function asyncC() {
console.log("1");
const dai = await DAI.at('0xD0fC300fAa2d474cae17B3A0045204dE093152Fb');
console.log("2");
}

asyncC();
console.log("3");

I also tried pasting in some code that should definitely wait, which has nothing to do with web3, I found it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

I put this into my truffle test file and ran truffle test -- again it did not wait. Is truffle running a modified version of javascript, or doing some preprocessing?

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();


texts:
In the JSORRPC wiki page, we can obtain a log with these format

For filters created with eth_newFilter logs are objects with following params:

removed: TAG - true when the log was removed, due to a chain reorganization. false if its a valid log.
logIndex: QUANTITY - integer of the log index position in the block. null when its pending log.
...

How ever when i use rpc to get a event log and found not removed field at all?
Is this field be removed?

If there is no such field, how can i judge whether is log is in fork chain or in the canonical chain


texts: Why does this contract cost 1 Eth to deploy?

texts:
Truffle is telling me that it costs 1 Eth to deploy. Is that seriously the cost of deploying a simple contract (this is my first Mainnet deploy)?  Or is there something else going on?
 mainnet: {
      provider: () =>
        new HDWalletProvider({
          mnemonic: { phrase: process.env.MNEMONIC },
          providerOrUrl: process.env.RPC_URL_1_WSS,
        }),
      network_id: 1, // Main's id
      from: process.env.DEPLOYERS_ADDRESS,
      gas: 4712388, // Gas limit used for deploys. Default is 4712388.
      gasPrice: 211000000000, //Gas price in Wei
      confirmations: 2, // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200, // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: false, // Skip dry run before migrations? (default: false for public nets )
    },
  },

pragma solidity ^0.7.4;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";

contract EthMsg {
  address payable public owner;
  uint public messagesSentCount = 0;

  uint decimals = 8;
  uint scale = 10**decimals;

  uint public txtPriceUSD = 1.70 * 10**8;
  uint public txtPriceEth;

  using SafeMath for uint;

  AggregatorV3Interface internal priceFeed;

  event Spend(
    string textMsg,
    string recipient
  );
  event TextMsgError(
    string reason
  );

  constructor(address oracleAddress) {
    owner = msg.sender;
    priceFeed = AggregatorV3Interface(oracleAddress);
  }

  function sendTextMessage(
    string calldata textMsg,
    string calldata recipient
  ) external payable returns(bool) {

    (uint newTxtPriceEth,,) = this.pollTxtPrices();

    require(
      msg.value > newTxtPriceEth,
      'Please send the correct amount of ETH to make send a message'
    );

    emit Spend(textMsg, recipient);
    messagesSentCount += 1;
    return true;
  }

  function setTxtPrices(uint _txtPriceUSD) external ownerOnly() {
    (int price,) = getLatestPrice();
    uint ethPriceUSD = uint(price);

    txtPriceEth = scale.mul(_txtPriceUSD).div(ethPriceUSD);
    txtPriceUSD = _txtPriceUSD;
  }

  function pollTxtPrices() external view returns(uint, uint, uint) {
    (int price,) = getLatestPrice();

    uint newTxtPriceEth = scale.mul(txtPriceUSD).div(uint(price));

    return (newTxtPriceEth, txtPriceUSD, decimals);
  }

  function totalBalance() external view returns(uint) {
    return payable(address(this)).balance;
  }

  function withdrawFunds() external ownerOnly() {
    msg.sender.transfer(this.totalBalance());
  }

  function destroy() external ownerOnly() {
    selfdestruct(owner);
  }

  function getLatestPrice() public view returns (int, uint) {
    (
      ,int price,,,
    ) = priceFeed.latestRoundData();

    return (price, decimals);
  }

  function uintToWei(uint unum) private pure returns(uint p) {
    return unum * (1 wei);
  }

  modifier ownerOnly() {
    require(msg.sender == owner, 'only owner can call this');
    _;
  }
}

truffle migrate --network mainnet --reset
  Replacing 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" could not deploy due to insufficient funds
   * Account:  0x16c8CF300eRa61f6d8e7S201AB7163FCc6660f1d
   * Balance:  297068575000000000 wei
   * Message:  sender doesn't have enough funds to send tx. The upfront cost is: 994313868000000000 and the sender's account only has: 297068575000000000
   * Try:
      + Using an adequately funded account
      + If you are using a local Geth node, verify that your node is synced.

Upfront cost is 994313868000000000 Wei??
That's almost 1 Eth!


texts: I am developing a transaction analysis in a certain scenario on the Ethereum platform. Reading about, I understood that there is not a limit of transactions per block, but a limit of gas. Would anyone have a mathematical equation to calculate this?


texts: How to pass constructor arguments in web3.py

texts:
I'm trying to deploy smartcontract with web3.py. below is my simple smart contract:

pragma solidity ^0.5.0;

contract homeAutomation{
  string public greeting;

  constructor(string memory _greet) public {
    greeting=_greet;
  }

  function greet(string memory _gree) public {
    greeting =_gree;
  }
}

below is my web3.py code

contract = w3.eth.contract(abi=abi, bytecode=bytecode)
K = input('write your greeting:' )
# Get transaction hash from deployed contract
tx_hash = contract.deploy(K,transaction={'from': w3.eth.accounts[0], 'gas': 410000})
# Get tx receipt to get contract address
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
contract_address = tx_receipt['contractAddress']

when I tried this, I am getting error

TypeError: deploy() got multiple values for argument 'transaction'

so please let me know how to pass constructor argument to deploy function


texts: Get the amount of Smart Contracts hosted on the ETC blockchain

texts:
I have a couple of questions:

How can I determine the amount of Smart Contracts that are hosted on the ETC blockchain?
Of these smart contracts, how many of them have been verified?

I guess geth is necessary for this, but I am not sure. Thanks in advance.


texts: So I get that Ethereum POW is different from Bitcoins POW, I dont get the calculation of nonce from the pseudo random nodes from the data set to serve as POW, can somebody elaborate on this ?