texts: TypeError: Member not found or not visible when using a struct

texts:
I am writing code for a contract to keep track of Theatrical plays. I get this error on this line:

play1.PlayTitle   = PlayTitle; (line 62 below)

  browser/teste.sol:62:13: TypeError: Member "PlayTitle" not found or
  not visible after argument-dependent lookup in struct
  Plays.PlayActionInfo storage ref[] storage ref
              play1.PlayTitle                          = PlayTitle;

        ^-------------^

I do have PlayTitle defined in both structs. I envision the user will enter the play title when the contract is created and when there are updates to the play information. The fact I define it twice may be part of the problem.

But I when I deleted the line containing PlayTitle, the next line (            play1.PlayWorkerName[numUpdates]  = PlayWorkerName; ) got the error.

Could someone explanation the meaning of the error? Any other code suggestions would be appreciated.

I did see other questions with the same error but the solutions didn't seem relevant to my code.

For my environment configuration, I'm using Remix in a Chrome browser.

Here's all my code:

pragma solidity ^0.4.18;

contract Plays
{
    //used to store information about the owner of the Play
    struct TopLevelPlayInfo {
      address PlayOwnerAddress;
      bytes32 PlayOwnerName;
      bytes32 PlayTitle;
    }
//instance of the owner
TopLevelPlayInfo playi;

//map into the PlayOwner based upon the owner's address
mapping (address => TopLevelPlayInfo) public theTopLevelPlayInfo;

//used to store actions taken to complete Play
struct PlayActionInfo  {
  bytes32   PlayTitle;
  bytes32   PlayWorkerName;
  address   PlayWorkerAddress;
  bytes32   PlayAction;
  bytes32   PlayActionDescription;
  uint256   PlayActionTimestamp;
  bytes32   PlayStatus;
}
//the instance of the struct
PlayActionInfo [] play1;

//map into the Play action
mapping (uint => PlayActionInfo) public thePlayActionInfo;

//State variables for storage - do I need these
// as state variables since they are also in a struct?
uint    numUpdates;
address theOwnerAddress;

//will be used to ensure only owner closes Play when work is accepted
modifier onlyOwner(){
  if(msg.sender != theOwnerAddress) revert();
  _;
}

//constructor for contract
function Plays(bytes32 thisPlayOwnerName, bytes32 thisPlayTitle) public  {
    //establish the owner
    playi.PlayOwnerAddress = msg.sender;
    theOwnerAddress        = msg.sender;
    playi.PlayOwnerName    = thisPlayOwnerName;
    playi.PlayTitle        = thisPlayTitle;
}

//used to enter a new action against thePlay
function PlayUpdate(
      bytes32   PlayTitle,
      bytes32   PlayWorkerName,
      bytes32   PlayAction,
      bytes32   PlayActionDescription,
      bytes32   PlayStatus)
      public {
        play1.PlayTitle                          = PlayTitle;
        play1.PlayWorkerName[numUpdates]         = PlayWorkerName;
        play1.PlayWorkerAddress[numUpdates]      = msg.sender;
        play1.PlayAction[numUpdates]             = PlayAction;
        play1.PlayActionDescription[numUpdates]  = PlayActionDescription;
        play1.PlayActionTimestamp[numUpdates]    = block.timestamp;
        play1.PlayStatus[numUpdates]             = PlayStatus;

        //update the number of updates to this contract
        numUpdates++;
}
}

Thank you


texts:
I have your latest version of contracts and almost same example like yours in the Github https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/examples/SampleCrowdsale.sol -
I use Ganache for testing on MAC os.
And the contract work only when I comment the line

function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
    //token.transfer(_beneficiary, _tokenAmount);
  }

if this is not commented I got a runtime error and revert.

My simple code is as follow:

TOKEN

pragma solidity ^0.4.18;

import 'zeppelin-solidity/contracts/token/ERC20/MintableToken.sol';

/**
 * The LeonardianToken contract does this and that...
 */
contract LeonardianToken is MintableToken {

    uint256 public constant INITIAL_SUPPLY = 10000;

    string public constant name = "Leonardian"; // solium-disable-line uppercase
    string public constant symbol = "LEON"; // solium-disable-line uppercase
    uint8 public constant decimals = 18; // solium-disable-line uppercase
}

CONTRACT:

pragma solidity ^0.4.18;

import 'zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol';
import "zeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import './LeonardianToken.sol';

contract LeonardianCrowdsale is Crowdsale {

    function LeonardianCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public
    Crowdsale(_rate, _wallet, _token)
    // TimedCrowdsale(_startTime, _endTime)
    {

    }
}

MIGRATION (without any errors):

var LeonardianCrowdsale = artifacts.require("./LeonardianCrowdsale.sol");
var LeonardianToken = artifacts.require("./LeonardianToken.sol");

module.exports = function(deployer) {

  deployer.deploy(LeonardianToken).then(function () {

    const startTime = Math.round((new Date(Date.now() - 86400000).getTime())/1000); // Yesterday
    const endTime = Math.round((new Date().getTime() + (86400000 * 20))/1000); // Today + 20 days
    var exchangeRate = 1; // 1 LEON = 0.0025 ETH or 1 ETH = 400 LEON

    deployer.deploy(LeonardianCrowdsale,
        startTime,
        endTime,
        exchangeRate,
        "0x627306090abaB3A6e1400e9345bC60c78a8BEf57", // Replace this wallet address with the last one (10th account) from Ganache UI. This will be treated as the beneficiary address.
        LeonardianToken.address
      );
  });

};

Can you help me what I`m doing wrong?

SOLUTION

As mentioned ERC20 _token = new LeonardianToken(); must be instanced in the Crowdsale contract and an important thing to work everything after this is to change your migration a little bit

return deployer
    .then(() => {
        return deployer.deploy(Token);
    })
    .then(() => {

        return deployer.deploy(
            Crowdsale,
            startTime,
            endTime,
            exchangeRate,
            "wallet",
            Token.address
        );
    })
    .then(() => {

        var token = Token.at(Token.address);

        token.transferOwnership(Crowdsale.address);
    });


texts: Encode function signature with callback function as parameter in Solidity

texts:
I would like to use low-level call to make calls to my contract. The function takes a callback function as an argument and I am not able to encode it.
This is my code:
contract B{
   event Foo();
   ...
   function foo(bytes32[10] calldata values,function(int256[] memory, bytes32[] memory) external callback){
       emit Foo();
       ...
   }

}

contract A{

    address b;
    ...

    function bar(){
       (bool success, bytes memory data) = b.call(
            abi.encodeWithSignature(
                "foo(bytes32[10],function(int256[],bytes32[]))",
                myArray,
                this.callback
            )
        );
        if (!success) {
            revert("CALL Failed");
        }
    }

    function callback(int256[] calldata mapInt,bytes32[] calldata mapBytes32) external {
        ...
    }

I did manage to create a correct encoding using web3, which I compared with the signature in the ABI:
var encoded = web3.eth.abi.encodeFunctionSignature({
    name: "foo",
    type: "function",
    inputs: [
        {
            type: "bytes32[10]",
            name: "values",
        },
        {
            type: "function",
            name: "callback",
            inputs: [
                {
                    type: "int256[]",
                },
                {
                    type: "bytes32[]",
                },
            ],
        },
    ],
});

How can I accomplish this in solidity? The encoding in bar() does not work.
Update: Using the bytes4 encoded signature below does not work either:
b.call(abi.encodeWithSelector(bytes4(0x48160c65), myArray,this.callback));


texts: How can I pass struct as function parameter with ABIEncoderV2 from outside?

texts:
have this code:

struct UserScore {
    address user;
    uint score;
    uint time;
}
function getWithStruct(UserScore _user) public view returns (address, uint, uint) {
    return (_user.user, _user.score, _user.time);
}

It seems that metamask does not support this feature at the moment. But is there a workaround? It is necessary for me that users with metamask could transfer the signed data in the form of structure. What I can do for it?


texts: Getting the transaction hash on function call

texts:
I am new to Solidity, Web3, and Ethereum.
I am trying to build a web application through which users can upload a file to IPFS, then store the IPFS hash in the blockchain. I am using the React truffle box and the value is being stored via the SimpleStorage contract that's included with the box.

So essentially, the ideal scenario would be:
User A uploads the file to IPFS and its hash is stored in the blockchain. User B can then access the file by typing the transaction hash and getting its storage value to check whether it's authentic or not.

The problem is that in order for User B to be able to check the file's authenticity, they need to have the transaction hash. Is there a way for a function to return the hash on function call? I can get it manually through Ganache, but that's just impractical.

The blockchain is very nice because it gives you the ability to permanently store data within it, but is there a way to check that data?

Thank you.


texts: Invalid sender when sending Raw Transaction, signed w/ ethereum-tx on PHP

texts:
I am using PHP and ethereum-tx library https://github.com/web3p/ethereum-tx to sign transactions but when trying to send them to the node I got an "invalid sender" error. Besides, exactly the same transaction signed by myEtherWallet https://www.myetherwallet.com/#offline-transaction yields a different result. So I guess ethereum-tx library is applying a different standard than myEtherWallet or I am doing something wrong when signing transaction.

The transaction is a very simple one, just sending 0.1 ether from a wallet to a contract:

$fromAddress = '0x0a2E9bBA44b58841174115b4859297D86d6e8eB0'; // My wallet
$fromPassword = '0x...'; // My pkey
$toAddress = '0x7665822efbd0fde3a4f3f57eccaecdc99b8a64a4'; // A contract address

$transaction = new Transaction([
     'nonce' => '0x14',
     'from' => $fromAddress,
     'to' => $toAddress,
     'gas' => '0x5208',
     'gasPrice' => '0x00',
     'value' => '0x016345785d8a0000' // 0.1 eth
]);

This is PHP code for signing the transaction:

<?
require_once('vendor/autoload.php');
use Web3p\EthereumTx\Transaction;

$transaction = ... <the code above>

$signedTransaction = $transaction->sign($fromPassword);
?>

And the resulting signed transaction is:

0xf8671480825208947665822efbd0fde3a4f3f57eccaecdc99b8a64a488016345785d8a00008023a0b21679034fd6304c1058a5d7505e284630fec38a0f8d3551261e9c45f056859aa041b397f49f566ce12fec2de93934987d119ab7ced2b0916ddb993b0879707d05

Meanwhile same tx signed through myEtherWallet returns:

0xf8671480825208947665822efbd0fde3a4f3f57eccaecdc99b8a64a488016345785d8a0000802aa0f0dd7d6e244b43b2ca138fef989c38f40bac304f50f4c052ef0c4175eaffeac3a038cb792e21016c171355afefc821fe9ec3b7accce9a094e7a6f5a9129c34b5ac

How can I find out why first signed transaction is invalid and how to fix it? Any ideas? Thx!


texts:
In a multi node network, if one node is down (and a majority of nodes are up and running) for a period of time - say its down at block 100 block and rejoins when the network is at block 200.

Q1: Will it copy the entire information from nearby nodes?

Q2: During replication, will it execute transactions in all blocks?

Please let me know what exactly happen in this scenario


texts: Accessing Ethereum network via JSON RPC from wallet balance/transactions

texts:
sorry if the question is silly.... I am tying to build a simple app that checks ETH wallet addresses balances and transactions (for both ETH and Tokens).

As far as my knowledge goes, I think that I have two options:

web3.js -> for which I need access to a node (hosted myself or by third party like infura.io)
JSON RPC -> do I still need to access a node, or I can just "tap" into the network (a bit like ElectrumX nodes in Bitcoin?)

If I host a node (to be used with web3.js), does it need to be a "full node"? (that will be so big and so expensive (if i run in in AWS)

I have tried infura, but it does not seems to be reliable (requests time-out so frequently)

Any suggestion?

Thank you all


texts:
When I run my Mist wallet, the internet becomes unusable.
I get a lot of timeout when browsing and page takes forever to be displayed.

I thought that maybe it was uploading too much to other people, so I installer the NetLimiter program. I saw that on occasion it was uploading at 50 KB/s, but most of the time it was very little like 2 KB/s or 0 KB/s.

What is odd is that the internet does not work even when the wallet is fully synced and I see no upload or download traffic from the wallet.

I got the message:

  DNS_PROBE_FINISHED_NO_INTERNET

This problem also impact other computers, making me think that somehow the wallet just kill my router or my Wi-Fi.

Did any of you experience a similar issue? What could be the cause of the problem?

I am using Windows 10, my connection over WiFi is 70 Mbps in download and 59 Mbps in upload.


texts:
In Brownie I'm running a script which sends me this error "AttributeError: Module 'Users' Has No Method 'Main'. Do you have any suggestions on how I can fix this?
import os
from brownie import network, accounts, config, Hello

def main():
    my_account = accounts.add(os.getenv(config['wallets']['from_key']))
    hello = Hello.deploy({'from': my_account})
    print(hello.address)

This is what I receive when I run the deploy.py script:
Brian Lee@MSI MINGW64 ~/Python39/brownie/New folder
$ brownie run scripts/deploy.py --network kovan
INFO: Could not find files for the given pattern(s).
Brownie v1.14.3 - Python development framework for Ethereum

NewFolderProject is the active project.
  File "c:\users\brian, line line, in in
    return_value, frame = run(
  File "c:\users\brian, line line, in in
    raise AttributeError(f"Module '{name}' has no method '{method_name}'")
AttributeError: Module 'Users.Brian Lee.Python39.brownie.New folder.scripts.deploy' has no method 'main'```


texts: Why is the transactionsRoot the same hash as "empty patricia merkle trie" root hash?


texts: contract interaction error: function should be payable

texts:
I apologize if it is a simple question. I tried to create a simple contract interaction. I've tried to follow instructions on https://ethereum.stackexchange.com/questions/51760/contract-interaction, docs, and another examples to create a simple contract interaction in solidity 0.5.16. There are two contracts, one is a hello-world contract, called con_H (H of "hello") and owns the helloworld() function. The other one is a contract "A" that calls the helloworld function of con_H. The point is that remix-ide throws an error that I find strange:
call to con_A.fun_A1 errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
The code is the following one:
pragma solidity ^0.5.16;

contract con_H {
  function helloWorld() external pure returns (string memory) {
    return "Hello, World!";
  }
}

contract con_A {
    con_H ins_H;

    function fun_A1() external view returns (string memory) {
        return ins_H.helloWorld();
    }
}

I've also tried for initial lines of con_A:
contract con_A {
    con_H ins_H = con_H(msg.sender);
    ...
}

with msg.sender address with enough balance of 100 test-ETH.
The only way I manage it to work is deploying aside con_H at a given direction 0x..123 and then force the instance H inside con_A with that exact address: con_H ins_H = con_H(0x..123);
How should be done? suggestions..?


texts: Two different owners on same computer with MetaMask Wallet?

texts:
Is this possible?
I have a MetaMask wallet working fine. A friend w/o computer - can I set him up with MetaMask on my system - but obviously not my account. If so, how?


texts:
this is the method that I call:
function depositAll() public {
        address(0xf5eA38B6b9644224dA1aECbC1219e8543c0689b2).call(abi.encodeWithSignature("depositAll()"));
    }

and this is the gas required:
https://bscscan.com/tx/0xae55f895817e9f985372cdfe61d1c972f24088ee4cbb01e9b20983054e70f9e0
Gas used: 119,307 (45.81%)
this are failed transaction because I ran out of gas:
https://bscscan.com/tx/0x66f63e1b185b7b8f406e690e33833bf367d226ee56abdfab254d7b4ec2e6d37b
https://bscscan.com/tx/0xaeaba37b2468375b6ea82187e6c565bb246b02cd472c3b350cb7983930ab4425
https://bscscan.com/tx/0x2c56e1ae3eb05f98141aa504fa76b03d0678d439e1652152efd5c0174e922339
https://bscscan.com/tx/0x7fdd50cee23295ea866baa8961a2105c58162e77125df852a4fc5bf0fad2f507
How can I calculate the gas beforehand?
the transaction from the contract directly (contract address: 0xf5eA38B6b9644224dA1aECbC1219e8543c0689b2) took 271,839 (57.36%) gas (this because I deposited more in this transaction so it called more smartcontracts)


texts: Connecting HTML buttons to functions of my smart contract

texts:
These solidity functions are part of my solidity code which i want to execute them by clickcing on a button on my HTML.One of them stands for accepting bets placeBet() and the other one for sending back the gains to winner gamblers claim().
function placeBet(Side _side) public payable {
    require(msg.value > 0, "Sorry we cannot accept Zero values");
    require(ended == false, "Unfortunately accepting bets is over!!");
    bets[_side] += msg.value;
}

    function claim() public {
    require(ended = true, "Game is not over yet sir!");
    uint gain = gamblerBet + (bets[result.LOSER] * gamblerBet / bets[result.WINNER])
    payable(msg.sender).transfer(gain);
    remainingWithdrawal -= 1;
}

Here is my contract instance getting saved into state object.
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = PredictionContract.networks[networkId];
      const instance = new web3.eth.Contract(
       PredictionContract.abi,
       deployedNetwork && deployedNetwork.address,
      );
      this.setState({ web3, accounts, contract: instance });

As you can see first solidity function accepts a parameter which is defined at the beggining of my script as a struct and second function does not need any parameter.
I have used truffle react box for user interface.Inside of App.js file after saving the contract instance into the state object i wanted to access its functions as below but it didn't work.
Here are a button refers to claim() function and a button for placeBet() in my render section.
<button type="button" onClick={this.claim}>CLAIM YOUR REWARD :)</button>
<input type="button" onClick={this.submitBetA} value="PLACE BET"/>

And finally here are my Javascript functions to connect buttons to their intended smart contract function but it does not work as well.
submitBetA = () => {
this.state.contract.methods.placeBet("0").send({from: this.state.accounts[0], value: this.state.amountA})}
claim = () => {
this.state.contract.methods.claim().send({from: this.state.accounts[0]})}

Values for submitBetA is taken from my state object.
Could anyone tell me where is my problem cause the buttons doesn't work properly.


texts: Problems setting two local nodes on the same computer

texts:
i'm setting two local nodes on the same computer as different users (two different sessions). The problem is that i can't make them be peers.

Command to wake main node:

geth    --identity "MainNode" \
        --rpc \
        --rpcport 8000 \
        --rpccorsdomain "*" \
        --datadir "/home/ubuntu/ethereum" \
        --port "30303" \
        --nodiscover \
        --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" \
        --rpcapi "db,eth,net,web3" \
        --autodag \
        --networkid 10165211 \
        --nat "any" console init /home/ubuntu/ethereum/CustomGenesis.json

Command to wake second node:

geth    --identity "My Node" \
        --rpc \
        --rpcport 8001 \
        --rpccorsdomain "*" \
        --datadir "/home/xxxx/ethereum" \
        --port "30304" \
        --nodiscover \
        --ipcdisable \
        --rpcapi "db,eth,net,web3" \
        --autodag \
        --networkid 10165211 \
        --nat "any" console init /home/xxxx/ethereum/CustomGenesis.json

But when i start the nodes, and i use the command admin.nodeInfo i find this in the first node:

admin.nodeInfo
{
  enode: "enode://34f8ec977f25f4a85d4d7debac748fd82851b75ca670b2ece234c9a26a493fb995fca0021b9eee6cb2ccfa98a934cdb4a8590e4a4140a1077575f94a82468129@[::]:30303?discport=0",
  id: "34f8ec977f25f4a85d4d7debac748fd82851b75ca670b2ece234c9a26a493fb995fca0021b9eee6cb2ccfa98a934cdb4a8590e4a4140a1077575f94a82468129",
  ip: "::",
  listenAddr: "[::]:30303",
  name: "Geth/v1.4.12-stable/linux/go1.5.1/MainNode",
  ports: {
    discovery: 0,
    listener: 30303
  },
  protocols: {
    eth: {
      difficulty: 17179869184,
      genesis: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
      head: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
      network: 10165211
    }
  }
}

And THIS, on the second one:

 admin.nodeInfo
{
  enode: "enode://34f8ec977f25f4a85d4d7debac748fd82851b75ca670b2ece234c9a26a493fb995fca0021b9eee6cb2ccfa98a934cdb4a8590e4a4140a1077575f94a82468129@[::]:30304?discport=0",
  id: "34f8ec977f25f4a85d4d7debac748fd82851b75ca670b2ece234c9a26a493fb995fca0021b9eee6cb2ccfa98a934cdb4a8590e4a4140a1077575f94a82468129",
  ip: "::",
  listenAddr: "[::]:30304",
  name: "Geth/v1.4.12-stable/linux/go1.5.1/My Node",
  ports: {
    discovery: 0,
    listener: 30304
  },
  protocols: {
    eth: {
      difficulty: 1024,
      genesis: "0x1a8c903ab9d8b7bec7ba8b15dab33a3418c90dbf8f73ec3086d34b4e17e017e6",
      head: "0x1a8c903ab9d8b7bec7ba8b15dab33a3418c90dbf8f73ec3086d34b4e17e017e6",
      network: 10165211
    }
  }
}

Even when the CustomGenesis.json file is a pure copy of each other (completely) we can see some strange things:

the enode ID is the same in both cases. It should not be.
The port changes (obviously it must be done that way). It's OK.
The difficulty is not the same, it should be.
The genesis hash and the head are not the same. I guess they should be.

I'm sure is not a Genesis.json file problem, as i've even tried to use the same file for both nodes but the same i'm explaining here happenned to me.

Any idea on where's the error/mistake/bug?

THANK YOU.


texts: What is best approach for generating random NFTs?

texts:
I am thinking of developing small DApp where user would collect cards (NFT). Each card would have some image and value associated with it. User collects cards by purchasing Pack of Five Cards which user can open and get 5 random cards of different value. Some cards would me more rare than others... This would create marketplace where users can buy/sell cards...
The problem I have is how to generate these random cards. I read a lot about randomness on blockchain and how it can be exploited so I have few options.
Optiona A:
Use Chainlink's VRF which gives me number like this:
60 281 005 833 581 254 158 276 701 724 503 448 998 474 868 621 179 906 924 992 243 038 007 226 057 672

Which has 77 digits (I am not sure if this is always the case, but testing on kovan network it seems it always has 77 digits). I can use these group of 3 digits which will give me random card... But this way user is limited to buying max 5 (or less) x Packs of Five Cards... I need to use group of three digits or more depending on how many cards are there in a set and different cards would have different weights so I would use those weights to pick random card from set.
Option B:
User approves some stable coins to contract address via MetaMask, and calls my backend which in turns has private keys to contract and backend picks all random cards and just sends instructions to contract to mint new NFTs and assign them to user who bought it...
But in this approach I need to pay for gas fees, and also I suppose that gas fees would be high for creating like 100 tokens at once (if user bought 20 Packs of Five Cards)
Option C:
I don't know if this is possible, but is there a way to create contract on Chainlink node, which would generate as much random numbers as needed... I would still limit users to buy max 10 packs, and chainlink contract would in return generate max 50 random numbers in range 1 and 1000 (or a bit more depending on sum of all weights of cards in set) and return them to my contract which would then mint these NFTs...
Is there any other way how to implement this. And also I suppose Option B would create some negative comments since that would be outside of blockchain and it won't be transparent...


texts:
Reading my input data on etherscan, I see each value as hex values. Which is fine to read the addresses. But I would like to read the amounts [1] && [3] as numbers.
Contract Method
Function: trade(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount)

input data
MethodID: 0x0a19b14a
[0]:0000000000000000000000000000000000000000000000000000000000000000
[1]:000000000000000000000000000000000000000000000016d8fceafcef3c0000
[2]:000000000000000000000000340d2bde5eb28c1eed91b2f790723e3b160613b7
[3]:00000000000000000000000000000000000000000008b7363b040ca2bb600000

I made a transaction etherdelta where I bought 25 tokens. So the expected transformed value of the input data [1] should be 25 or 25 * 10^18 (in wei) or at least any multiple of 25*10^x.
Question
How to convert the hex to the expected value?
Tries

Using https://github.com/miguelmota/ethereum-input-data-decoder
shows me the same values as on etherscan.io

converting to Ascii gives garbage (as recommended here: How to decode input data from a transaction?)

web3.utils.hexToNumberString & web3.utils.hexToNumber err

console.log(0x000000000000000000000000000000000000000000000016d8fceafcef3c0000)
shows some arbitrary value


texts:
What is the maximum size of NFTs on the Ethereum blockchain (ERC-721 or ERC-1155 tokens)?
crypto art NFTs on the Ethereum blockchain already contain JPG/PNG files that are about 5 MB large, and sometimes even motion graphics in MP4 format about 50 MB large, so why not full-length hour-long movies wrapped inside an NFT?
Is this impossible to do on the Ethereum blockchain, or would a whole separate company and blockchain be required to support that digital video ecosystem?


texts: ethereum question - why is my node returning 0 transactions for a block, but etherscan returning many?


texts: Does Transfer event fire for transactions in pending status (not confirmed) on ethereum platform?

texts:
I am developing a software that deals with smart-contract in ethereum platform (ERC20) that transfers tokens from one wallet to another. I have ethereum node (geth) deployed on my server that listens for events.

I need to catch Transfer events whenever someone sends tokens to my smart-contract. Is it possible? I just in doubt when I would receive transfer event:

When transaction was already approved?
or
When transaction was just created and then when it was confirmed/rejected?

I need to achieve the second behavior. Is it possible?


texts: What is the difference between account nonce and block nonce?

texts:
Block and accounts both use a value called "nonce" but they seem to represent something very different.

For account I understand that the nonce is an integer quantity indicating the number of transactions created by this account to prevent replay of transactions.
For block, I understand that it's a 64-bit value that, combined with mix-hash, proves the computational work required to build the block was made.

If my understanding is right, do you have more info on how this block nonce is computed? And perhaps why it's called the same way as the account nonce even if they are not the same things?


texts: I am trying to compile my solidity code in remix editor. I keep getting this error "Optimization exception during compilation". I was using solidity version 0.5.2 till day before yesterday. Now, It is not letting me choose the version or higher version which is nightly build.


texts: We can test our smart contract in remix and can perform several workflow checks before putting the contract in the final sol file in the dapp project. This way we can ensure that everything is in place and executing as expected. Then why do we need a test.js file separately to put a check on the contract?


texts: Etherdelta error when calling withdraw, deposit or transfer

texts:
Everything I do with Etherdelta. I get an error. I really don't know where is it coming from.

It is pending the whole time.


texts: How can i do to interact with web3 on the server side?

texts:
I'm trying to develop a web application that interacts with web3.
I have to create accounts, wallet and perform transaction.
I'd like to know which is the best way to interact with web3 on the server side.


texts: Signing a message to sell NFT/token - what happens if you transfer the NFT later?

texts:
If you sign a message with intent to list an NFT/token for sale - how does that work if you transfer the item later?
For example on an NFT marketplace - you list your NFT for sale by signing a message. I'm assuming that signed message is a signed transaction to transfer the NFT to a contract that acts as a medium of exchange between buyer and seller.
But what if I sign that message - then transfer my NFT?

List NFT for sale
Site asks for Approval of NFT to be confirmed -
tx sent
Site asks for signature with listing details (price, etc)

I now exit site and send the NFT to my friend.
4. Someone fills that
listing for the NFT - but my NFT is gone
- how is the order filled?
Specifically I'm looking at a site like rarible - where that is the flow - they only get approval and thats it.
But I don't get how it works if you transfer that NFT?


texts: Truffle develop vs Ganache. Is there a reason to prefer one over the other?

texts:
Now that Ganache is usable, I don't see a reason to use truffle develop anymore.

Is there still a scenario where the latter is preferred?


texts: What is the difference between require() and return in an if() statement?

texts:
I am reading this page and trying to understand how these 2 pieces of code will behave:

With require()

function transfer(address _newOwner) public {
    require(msg.sender == owner)
    // Do the actual transfer
}

With return in an if():

function transfer(address _newOwner) public {
    if (msg.sender != owner) return;
    // Do the actual transfer
}

I understand that require() will revert all changes and refund me any unused gas, but what exactly does the second code will behave? The function will stop executing, but does it refund unused gas?

Thanks


texts: Confusion between MetaMask enabled and Disabled

texts:
I ran the truffle box react example with Metamask disabled and the stored value is correctly shown as 5.

simpleStorageInstance.set(5, {from: accounts[0]})

However when I enable the Metamask plugin in Chrome, the Metamask window appears asking for the transaction to be approved, before the SimpleStorage method set is called.

Question: Why was the transaction automatically approved/signed when Metamask is disabled, but not when Metamask is enabled?

My Guess: Is this because when Metamask is disabled, the web3 provider used is the one Truffle provided, and running truffle develop started a testrpc where all accounts are unlocked and thus require no approval for any transactions?


texts: Why is my view function running out of gas when reading from mapping/HashMap?

texts:
I have the following vyper code:
address_to_addresses: public(HashMap[address, address[2])

Vyper auto generates a view function called address_to_addresses(arg0: address, arg1: uint256) -> address that allows you to read the value of the public variable.
The abi for this function looks like this:
"name": "address_to_addresses",
"outputs": [
  {
    "type": "address",
    "name": ""
  }
],
"inputs": [
  {
    "type": "address",
    "name": "arg0"
  },
  {
    "type": "uint256",
    "name": "arg1"
  }
],
"stateMutability": "view",
"constant": true

But when I execute the following using ethersJS:
myContract.address_to_addresses(<someAddress>, 0)

I get a transaction revert error that says I have run out of gas:
Error: VM Exception while processing transaction: out of gas

How is it possible that I can be running out of gas when I am calling a view function? How can I call this function without "running out of gas"?


texts:
Sorry for vague question but just looking to get some insight. I have just began developing a dapp for the ethereum network and I need some advice on what development frameworks/technologies to use.
I am fine with the Solidity smart contract development however I am struggling with the front-end UI and contract interaction.
Is drizzle a necessity when using truffle?
Is react recommended or can I just use a node-js front-end and interact with web3-js.
Any advice would be great.
Thanks


texts: Accessing Contract Variables from JS Unit Tests

texts:
I am having trouble unit testing my contracts: I am using Mocha, Chai and calling truffle test

I am testing LoanRecord.sol

contract LoanRecord {
  public bool on;
  ...

  constructor(...){
    ...
    on = false;
   }

  function external turnOn(){
    on = true;
  }
}

And testing in record.test.js:

var assert = require('chai').assert
var LoanRecord = artifacts.require("../../contracts/record/LoanRecord.sol");

contract ('Record', function (accounts) {
    describe("#turnOn()", function () {
        it("should turn on a loan record instance", async function () {
            loanrecord = await LoanRecord.new(
                1,
                18,
                0x0000000000000000000000000000000000000002,
                0x0000000000000000000000000000000000000001,
                "LOAN"
                );
            await assert.equal(loanrecord.on, false)
            await loanrecord.turnOn()
            await assert.equal(loanrecord.on, true)
        });
    });

However, I am recieving:

1) Contract: Record
       #turnOn()
         should turn on a loan record instance:
     AssertionError: expected [Function] to equal false
      at Context.<anonymous> (test/record.js:15:26)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

Why does loanrecord.on return [Function] rather than a boolean type?

Fixed (with gitter@dwardu help too):

contract ('Record', function (accounts) {
    describe("#turnOn()", function () {
        it("should turn on a loan record instance", async function () {
            loanrecord = await LoanRecord.new(
                1,
                18,
                0x0000000000000000000000000000000000000002,
                0x0000000000000000000000000000000000000001,
                "LOAN"
                );
            var on = await loanrecord.on()
            await assert.equal(on, false)
            await loanrecord.turnOn()
            var on = await loanrecord.on()
            await assert.equal(on, true)
        });
    });
}


texts:
I have an ERC20 smart contract address
The total supply is 1,000,000,000,000
Now I want to increase the total supply
please help me
What code should I use in
https://remix.ethereum.org/


texts: Is their any change to move a wallet from an bnb blockchain to an ethereum blockchain?

texts:
I transferred some ethereum to my bnb wallet. Later I found out that this bnb wallet is not on the ethereum platform.
So I send an amount of ETH to an address similar to the address of the bnb wallet (but that bnb wallet is not the same wallet as the wallet I send the eth to).
Info of the wallet I send my eth to:
https://etherscan.io/address/0x7C7ffb0d9a3cB52265b2224b1358b56916A6e199
info of the bnb wallet:
https://bscscan.com/address/0x7C7ffb0d9a3cB52265b2224b1358b56916A6e199
you see that the address of both wallets are identical.. but they are not the same!
if someone can explain how this, or if someone might know if I will ever see my eth back u will be rewarded! :)
kind regards,
Dennis Franke


texts:
Initially, the regular sync would not download the last 200+/- blocks or so. I was told to switch to light sync where it finished. I then read that to start mining real ether on the main network, I need to use geth here:

  I don't see "Start Mining" option?

mist geth

After typing the command abolve into the terminal, I got the following:

My issue is, how do I know if I am mining ether or not? Or is there another step I am missing?


texts: why is sendTransaction is taking too much gas?

texts:
I have a contract such

contract tokenEvents
{
    event globalEvent(address contractAddress, string eventName, uint value);
    event globalEvent2(address contractAddress, string eventName, uint value, address senderAddress);

    function callEvent(string eventName, uint value)
    {
        globalEvent(msg.sender, eventName, value);
    }

    function callEvent2(string eventName, uint value, address senderAddress)
    {
        globalEvent2(msg.sender, eventName, value, senderAddress);
    }

}

Another contract is used to above contract such

function(){
    uint amount = msg.value;
    amountRaised += amount;
    tokenEvents te = tokenEvents(0x5488845db957f6fd3691b0c2959b607dc52f09b2);
    uint nValue;
    address senderAddress;

    if (msg.sender == partyone){
        if (contribution[partyone] == 0)
        {
            contribution[partyone] = amount;
        }
        else
        {
            contribution[partyone] += amount;
        }

        eventName = "party1_contribution";
        nValue = contribution[partyone];
        senderAddress = partyone;

    }
    else if (msg.sender != beneficiary) {
        partytwo = msg.sender;
        if (contribution[partytwo] == 0){
            contribution[partytwo] = amount;
        } else {
            contribution[partytwo] += amount;
        }

        eventName = "party2_contribution";
        nValue = contribution[partytwo];
        senderAddress = partytwo;
    }
    else {
        if (contribution[msg.sender] == 0){
            contribution[msg.sender] = amount;
        } else {
            contribution[msg.sender] += amount;
        }

        eventName = "other_contribution";
        nValue = contribution[msg.sender];
        senderAddress = msg.sender;
    }

    te.callEvent2(eventName, nValue, senderAddress);
}

Now whenever I send ether some ether to this contract its taking too much gas. For example: 20000

What is the issue?


texts:
I am writing a fairly simple smartcontract unising flash swap:
function uniswapV2Call(
    address _sender,
    uint _amount0,
    uint _amount1,
    bytes calldata _data
) external {
    address[] memory path = new address[](2);
    uint amountToken = _amount0 == 0 ? _amount1 : _amount0;

    address sender = _sender;

    address token0 = IUniswapV2Pair(msg.sender).token0();
    address token1 = IUniswapV2Pair(msg.sender).token1();

    require(
        msg.sender == UniswapV2Library.pairFor(dex1FactoryAddress, token0, token1),
        'Unauthorized'
    );

    require(_amount0 == 0 || _amount1 == 0);

    path[0] = _amount0 == 0 ? token1 : token0;
    path[1] = _amount0 == 0 ? token0 : token1;

    IERC20 token = IERC20(_amount0 == 0 ? token1 : token0);
    IERC20 otherToken = IERC20(_amount0 == 0 ? token0 : token1);

    token.approve(address(sushiRouter), amountToken);

    uint amountRequired = UniswapV2Library.getAmountsIn(
        dex1FactoryAddress,
        amountToken,
        path
    )[0];

    uint amountReceived = sushiRouter.swapExactTokensForTokens(
        amountToken,
        amountRequired,
        path,
        sender,
        deadline
    )[1];

    assert(otherToken.transfer(msg.sender, amountRequired));
    assert(otherToken.transfer(tx.origin, amountReceived - amountRequired));
}

I always have UniswapV2 K. I have read the doc, but I have no clue what is the issue.
Any Help?


texts: ER721Token contract functions all working in remix, but not in geth --dev console with web3 commands?

texts:
I'm using the following contract with all the dependencies.

MasteringEthereum/code/auction_dapp/backend/contracts/ERC721/ERC721Token.sol

When deployed in remix the contract functions work fine, all of them execute and the data is stored in the correct places (i.e arrays and mappings) Although when I deploy to a local geth --dev console the following functions execute but the state of the contract does not change

erc721token.mint(acct1, 9000 {from: acct1})

erc721token.totalSupply()

erc721token.tokenByIndex([0])

erc721token.balanceOf(acct1)

erc721token.exists(9000)

erc721token.ownerOf(9000)

???

Any help would be fantastic.


texts: How does a transaction verified with Truffle test?

texts:
I'm a new to Ethereum and Solidity, and I don't understand how Truffle executes transaction calls.

From what I learned and understood, if I try to use a contract method which changes the contract's state(changes any values), this means I(sender) have to make a transaction to that contract. In this way, I need my account's data, such as private key, or this stuffs are done by Metamask.

But I don't see any signing or verification process in the test code provided by Truffle docs. In it block, just execute any contract's method, and we can see the changes.

Does this mean Truffle internally addresses the verification stuff, as this is test environment provided by itself? I don't get how Truffle test handle transactions. Can somebody explain what is going on inside the box? Or maybe I'm missing some of the concepts.

Thank you for advance for your explanations.


texts: ERC20 tokens transactions' history from Ethereum node

texts:
I have a parity node. I developed a web3.js interface on top of it.

I have APIs whose job is to fetch addresses' balances and transactions.

Example response of transaction API:

{ tx_hash: '0xc4a2db4211686f740885ad72ef5d424f5ba6d953d583ef39382e7c1c594ecab7',
  nonce: 0,
  block_hash: '0xf2b173625cf874387302295f408ef0876c04e5778e6ccacec63fe28ff268f9a3',
  block_number: 5955478,
  transaction_index: 184,
  from: '0xAcc7662daDfCE9dA2C0d8ef7867C15A262c762D7',
  to: '0x3495Ffcee09012AB7D827abF3E3b3ae428a38443',
  value: '0',
  time: '1531467099 Fri, 13 Jul 2018 07:31:39 GMT',
  gas_price: '5000000000',
  gas: 37351,
  input: '0xa9059cbb000000000000000000000000c5c813994f9142d11d73b47e1437c81e27b4dae3000000000000000000000000000000000000000000000000b469471f80140000' }

value key is for ether/wei transfers only.

For ERC20 tokens:

I fetch the to address and compare it to a list of supported erc20
contract addresses.
If there is a match, the transaction call was to erc20 contract and it wrote to the blockchain (contract.send())
At this point I am lost. How to figure out which function of ERC20 standard contract was called?
How to fetch how many tokens were transferred and to which address in this call?

Thanks for reading my query. Any help would be really great. You are free to use the linked git project.

UPDATE

If we use getPastEvents function of web3.js and fetch all events, then a matching can be done against all transactions and I can figure out somehow how many tokens were delivered and when.

But this will be a complicated flow, and will be done per contract basis. Anything that can avoid calling events and figure out the details of the erc20 transactions? what if the contract didn't call any event?


texts: How to store private data on blockchain to be readable from a contract?

texts:
I'm writting DApp on Ethereum (Solidity) and I need to find a solution how to store a private data on blockchain, when I also need to proceed them somehow. If it is only about storing, I can use some normal encrypting, but the problem is that I need to read the data IN the smart contract and proceed it somehow too.

Let's say:

1) I want to send some private number to a blockchain.

2) I need to check if the privete number is bigger than the last stored private number and smaller than the second last stored number.

if (storage[n] < y < storage[n-1]) storage.push(y);

3) If yes, I want to store it privately.

Any ideas? Thank you.


texts: truffle console - invoking contract function usage (Version 3)

texts:
I have a simple contract like below. I was able to successfully compile and migrate the same.

pragma solidity ^0.4.8;

contract A {

    function A() payable {
    }

    function getBal() returns(uint a){
        return (10);
    }

}

Now I am using truffle console and trying to invoke getBal() function of my contract.

A.deployed().then(function(instance) { test = instance; return test.getBal();}).then(function(result){});

I am not getting the new version 3 way of calling the functions.

Could you help me out and point what I am missing?


texts:
I have a private testnet set up on my local machine:

geth --rpc --rpcaddr "localhost" --rpcport "8545" --dev --mine --datadir="~/Library/Ethereum_dev" --rpccorsdomain="http://localhost" console 2>>geth.log

It's working great.

However, I'm on a MacBook Pro 2010 which is 5.5 years old now. Geth is eating one of my CPUs and I only have two.

I tried to use nice to suppress CPU usage:

nice -n 19 geth --rpc --rpcaddr "localhost" --rpcport "8545" --dev --mine --datadir="~/Library/Ethereum_dev" --rpccorsdomain="http://localhost" console 2>>geth.log

But I'm still using way too much for my liking. Does anyone have any ideas?


texts: Gas estimation for mapping updating with web3js

texts:
The gas estimation for contract deploying with web3js will look like:

var res = web3.eth.estimateGas({
    from: web3.eth.defaultAccount,
    data: contractByteCode
});

For example, I have the simple mapping mapping(string => string) and updateMapping function to set mapping key/value pair in contract.
I want to update it:

var contract = web3.eth.contract(contractABI).at(contractAddress);
contract.updateMapping.sendTransaction(
   foo, bar,
   {gas: estimatedGas, from: web3.eth.defaultAccount},
   function(err, result) {
});

How to estimate gas for such transaction with web3js?


texts: Theoretical question: running a huge function with many iterations

texts:
I am still pretty new to Ethereum and smart contract but for a couple of last weeks I have been developing a smart contract for a gambling website project (studying purposes).

In the smart contract I have a function (called by the manager of smart contract) that group up all winners of a jackpot, returns to them what they bet, and then also draw random prices. So for every person who entered the jackpot, there is one iteration of a big function (drawing prices, returning initial bet).

I learned the hard way that if let's say 1000 people enter the jackpot and I call the function to reward all winners it consumes more than 6 milion gas.

How do people get around this? I would be even willing to pay considerable amount of money for running this function if so many people enter (because I can charge fees and use them to pay for this) but then there is block gas limit and there is no way I can even run this function to the end at all.


texts: Geth command line - load JavaScript file on startup with console

texts:
MISSION: Start a Geth node with a console while loading JavaScript function libraries at the same time
I need to load function libraries at startup, without having to call loadScript() on the Geth console every time the node fires up.  I  tried the js command, to no avail (loads console, but no script).

CONSOLE AND NO SCRIPT
geth --nousb --datadir ~/eth-me/ --networkid 319 --verbosity 1 --port 30303 console 2> /dev/null js "/eth-me/function/lib_acc.js"

When calling a function CheckAllBalances(), for example:

> checkAllBalances()

ReferenceError: checkAllBalances is not defined
at :1:17(2)

NO CONSOLE, NO GETH
geth --nousb --datadir ~/eth-me/ --networkid 319 --verbosity 5 --port 30303 js "/eth-me/function/lib_acc.js" console 2>> /eth

How do I load a JavaScript file when starting a node (with console) using command line Geth?


texts: How to download the whole transfer records of a token

texts:
I want download the whole transfer records of a token. https://etherscan.io/token/0xB8c77482e45F1F44dE1745F52C74426C631bDD52?a=0xd551234ae421e3bcba99a0da6d736074f22192ff.
But the default setting is 2000. It means you can only export the earliest 2000 records starting from some date time. What can I do if the records more then 2000?
https://etherscan.io/exportData?type=tokentxns&contract=0xB8c77482e45F1F44dE1745F52C74426C631bDD52&a=0xd551234ae421e3bcba99a0da6d736074f22192ff&decimal=18


texts: Geth's fast syncing cannot get past block 4179789

texts: I have been syncing my node using "geth console --fast" but it has been stuck at block 4179789 for a long time. It keeps importing new state entries. What's the problem here?


texts: Send raw transaction from geth when not synced (exceeds block gas limit)

texts:
I have a geth node which is not synced and I want to send eth.
> TX={ from: FROM, to: TO, value: VALUE, nonce: NONCE, gas: GAS, gasPrice: GP }
> personal.unlockAccount(...)
> SIGNED_TX=eth.signTransaction(TX)
> RAW=SIGNED_TX.raw
> eth.sendRawTransaction(RAW)
Error: exceeds block gas limit
        at web3.js:6347:37(47)
        at web3.js:5081:62(37)
        at <eval>:1:23(4)

In the past I have managed to submit RAW to an ethereum broadcast web page such as https://etherscan.io/pushTx but sometimes that works and sometimes I get an error like
Error! Unable To Broadcast Txn : {"id":"1","jsonrpc":"2.0","error":"One or more errors occurred."}

This isn't enough information for me to fix anything. I would like to do it direct from geth but since I am not synced I'm getting the block gas limit error.
How can I tell geth to submit the raw transaction to the network regardless of the block gas limit?


texts: How to write a mock method for getting ether balance using Web3j Api. I am trying to mock Web3j and callig EthGetBalance method but I am getting Null

texts:
public static BigInteger OriginalMethod(){

// connect to node
Web3j web3 = Web3j.build(new HttpService());  // defaults to
http://localhost:8545/

// send asynchronous requests to get balance
EthGetBalance ethGetBalance = web3
.ethGetBalance("0xAccountAddress", DefaultBlockParameterName.LATEST)
.sendAsync()
.get();

BigInteger wei = ethGetBalance.getBalance();
}

public static BigInteger MockOriginalMethod(){
web3j=Mockito.mock(Web3j.class);//Mock web3j class
        BigInteger bigValue=Mockito.mock(BigInteger.class);
        Mockito.when(web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).sendAsync()
                .get().getBalance()).thenReturn(bigValue);
return bigValue.valueOf(11);
}


texts:
I wrote what I thought was a dead simple contract - a saving jar... you add value ("save") into the jar and when the balance of the contract reaches a certain amount ("target"), then I am able to withdraw the value.
But whenever I try to send it value, it errors with "Bad Jump Destination"

Here is my contract:

pragma solidity ^0.4.0;

contract jar {
  uint public target;
  uint public numDonations;

  function jar (uint _target) {
    target = _target;
    numDonations = 0;
  }

  function save() {
    numDonations++;
  }

  function getBalance() constant returns (uint) {
    return this.balance;
  }

  function withdraw () {
     if (this.balance < target) throw;
     if (!msg.sender.send(this.balance)) throw;
  }
}

And here is the save command I am sending:

jar.save({from:eth.accounts[0], value: 100000000000000000, gas:3000000})

Here is an example of a failed transaction:

https://testnet.etherscan.io/tx/0xcf93aa967f6d1d42b84147511ab58a66a468ee8a102a8d78f78f071ec1a30a05

I have never seen this error before and I am totally stumped. Any pointers would be greatly appreciated.


texts:
I have create a very basic ERC1155 token from this tutorial:

https://docs.openzeppelin.com/contracts/3.x/erc1155

// contracts/GameItems.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SILVER = 1;
    uint256 public constant THORS_HAMMER = 2;
    uint256 public constant SWORD = 3;
    uint256 public constant SHIELD = 4;

    constructor() public ERC1155("https://game.example/api/item/{id}.json") {
        _mint(msg.sender, GOLD, 10**18, "");
        _mint(msg.sender, SILVER, 10**27, "");
        _mint(msg.sender, THORS_HAMMER, 1, "");
        _mint(msg.sender, SWORD, 10**9, "");
        _mint(msg.sender, SHIELD, 10**9, "");
    }
}

As you can see, 5 tokens are created when the contract is deployed.
Each of this 5 token is associated to a metadata file:
https://game.example/api/item/0000.....0001.json
https://game.example/api/item/0000.....0002.json
https://game.example/api/item/0000.....0003.json
https://game.example/api/item/0000.....0004.json
https://game.example/api/item/0000.....0005.json

I want to customize this 5 urls. They need to be very different.
Is it possible ?
I can override ERC1155 functions but i want to be compliant to ERC1155 in order to keep my token compatible with market places.
Thanks


texts: Can I send ethereum to a contract outside of its constructor?

texts:
How do I fund Solidity contracts with Ether? The example in the Solidity FAQ, http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html#store-ether-in-a-contract, funds a contract via the contract's constructor. Can you do the same outside of the constructor?

Some background; I want a contract to be able to send Ether to someone's address via something like recipient.send(169000000000000000000);

Anyway, here's the output from my geth console:

>eth.getBalance(eth.coinbase)
169531250000000000000

So I have ~169 Ether to play with. Great! So I tried this:

contract A {
    function fund() public {
        Funded(msg.sender,msg.value);
    }
}

Which I then wanted to fund with the following .js call:

const exchangerContract = web3.eth.contract(exchangerAbi)
const contractAddress = '0x0d2bbe5af1fa1eaebc5ad6e27aa27a7328dc58bc'
const contract = exchangerContract.at(contractAddress)
contract.fund({from: web3.eth.accounts[0], value: web3.toWei(100,"ether")})

Unfortunately, that doesn't seem to work; I get the following when I load up the console:

>eth.getBalance('0x0d2bbe5af1fa1eaebc5ad6e27aa27a7328dc58bc')
0

So, wondering if my .js was faulty, I tried the same in the console:

>eth.sendTransaction({from: eth.coinbase, to: '0x0d2bbe5af1fa1eaebc5ad6e27aa27a7328dc58bc', value: web3.toWei(100, "ether")})
"0x136ae6919bd2640425b03633b6709c3863d96600da6ca0c61956f694bbe62384"
>eth.getBalance('0x0d2bbe5af1fa1eaebc5ad6e27aa27a7328dc58bc')
0

Boo :( So then I wondered if it was possible to send Ether at all! But:

>personal.newAccount()
Passphrase:
Repeat passphrase:
"0x5e610b6696683e1c4173bd949279fd6127d8b808"
> eth.getBalance(eth.coinbase)
169531250000000000000
> eth.getBalance(eth.accounts[1])
0
> eth.sendTransaction({from: eth.coinbase, to: eth.accounts[1], value: web3.toWei(169, "ether")})
"0x136ae6919bd2640425b03633b6709c3863d96600da6ca0c61956f694bbe62384"
> eth.getBalance(eth.accounts[1])
169000000000000000000

So it seems I can send Ether to a non-contract address, after all. Phew!

How do I do the same to contract addresses?


texts: Solidity is installed but is not working within geth, on Ubuntu 16.04

texts:
Geth console outputs after admin.setSolc("/usr/bin/solc"):

eth.compile.solidity("")
I0601 15:31:56.663260 common/compiler/solidity.go:114] solc, the solidity compiler commandline interface
Version: 0.3.3-0/RelWithDebInfo-Linux/g++/Interpreter
path: /usr/bin/solc
solc: empty source string
at web3.js:3119:20
at web3.js:6023:15
at web3.js:4995:36
at :1:1

and

eth.getCompilers()
[]

I am getting an empty array instead of ['Solidity'].

Installed solidity through: sudo apt-get install solc

output for which solc: /usr/bin/solc (added this to PATH)

I have seen a similar question, but I am using the latest version (0.3.3) and still have the problem. Am I missing anything?


texts: Unable to mine smart contract using Oraclize - Invalid JSON RPC response,error code : -32603

texts:
I am trying to use Oraclize to make a REST call. Please find below my contract code -

pragma solidity ^0.4.16;
import "./usingOraclize.sol";  //Importing Oraclize(verion 0.4)
contract TestOraclizeCall is usingOraclize {
     uint public price;
     event Log(string text);
     event LogOracleConnection(OraclizeAddrResolverI obj);
     OraclizeAddrResolverI OAR;

 //Constructor
 function TestOraclizeCall() {
     OAR = OraclizeAddrResolverI(0x6f485c8bf6fc43ea212e93bbf8ce046c7f1cb475);   // address of the resolver
     emit LogOracleConnection(OAR);
    // update();
 }

 function checkOARInstance() public view returns(address){
     OAR.getAddress();//returns no address
 }
 function __callback(bytes32 _myid, string _result) public {
      if (msg.sender != oraclize_cbAddress()) revert();
      emit Log(_result);
      //price = parseInt(_result, 2);
   }
 function update()public{
    oraclize_query("URL","json(http://**/storage/compartments/list?next_page=).Data");
 }
 }

However when I try to execute the update() method the call to mining process fails :

  Invalid JSON RPC response,error code : -32603.

The ethereum bridge has been successfully deployed on a private blockchain and both address resolver and connector contracts have deployed and generated the contract address, but still I am not able to execute any oraclize methods.

Blockchain running on Ubuntu machine.

Request any help on this issue.
Thanks.


texts:
I'm trying to understand how to sign a message in Java and recover the public key in a Solidity smart contract however my public keys don't seem to match.
Here's my Java code to generate the signature:
    String testString = "testing signature method";
    Sign.SignatureData signatureData = Sign.signMessage(testString.getBytes(), credentials.getEcKeyPair());

    System.out.println(Numeric.toHexString(credentials.getAddress().getBytes()));
    System.out.println(Numeric.toHexString(testString.getBytes()));
    System.out.println("R: "+Numeric.toHexString(signatureData.getR()));
    System.out.println("S: "+Numeric.toHexString(signatureData.getS()));
    System.out.println("V: "+signatureData.getV());

And here's my smart contract verify function:
function verify(bytes32 testStringBytes, uint8 v, bytes32 r, bytes32 s) constant returns (address) {

bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedValue = keccak256(prefix, testStringBytes);
return ecrecover(prefixedValue , v, r, s);
}

The output I get for the verify function is
0x60009F80EA2D060fd804285d8a8a649351521582

However my java program is outputting the address as
0x307838336530386135653737393031313236613136373231353930613865313337396662376231623662

Anyone see where I'm going wrong?
The values I'm plugging into Ecrecover:
R: 0x524d3f28b7aad7418d9b9e30615e26104925b5fbaaf868a87bcf1b0b42172ec2
S: 0x07014e250540ce8e6dffb45e8c90e34ad5a31a3bbe5bb9a958ae7fdbee4f2048
V: 28


texts:
I have a private ethereum system with a couple of nodes. I'm trying to deploy a contract on one of them.
To begin with, I am trying to just deploy a sample contract from the net. This is what I'm using:

pragma solidity ^0.4.24;
contract sample {
 string public name = "ZeonLab";
 function set(string _name) {
    name = _name;
 }

 function get() constant returns (string) {
   return name;
 }
}

I compile this with the solc compiler and get the ABI and bytecode by running solc --abi and solc --bin respectively. I then try to deploy the contract on geth as follows:
geth console

> var test = eth.contract('abi text above')

It however gives me an undefined error. in fact, instead of the ABI text from above, if I just do: var test = eth.contract('test'), I still see an error.

I read somewhere that we need to do: var testTxt = JSON.parse('abi text above')
However, that did not work either.

From the error, it looks like there may be an issue with recognizing eth.contract itself. When I type eth on the console, I see that contract is one of the options.

Any suggestions on what could b wrong.

thx - anand


texts:
The web3.js is the most easiest and perhaps the standard way of dapp creation.And there are two providers possible as of now , HttpProvider and IPCProvider. The HttpProvider takes the address at which the server is running, it can be something like

             var Web3 = require('web3');
             var web3 = new Web3();
             web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
                                               // or it can be http://m.n.k.l:8545

My question is if the server hosting/node , has went down how can the client be able to access it. In cases like this the entire dapp is down. Then what is the point of calling it dapp ?

Is my understanding correct about having a single server as provider ?

Not all dapp creators host their own server / a node running in rpc.In such cases,  how would the creator would know any node address ?


texts: Payable and address.transfer for ERC20 token

texts:
I am trying to develop forsage like MLM using ethereum smart contract. But I like to use ERC20 token for registration payment and dividends. The ERC20 token is already deployed. I have to use deployed ERC20 token in MLM smart contract for registration payment and dividends. If we are using ether instead of token, we can use payable for registration payment and address.transfer method for sending dividends. How to do the same for ERC20.
For example in case of ether, the registration payment will be like,
function registration(address referrerAddress) private {
    require(msg.value == 0.05 ether, "registration cost 0.05");
}

Suppose I am expecting 5 token as registration fee, how to write this logic.
We can send ether to receiver like,
receiverAddress.send(levelPrice)

How to do the same in case of ERC20 token.


texts: ReferenceError: cannot access 'CONTRACT' before initialization

texts:
I'm trying to test a single smart contract (PCE_Contract.sol) with (PCE_Contract_test.js) using Truffle. When I run Truffle test, console output is :
ReferenceError: Cannot access 'PCE_Contract' before initialization
PCE_Contract_test.js:
const PCE_Contract = artifacts.require("./PCE_Contract");

contract('PCE_Contract', () => {

it('should deploy SC properly', async() => {

  const PCE_Contract = await PCE_Contract.deployed();

  console.log(PCE_Contract.address);

  assert(PCE_Contract !== '');

});

});

PCE_Contract.sol:
pragma solidity ^0.7.0;

contract PCE_Contract {

  uint256 public LOCK_PERIOD  = 365 days;
  address public investor;

  mapping(address => Deposit) deposits;

  constructor(){

  investor = msg.sender;
  }

  struct Deposit {
      uint256 value;
      uint256 releaseTime;
  }

  function investment() public payable {
       require(msg.value > 0,
         "You must make a non-zero deposit.");

       if (deposits[investor].releaseTime == 0) {
           uint256 releaseTime = block.timestamp + LOCK_PERIOD;
           deposits[investor] = Deposit(msg.value, releaseTime);

       } else {
           deposits[investor].value += msg.value;
       }
   }

   function withdraw() public {

    require(deposits[investor].value > 0,
      "You have no deposits available.");

    require(deposits[msg.sender].releaseTime < block.timestamp,
      "Your lock period has not ended yet.");

    msg.sender.transfer(deposits[investor].value);

    deposits[msg.sender].value = 0;
    deposits[msg.sender].releaseTime = 0;
}

function getDeposit(address holder) public view
  returns (uint256 value, uint256 releaseTime)

  {
        return(deposits[holder].value, deposits[holder].releaseTime);
    }

}

Truffle v5.1.49 (core: 5.1.49)
Solidity - ^0.7.0 (solc-js)
Node v12.18.4
Web3.js v1.2.1
Any help is appreciated !


texts: What does total number of blocks per day mean in Etherscan?

texts:
I tried to figure out what does total number of blocks per day means here and on the Internet, but i failed. For example, the number of blocks on 26 Aug is 5947 [here https://etherscan.io/chart/blocks]. My question is whether this number includes main blocks (that made it to the main ethereum blockchain) + uncle and stale blocks? or just the main blocks?

I made some calculations e.g., if 5947 is only main blocks, uncles is 1044 [here https://etherscan.io/chart/uncles], which result in 6991 blocks produced on 26 Aug. This contradict with average block time, which is 14.21 s [here https://etherscan.io/chart/blocktime] as the number of blocks per day should be 86400/14.21= 6080 blocks.

If 5947 includes uncles and stales, this is close to the expected 6080 blocks, but still there is a difference as the average block time should be 86400/5947= 14.53 seconds.

hence 1 day = 86400 seconds


texts: Get contract data if all I have is a contract address

texts:
I have the address of a smart contract and I need to get the data residing in that address. I seem to have been struck at this for a while now and I want all this inside a smart contract.

pragma solidity ^0.4.8;

contract myContract
{
    address[] public childContracts;

    function newContracts(uint _id,string _name) public returns(address _newContract)
    {
        uint id=_id;
        string memory name=_name;
        anotherContract a = new anotherContract(id,name);
        childContracts.push(a);
        return a;
    }
}

contract anotherContract
{
    string name;
    uint id;
    constructor(uint _id,string _name)
    {
        name=_name;
        id=_id;
    }
}

So I want to get the id and name in my instance Contracts when all I have is the address of that contract.

Can someone help me?


texts: How do I define mapping in solidity where each value is array of Struct?

texts:
I'm trying to define a mapping, where each value should be an array of struct. Not sure, if this is possible? If yes then what wrong I'm doing here?

After defining, I also need to push values to the array as shown below. Please advise if it is correct.

struct Review {
    uint rating;
    address reviewer;
    string description;
    uint dateAdded;
}

mapping (uint => Review[]) public ratings;

function rateBook(uint id, uint rating, string comments) onlyMember {
    if (id > numBooks || rating < 1 || rating > 5) {
        throw;
    }

    ratings[id].push(Review({
        rating: rating,
        reviewer: msg.sender,
        description: comments,
        dateAdded: now
        }));
}


texts: Random distribution of large amount of NFT

texts:
I'm an beginner in solidity, and with a teamate we have a project for an NFT contract.
I have a contract with 5000 NFT limite (cards, and 20 specific card form a familily, each family and cards are unique). All this NFT card are unique by their number of index.
The goal of the game its to assemble a familily of card (example : card number 1 to 25 form the famili RED) for win a prize.
So, in the start of the game, we need to distrib this card randomly. In my function "claimCard", a "random number" is calculate, and the number's index of the cards is attribute to the owner address.
I Have :
 function claimCard(uint _cardIndex) public payable returns(uint){

 _cardIndex = 5000;
 randNonce++;

cardIndexToAddress[uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _cardIndex] = msg.sender;

 return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _cardIndex;

Problem : in case with the "random number" is a card that already owned, how can I manage my function for re start and find a new random number for a card not already owned ?

I can take a loop (if address card is != 0x0, loop) but this solution can cost a big amount of gas
50% of card claim => 2loop
33% of card claim => 3loop
10% of card claim => 10loop
4% of card claim => 25loop
1% of card claim => 100loop

I can create an array with 5000 index, like arrayCard(1, 2, 3... 5000) and with a random number modulo lengh.array, take the number and remove the element in the array, so the array become with 5000 element - 1...
But the cost of an array of 5000 element its too expensive...

Have u got some issue for me ? :)
Thanx you and have a nice day !


texts:
I am deciding whether to start a full node, so I researched the storage size I need for hosting it.
https://etherscan.io/chartsync/chaindefault shows the size of an Ethereum full node on Geth and on OpenEthereum. I can't understand why a Geth node takes up 633 GB and an OpenEthereum node only 371 GB. Why is there such a big gap from the two. Am I missing something?


texts: Need to help in adding bigendian support for Keccak256.cpp

texts: Need help in making the keccakf function based on endiness in https://github.com/ethereum/solidity/blob/develop/libdevcore/Keccak256.cpp. I have gone through similar functionality at https://github.com/stbrumme/hash-library/blob/master/keccak.cpp. but unable to re write keccakf function in Keccak256.cpp. Any help on this would be very helpfull


texts:
I have the following contract that uses Oraclize:

contract Test is usingOraclize {

bytes32 public query;

mapping (bytes32=> address) senderAddress;

address public resultAddress;

function sendQuery() public payable {

  string memory queryString = "some query stringified JSON..."
  bytes32 queryId = oraclize_query("nested", queryString, 235000);

  senderAddress[queryId] = msg.sender;
  query = queryId
}

function __callback(bytes32 myid, string result, bytes proof) {

  resultAddress = senderAddress[myid];

}

}

Now, this works just fine in terms of sending a query and getting a result. However, when I get the resultAddress state variable, it is equal to 0x0 instead of showing the mapped query msg.sender address. Furthermore, if I create a global variable for myid and then store the value in it, it is different from the queryId. I suppose the issue is that since myid and queryId are different, the needed address is not found in the mapping.

What am I missing here?

UPD: It looks like everything is working fine in testnets, and the issue is in JavaScriptVM of the Remix browser. I wonder if there's a way to fix this...


texts: How to encode tuple as input parameter to function using web3j

texts:
I am attempting to call a solidity function that looks something like the following:

function fillOrder(
    Order memory order,
    uint256 takerAssetFillAmount,
    bytes memory signature
)

Using web3j I would create the function similar to below, however I'm not quite sure how to represent the order which is represented as a struct in Solidity.

List<Type> inputParams = Arrays.asList(
    ???,
    new Uint256(takerAssetFillAmount),
    new Bytes32(signture)
);

new Function("fillOrder", inputParams, Collections.emptyList());

Any pointers on how I should represent the struct? From what I can tell web3j doesn't have support yet for ABIEncoderV2?

Thanks.


texts: running contracts on freshly created accounts. how to pay the gas?

texts:
for my scenario i have an application that doesn't require any knowledge about Ethereum, contracts and wallets from the enduser.

my software handles everything. creates an account for the enduser etc.

now i wish to run a contract on said newly created account. but this seems like a nightmare because the newly created accounts have no GAS so they can't run anything.

what would be the best practice?

have a contract where an admin-account runs everything and pays all the GAS.
or pay the new accounts some money so they can spend their own GAS?

i don't expect the fresh accounts to run a lot of contract transactions. (consume a lot of GAS) in average maybe 1-20 runs in their lifetime.


texts: Sending a transaction via web3.js is not working

texts:
I'm trying to send some ether and here is my code:

function sendEth(fromAddress, secret, toAddress, amount) {
  let params = {
    to: toAddress,
    from: fromAddress,
    value: web3.utils.toWei(amount + '', 'ether'),
    nonce: (new Date).getTime()
  };
  console.log(params);

  return Promise.all([web3.eth.estimateGas(params), web3.eth.getGasPrice()])
    .then((response) => {
      console.log(response);
      const estimatedGas = response[0];
      const gasPrice = response[1];
      params.gas = web3.utils.toHex(estimatedGas);
      params.gasPrice = web3.utils.toHex(gasPrice * 2); // Use 10% more gas than recommended
      params.value = params.value - (params.gasPrice * params.gas);
      // params.value = web3.utils.toWei(params.value - params.gas * params.gasPrice + '');
      // delete params.value;
      console.log(params);

      return web3.eth.accounts.signTransaction(params, secret);
    })
    .then((signedTx) => {
      console.log(signedTx);
      return web3.eth.sendSignedTransaction(signedTx.rawTransaction);
    })
    .then((response) => {
      console.log('response', response);
    })
    .catch((err) => {
      console.log('err', err);
    });
}

The signed transaction looks like:

{ messageHash: '0x0f974cbc64a581b4edb0bbd01d6c13f90bc632a5f91e8c15e938b13a5cbdf904',
  v: '0x2a',
  r: '0x957739758fcbe96c0f2fed2b69b486c99cacd6b3f338714c419fdcefa6074d19',
  s: '0x26030359b1bd16317ea6dab9d4da61fc77b7963fc22dc8072663747104a30dea',
  rawTransaction: '0xf87086016446eca4108306b6c2825208941608ff60df6884ad57dbedb6ebc41aebee4485d2880163457636ca25f0802aa0957739758fcbe96c0f2fed2b69b486c99cacd6b3f338714c419fdcefa6074d19a026030359b1bd16317ea6dab9d4da61fc77b7963fc22dc8072663747104a30dea' }

And it never actually hits the blockchain (I'm on ropsten). If I use https://ropsten.etherscan.io/pushTx to push the rawTransaction, it appears to succeed. But the transaction stays pending: https://ropsten.etherscan.io/tx/0x5ec8371471aa3159ea12e52fbcde552bd1cbf1a30534f6b44a3de983289a94df

What am I doing wrong?


texts: What does it mean Ethereum Swarm account?

texts:
ETH wallet is something like

0xd0a6e6c54dbc68db5db3a091b171a77407ff7ccf

I read Swarm docs and see

in our example swarm --bzzaccount 2f1cd699b0bf461dcfbf0098ad8f5587b038f0f1
(You should replace
2f1cd699b0bf461dcfbf0098ad8f5587b038f0f1 with your address).

I don't understand:

why swarm account format is different then ETH wallet format?

why i need swarm account after I'll upload data? I need this account to edit data?

does swarm has is own payment protocol?

how can I integrate/associate my own ETH wallet with my swarm account?


texts: etherwallet-3.4.1/ on private chain setup - having 404 error

texts:
I am following the MyEtherWallet: Use Your Own Server Guide to use MyEtherWallet on my private ethereum network. I am doing this setup on my node, where my ethereum node runs.

I have done first 4 steps.

In response.js file: I have set host as:

host: '127.0.0.1'

In runLocalServer.js file: I have set app.use as:

app.use(vhost('127.0.0.1', require('./index.js').app));

Since port 80 is occupied, I have changed port number 80 to my free port number as 8000;

httpServer.listen(80); in runLocalServer.js.
httpServer.listen(80); in runServer.js

As recommended on Step-2 I run:

[~]$ node runLocalServer.js
//waits

But on Step-3, when I navigate to http://localhost/api.mew inside my node, I do have 404 or timeout errors. I was not able to end up on a empty/white page.

I was not able to figure out how to overcome this problem or where I am doing something wrong/missing. Any valuable guidance will be appreciated.

Thank you for your valuable time and help.


texts: CRUD storage pattern Infinite gas error when trying to implement in Remix

texts:
I'm trying to implement @robhitchens CRUD storage pattern in solidity, and I'm getting infinate gas costs when I import the library. Not sure where to go from here.

one of them:

Gas requirement of function HitchensUnorderedKeySet.exists(bytes32) high: infinite.
If the gas requirement of a function is higher than the block gas limit, it cannot be executed.

pragma solidity ^0.5.1;

import "https://github.com/rob-Hitchens/UnorderedKeySet/blob/master/contracts/HitchensUnorderedKeySet.sol";

contract Filter {

    using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
    HitchensUnorderedKeySetLib.Set filterSet;

    struct FilterStruct {
        string name;
        string tag;
    }

    mapping(bytes32 => FilterStruct) public filters;

    event LogNewFilter(address sender, bytes32 key, string Filternamename);

    function newFilter(bytes32 key, string memory name) public {
        filterSet.insert(key);
        FilterStruct storage f = filters[key];
        f.name = name;

        emit LogNewFilter(msg.sender, key, name);
    }

}


texts: Geth unable to broadcast pending transactions

texts:
Been having issues since the last 2 or 3 days. Unable to get pendingTransactions mined despite Geth getting caught up to the latest block and having 25 connected peers.

The transactions were created from Mist and/or Ethereum Wallet. I can see them at eth.pendingTransactions, but can never get them to be mined.

Cleared pending tx by restart Geth, it would come back again after awhile, probably stuck in mempool somewhere, but never mined.

Anything I can do about it?


texts:
I was wondering if its possible (essentially if there exists a library) to query a node (either IPC or RPC) on ethereum.
For example there is web3(py,js), there is ethereum in golang and probably other packages/modules/dependencies that integrate that on some languages. Is there something similar in C++?
I checked aleth on github but it looks like a client implementation and not a library(might be that in general that all the etherum documentation is bad :P ).
Thank you very much!


texts: How to configure Geth for accepting future transactions without full sync?

texts:
I need to monitor a future (also known as pending or unconfirmed) transactions.

First of all, let's start with the source code. In the core/tx_pool.go let's configure logging a little. Replace

log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())

in the func (pool *TxPool) add(tx *types.Transaction, local bool) with the

log.Info("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())

After building with make geth and running this code, I see a lot of logging messages like:

INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=3a6716…b8252e from=0xFF4690F85cd1b43aEdcCbeabE15744b5d496bcEE to=0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf
INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=77175c…54e233 from=0x4b5624B25CeDc608C1e092d906B2fFF1DB919C56 to=0x4549c04465e1a89c16D5037c962077857e3923C4
INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=a47f2f…bc7df9 from=0xA15D4f7a9272c178aFA468cA9a0779bC76C37B9e to=0xfD107B473AB90e8Fbd89872144a3DC92C40Fa8C9
INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=fb0061…50a38f from=0x160741663430A72D5725FdF059dE936a4E4c7171 to=0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0
INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=73dc11…cf1165 from=0xb219B36e2f176a271E9b9EfA877c546e922c1329 to=0x390D6673c1FA9DBb8000dB1AE89252b7d531Ab75
INFO [05-20|22:35:42|core/tx_pool.go:672]                Pooled new future transaction            hash=fde95f…af7b68 from=0xEC2e44E44F3c9163029A55d9BC4B310eB524895b to=0xe57Cf6e88505f36954e7c8e6cA9d6b645D030375

But they are shown only after geth is fully synced. I didn't find any special message inside the Ethereum protocol, which means something like I'm ready, sent me new transactions, so most likely there's some if ... else ... statement in the code, which controls processing of future transctions. I'm not very good with golang, so I'm stuck.

How can I make geth logs Pooled new future transaction ... messages right out of the box, without syncing it?

Thanks in advance!


texts: What is the right way to create a struct instance inside a function?

texts:
I read somewhere that if you create a storage variable inside a function, it could overwrite another existing one in the global scope of the smart contract, is that true?

So, if I wanted to create a new struct variable inside a function, and then push it to an array, should I create it in the storage space or memory space?

Like this:

MyStruct storage newStruct;
... // modifiying newStruct variables
myStructsArray.push(newStruct);

Or like this:

MyStruct memory newStruct;
... // modifiying newStruct variables
myStructsArray.push(newStruct);

Same question for when wanting to add a newly instantiated struct to a mapping:

MyStruct storage/memory newStruct;
...
MyStructMapping[index] = newStruct;


texts: What public test-networks and faucets exist?

texts:
What public test-networks exist and what are their conditions?

What are the connection data?
How often (if so) are they reset?
Does a public faucet exist for this test network?
Does a block explorer exist for this test network?
How frequent/ reliable are new blocks mined?
Any thing else user should know about this test network?


texts: Pure functions as a replacement of constant mappings?

texts:
I need to create a lookup table [uint -> uint] that is constant.

Constant mappings or switch-case are not available in solidity. Are pure functions full of if-else the only option?

Any better suggestion?

Update Ideally, I would like an option that minimizes gas utilization


texts: How to save/read mappings within struct?

texts:
I am trying to create a mapping inside struct and then create a mapping of the struct. Take a look at below example:

    // ------------------------------------------------------------------------
    // Each Level related details are stored using `Level` struct
    // ------------------------------------------------------------------------
    struct Level{
        address payable luckyDraw;
        uint256 dividend;
        address payable topHolder;
        uint256 topInvestment;
        uint256 reversedAllowed;
        mapping(address => uint256) userReversed;
        mapping (uint => address payable) levelUsers;
        uint256 ETH_REVERSED;
        uint256 countDeposit;
        uint totalBuyers;
    }

mapping (uint => Level) public payouts;                    // keeps record of each payout

Now here, the payouts saves record of the Level(struct), you can see the struct which have two mapping as well other than other member variables.

When I try to read the payouts, I can never read about these mappings, also it seems that I can never save any record inside these mappings. I am trying to save data for levelUsers but it doesn't seems to work, If I try to read this, it returns me 0x0000.

 // add the purchaser address to the all users array
 payouts[1].levelUsers[0] = msg.sender;

address payable user = payouts[1].levelUsers[0];

The user is always 0x000, seems it never saves successfully

Are my declarations all good?


texts: How do I set the Ledger Nano S to display the recipient's full address?

texts: Presently the Ledger Nano S is showing only the first few first and last digits, with the middle truncated. Why does it truncate the middle of the address? How do we display the entire address?


texts: How can I store user data on smart contract without exposing it to other nodes to read ? I read somewhere that you can store data pointers instead of data on contract and use it for offline data exchange. What does data pointer imply here ?


texts: How can i do 2^0.3 (exponent below 1) using integers?

texts:
simple problem, but i can't seem to wrap my head around it in solidity.
how can i do 2^0.3 (exponent smaller then 1) in solidity using integers.
thanks in advance
K.


texts:
My question relates to a older question on this stackexchange.

Details
Patrick used the Ethereum Wallet to transfer 1 ether to test out buying TheDAO tokens on his mining computer. When (so far it seems that) Ethereum wallet unlocked his geth wallet for 2 seconds (via the IPC API, not exposed to the Internet), a bot that was watching his geth wallet activity swooped in to send a transfer instruction to geth (via JSON-RPC, exposed to the Internet) and transferred his remaining 7218 ethers into the hacker's account.

Did this bug ever got fixed or is still in the newest version of mist and how could i check if I am vulnerable to this attack or not? Did the developer had a special why they implementet it this way or isn‘t even possible to implement it in other way?


texts: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()". throw;

texts:
my question is if "THROW" is deprecated then what i have to put instead throw in the following solidity code ?

// This function creates Tokens
     function createTokens() payable {
        if(isMinting == true){
            require(msg.value > 0);
            uint256  tokens = msg.value.div(100000000000000).mul(RATE);
            balances[msg.sender] = balances[msg.sender].add(tokens);
            _totalSupply = _totalSupply.add(tokens);
            owner.transfer(msg.value);
        }
        else{
            throw;
        }
    }

so the code should look like this:

// This function creates Tokens
 function createTokens() payable {
 require(isMinting == true && msg.value > 0);
 uint256  tokens = msg.value.div(100000000000000).mul(RATE);
 balances[msg.sender] = balances[msg.sender].add(tokens);
 _totalSupply = _totalSupply.add(tokens);
 owner.transfer(msg.value);
    }
    else{
        throw;
    }
}

Or i have to delete the

else{
     throw;

last update:

function createTokens() payable public {
    if(isMinting == true){
       require(isMinting, "Not allowed");
       require(msg.value > 0, "No funds");
        uint256  tokens = msg.value.div(100000000000000).mul(RATE);
        balances[msg.sender] = balances[msg.sender].add(tokens);
        _totalSupply = _totalSupply.add(tokens);
        owner.transfer(msg.value);
    }
    else{
        revert();
    }

thanks AK


texts: Solidity and Web3js codes are not working inside the private Ethereum(geth) network but same codes are working in public ethereum

texts:
geth version : 1.9.0-stable-52f24617,
 node version : v10.16.3,
 npm version  : 6.9.0,
 web3 version : -- web3@1.0.0-beta.36.

genesis.json:

{
"config": {
"chainId": 9663080,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"Ethash": {
  "period": 15,
  "epoch": 30000
}
},
"nonce": "0x0",
"timestamp": "0x5d5769ad",
"gasLimit": "0x7FFFFFFFFFFFF",
"difficulty": "0x1",
"mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
"alloc": {
"0x02731Eb61f258C104F1BB4191cF715d8D1014CD3": {
  "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
}
 },
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

In geth deployment of the smart contract is working, while calling
functionalities I am facing some issues.

2.both web3 code and solidity codes are working in public ethereum but the
  same codes are not working in private network(geth).

Is there any problem with my geth or genesis.json.

Web3js error:

    Error: Returned values aren't valid, did it run Out of Gas?
at ABICoder.decodeParameters (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-abi/src/index.js:226:15)
at Contract._decodeMethodReturn (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-contract/src/index.js:465:22)
at Method.outputFormatter (/home/nithin/project/ConnectedVehicles/node_modules/web3-eth-contract/src/index.js:818:46)
at Method.formatOutput (/home/nithin/project/ConnectedVehicles/node_modules/web3-core-method/src/index.js:163:54)
at sendTxCallback (/home/nithin/project/ConnectedVehicles/node_modules/web3-core-method/src/index.js:473:33)
at /home/nithin/project/ConnectedVehicles/node_modules/web3-core-requestmanager/src/index.js:147:9
at XMLHttpRequest.request.onreadystatechange (/home/nithin/project/ConnectedVehicles/node_modules/web3-providers-http/src/index.js:91:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
at XMLHttpRequest._setReadyState (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
at XMLHttpRequest._onHttpResponseEnd (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
at IncomingMessage.<anonymous> (/home/nithin/project/ConnectedVehicles/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)

I connected to the private(geth) from the remix and I deployed the smart contract and(1) while calling functionality data is not coming. and
(2)in the hash column, it is showing call+transaction hash


texts: How can Ethereum sustain short block creation times if the uncle transactions are not counted?

texts:
Lower block times are clearly desirable. Why does not Bitcoin reduce block creation times to 15 seconds just like Ethereum in this case? Because it would lead to too many forks. The main problem with forks is not the lack of rewards for stale blocks. It is the convergence time and wasted computation.

Let us suppose Bitcoin will reduce block creation times to 15 seconds and call it Bitcoin-15 for the sake of the discussion:

Is there a reason Ethereum does not have as many forks as Bitcoin-15 would? Or perhaps it does but the forks are not as harmful? For example, if the transactions from the uncle blocks had been merged with the transactions in the main branch, the computation would not have been wasted. However, the transactions from the uncle blocks are not merged. The fact that the miners of uncle blocks are rewarded does not solve the problem of wasted computation or convergence time.


texts:
I'm trying to create a crowdsale contract with open-zeppelin.

I want to pause the sale of tokens during the ICO period. I see there is this Pausable.sol which is to pause the contract (as per my understanding). I've called this pausable function in my crowdsale contract like the following:

contract SampleCrowdsale is CappedCrowdsale, Pausable {

  function SampleCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, address _wallet) public
    CappedCrowdsale(_cap)
    Crowdsale(_startTime, _endTime, _rate, _wallet)
  {

  }

  function createTokenContract() internal returns (MintableToken) {
    return new SampleCrowdsaleToken();
  }

}

After deploying the contract, , in the contract management page in Mist I can see the pause and unpause option. However, triggering them doesn't make any difference and the sale goes on. Am I doing something wrong here or this is not the way the pausable function works in opnezeppelin?


texts: Why account balance can decrease when gasPrice is 0 and msg.value is 0?

texts:
It also spends pretty large amount, which doesn't seem to be related to gasUsed

Contract:

pragma solidity ^0.4.24;

contract Test {
    bool i;
    function hello() public {
        i = true;
    }
}

Test script:

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

contract('Test', async (accounts) => {
    it('should pass', async () => {
        const operator = accounts[0];
        const alice    = accounts[1];
        let testInstance = await Test.new({from: operator});
        const before = web3.eth.getBalance(alice);
        const receipt = await testInstance.hello({from: alice, value: 0});
        const after = web3.eth.getBalance(alice);
        assert.equal(before.toString(), after.toString());
    });
});

Ganache launched as

# ganache-cli --gasPrice=0 --gasLimit=7e7

Output:

# truffle test
Using network 'development'.

  Contract: Test
41672
    1) should pass
    > No events were emitted

  0 passing (1s)
  1 failing

  1) Contract: Test should pass:
     AssertionError: expected '100000000000000000000' to equal '99995832800000000000'
      at Context.it (test/withdrawalFunctions.js:16:16)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:160:7)


texts: Is the size of the Ethereum blockchain a problem for full nodes in the coming months?

texts:
In August 2017 the size of my chaindata directory was about 12GB. Now it's November and my chaindata directory is now 220GB - as per expectations with the growing popularity of Ethereum.

I run my geth node on Windows 10 with this command-line:

geth.exe --syncmode fast --cache 1024 --datadir D:\Ethereum\GethBlockchain

I had been running my node on my 2TB platter drive, however around late October my geth node simply couldn't keep-up with the new blocks: it was processing blocks it received at a slower rate than they were being produced, I assumed it was my internet connection or something else.

However I saw in Task Manager that my 2TB disk's Random IO was at a constant 100% usage. I swapped it out for a 500GB SSD (just SATA3, not NVME/U.2/M.2) and my disk Random IO dropped to about 20% and geth was able to process blocks fast enough again. It seems that Ethereum (or at least geth) really needs fast Random IO SSD drives in order to process new blocks (why? don't Merkel trees mean there's no need to query older blocks?).

Given that the blockchain is growing at a very fast rate such that it will probably hit 1TB within a few months (and then likely 2TB and onwards before halfway through 2018) this is a problem because that's hitting capacity limits of SSDs affordable by normal people - then you start needing special (read: expensive) setups comprised of either super-expensive high-capacity SSDs or a massive array (presumably concatenation/JBOD, no need for RAID necessarily) of SSDs just to store the blockchain. I don't like the idea of having to spend $200 every few months for another 500GB SSD - eventually I'll run out of SATA ports.

If this holds true, even without it continuing to accelerate, eventually the Ethereum blockchain will be impossible to store on a geth full-node running on commodity hardware: removing its democratization and putting its control only in the hands of those who can afford the hardware necessary to run a full-node.

I read that geth with --syncmode fast will prune the blockchain of unneeded extra data (e.g. intermediate results for smart-contracts) during its initial sync, but after the sync is finished then any new blocks processed will retain that extra data and that it is not currently possible to prune those new blocks.

This has been raised in the Geth/Mist repos on GitHub, the advice seems to be to delete the entire blockchain and run another --sync fast - but I'm finding that this becomes less and less feasible as time goes on. There is talk of this inability to prune/clean-up the blockchain store as a temporary inconvenience, so I hope it means they'll add support soon.

Why does geth perform so much random IO?
Is there any way to compress the chaindata directory contents at all to minimize disk usage?
What will happen when commodity hardware cannot be used to run a full-node? Do the Ethereum Project organizers have a plan for this eventuality?


texts:
Made a mist wallet put ethereum into it and stupidly forgot my password. Have I lost my eth, or if I still have control of the private keys for the eth can I recover it elsewhere.

Thanks in advance.


texts: Private Ethereum blockchain: missing trie node

texts:
I deployed a private blockchain with the following steps:

Setting the difficulty to a fixed value (see Running a “quick” Ethereum private network for experimentation and testing) and creating the genesis.json
Creating the genesis block
geth --datadir ~/.geth init ~/.geth/genesis.json
Script miningontransaction.js for mining only when there are pending transactions (see Mining until x confirmations have been achieved):
miner.setEtherbase("0xac2c266b110979b162fbcbe994da5b1121b3e2ee");
var minimum_confirmations = 12;
var mining_threads = 1
var txBlock = 0
function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        txBlock = eth.getBlock("pending").number
        if (eth.mining) return;
        console.log("Transactions pending. Mining...");
        miner.start(mining_threads)
        while (eth.getBlock("latest").number < txBlock + 12) {
            if (eth.getBlock("pending").transactions.length > 0) txBlock = eth.getBlock("pending").number;
        }
        console.log("12 confirmations achieved; mining stopped.");
        miner.stop()
    }
    else {
        miner.stop()
    }
}
eth.filter("latest", function(err, block) { checkWork(); });
eth.filter("pending", function(err, block) { checkWork(); });
checkWork();

Starting one node
geth \
    --verbosity 3 \
    --datadir $HOME/.geth \
    --nodiscover \
    --syncmode "full" \
    --gcmode "archive" \
    --cache 2659 \
    --port 30300 \
    --ws \
    --wsaddr "0.0.0.0" \
    --wsport 8006 \
    --wsapi "personal,db,eth,net,web3,txpool,miner" \
    --wsorigins "*" \
    --rpc \
    --rpcaddr "0.0.0.0" \
    --rpcport 8005 \
    --rpcapi "personal,db,eth,net,web3,txpool,miner" \
    --rpcvhosts "*" \
    --rpccorsdomain "*" \
    --networkid 14562 \
    --preload "$HOME/miningontransaction.js" \
    console

Sometimes (completely irregularly) the node stops with the following on the console:
ERROR[08-13|01:20:01.160] Failed to reset txpool state             err="missing trie node 0ebb4a8b33e7945d2bfdf2b5e7c487bdd302e4b40a010389606657cca6132301 (path )"
ERROR[08-13|01:20:03.161] Failed to create mining context          err="missing trie node 0ebb4a8b33e7945d2bfdf2b5e7c487bdd302e4b40a010389606657cca6132301 (path )"

After restarting the node (step 4), the node runs perfectly again. What am I missing?