texts: Out of gas when executing contract via web3 js

texts:
I am having a trouble invoking contract via web 3 js in browser. I am using truffle develop  and have migrated and run tests successfully.

I am also getting the info when I console.log the contract.at();

eventHost.createEvent("testevent1",5,30);

when i run the above in console of chrome

  web3.min.js:2 Uncaught Error: VM Exception while processing transaction: out of gas
        at Object.InvalidResponse (web3.min.js:1)
        at s.send (web3.min.js:2)
        at r.e [as sendTransaction] (web3.min.js:2)
        at c.sendTransaction (web3.min.js:2)
        at c.execute (web3.min.js:2)
        at <anonymous>:1:11

I get this

my contract Event.sol

contract Event {

    uint32 currentMaxNumOfEvents=0;
    struct eventDetail{
    uint32  eventId;
    address  eventHost;
    string  eventName;
    uint32  noOfDaysToRegsiter;
    uint32  maxMembers;
    address[]  memberAddress;
    }
    mapping(uint32 => eventDetail) public events;
    function joinEvent(uint32 selectedEventId)public returns (uint32){
         for (uint i = 0; i<events[selectedEventId].memberAddress.length; i++) {
             assert(events[selectedEventId].memberAddress[i]==msg.sender);
        }
        require(selectedEventId>=0&&selectedEventId<=currentMaxNumOfEvents);
        require(events[selectedEventId].memberAddress.length < events[selectedEventId].maxMembers);
        events[selectedEventId].memberAddress.push(msg.sender);
        return selectedEventId;
    }
    function createEvent(string eventName,uint32 noOfdays,uint32 maxMembers) public returns (uint32){
        events[currentMaxNumOfEvents].eventId= currentMaxNumOfEvents;
        events[currentMaxNumOfEvents].eventHost =msg.sender;
        events[currentMaxNumOfEvents].eventName = eventName;
        events[currentMaxNumOfEvents].noOfDaysToRegsiter = noOfdays;
        events[currentMaxNumOfEvents].maxMembers = maxMembers;
        currentMaxNumOfEvents += 1;
        return events[currentMaxNumOfEvents].eventId;

    }
}

my script running in browser

 if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            // set the provider you want from Web3.providers
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:9545"));
        }
        web3.eth.defaultAccount = web3.eth.accounts[0];
        var contract = web3.eth.contract([{"constant":true,"inputs":[{"name":"","type":"uint32"}],"name":"events","outputs":[{"name":"eventId","type":"uint32"},{"name":"eventHost","type":"address"},{"name":"eventName","type":"string"},{"name":"noOfDaysToRegsiter","type":"uint32"},{"name":"maxMembers","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"selectedEventId","type":"uint32"}],"name":"joinEvent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"eventName","type":"string"},{"name":"noOfdays","type":"uint32"},{"name":"maxMembers","type":"uint32"}],"name":"createEvent","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]);
        var eventHost = contract.at('0x345ca3e014aaf5dca488057592ee47305d9b3e10');
        console.log(eventHost);


texts: How does Ethereum Smart Contract work on Mobile Client

texts:
I want to deploy a smart contract on server and interact with it using mobile client. I'm not familiar with how does that work but after some research, I found something like below:

If we compare communication through web services in mobile client, then pretty much everything is same expect in Smart contract, is no database or deployment service as the result of decentralized nature of the system. Is that right? We can connect mobile client to smart contract using some library like web3 which would essentially work with Json RPC or websockets.

But what if I don't want to connect each mobile client to smart contract using library like web3? Instead, what if I want to have a HTTP server and then it would connect to smart contract like below?

Is that possible? If yes, then how can I do that?

My second question is regarding deployment. In the centralized server scenario, I would have database deployed on some service like AWS etc. I could estimate the deployment cost. I understood that we have to deploy smart contract on Ethereum mainnet which will cost some x amount of Ether. But then I found out that my users will have to pay for each computation. What if I want to bear all the costs? How can we estimate such costs?

Please guide me on the above questions.Thanks.


texts:
It seems like a chicken and egg problem:

(Chicken): I want to start a private blockchain from the genesis block, including the chainspec file that has addresses in it.

(Egg): But don't I generate the addresses on the private blockchain, once the blockchain is fired up?

Specifically, I'm thinking about the chainspec for:

author (insert address here)

accounts (accounts pre-loaded with ether here)


texts: Why do you always have to declare the "memory" keyword for strings inside a function?

texts:
Example:
function myfunc (string memory words) public returns (string memory) {

XXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXX

}

Why is it compulsory to declare the "memory" keyword?
Would the compiler treat it as "storage" otherwise?
Why doesn't this apply for uint256, or other types?
Thanks for your time!!
Have a good one.


texts: Can you call a contract's (C) function with the msg.sender value of another contract (B) while originating the transaction from a third contract (A)?

texts:
If there exists a proxy/implementation system (two contract system) where Contract C (the proxy) only accepts calls from Contract B (Contract B is the owner of Contract C via {owner = msg.sender} in the constructor of contract C), could a third contract, Contract A that is also the owner of Contract B, call Contract C with a msg.sender value that is equal to Contract B (and thus be able to use the proxy's functions because to the proxy it is being called by its owner)?

Additionally, is there any way that A can call C with the identity of B? What if B does not have an explicit function to do so?

Any help here would be greatly appreciated. I am trying to wrap my head around the various calls/interactions between contracts. Is this achievable with a special type of call?


texts: cannot be able to connect to private blockchain hosted at local VM

texts:
I want to use remix IDE and want to connect web3provider which needs to be connected to private blockchain running on VM locally.
My system is running on Windows 10 and I am running the VM on my local using vagrant, the subsequent vagrant file is

Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "3072", "--cpus", "2", "--natnet1", "10.252/16"]
  end

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "ubuntu/xenial64"
  config.vm.box_version = "20190625.2.0"
  config.vm.network "forwarded_port", guest: 8000, host: 8080
  config.vm.network "forwarded_port", guest: 3503, host: 8073
  config.vm.network "forwarded_port", guest: 3505, host: 8075
  config.vm.network "forwarded_port", guest: 8090, host: 8070
end

`

I have created an account which is to be used as a miner and connected that using the command
nohup geth --datadir node1/ --syncmode 'full' --allow-insecure-unlock --port "30303" --rpc --rpcaddr "127.0.0.1" --rpcport "3503" --rpcapi 'personal,db,eth,net,web3,txpool,miner'
 --bootnodes 'enode://6b9a53203cd41106bf21c8496a1ff7d1e41b7437b9b41dedd557d89be35fcc3b18562f8ce81287b4872ca0adfc27c7b5ea98b159698ca7ac833ae133b82b672d@127.0.0.1:30302' --networkid 1505 --gasprice '1' --unlock 0 --p
assword node1/password.txt --mine > node1/01.log 2>&1 &

though the blockchain network is up and running but cannot be able to connect the remix IDE on my local browser to be connected to VM's blockchain.
The http endpoint which I am using to connect to remix IDE is http://127.0.0.1:3503

I have tried changing the rpcaddr to "0.0.0.0" but of no use.
Can you please help me to identify where I would have gone wrong I am new to this please help me with this.


texts: Creating hash of a struct in Solidity and JavaScript

texts:
I have created a message hash in JavaScript using:

let message = {
        'message': 'Receiver closing signature',
        'sender': sender,
        'balance': value
};

message = web3.utils.toHex(message);
let messageHash = web3.utils.sha3(message);

How should I define the equivalent object in solidity, and what function should I use to get the same message hash.


texts: How can I retrieve the constructor arguments used during contract deployment

texts:
I know how to extract the constructor arguments out of the transaction object returned from a contract-deployment operation.

It is explain in web3.js official documentation here.

But this is not an issue of course, because if I am the one deploying the contract, then I obviously know the constructor arguments beforehand.

I am interested in retrieving the constructor arguments of an already deployed contract, i.e., the constructor arguments used during the deployment of that contract (by someone else).

I have the following at my disposal:

The address of the deployed contract
The byte-code of the deployed contract
The contract-deployment's transaction hash

Can any of the above help me retrieving the constructor arguments of an already deployed contract?

Thank you!


texts:
I'm using the crowdsale contract (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/crowdsale/Crowdsale.sol). I have deployed a detailedERC20 smart contract. When I send the ether to the crowdsale contract it shows me the following error:
SafeERC20: low-level call failed

When I use transfer() externally it works fine.

computer Environment
Ganache-cli


texts: How to reset transactions? I can't move funds

texts:
I tried some transactions and they are still unfinished. I started them on the 22nd of may and since then it has been a nightmare.

I could only succeed doing 1 transaction but now I can't do more. They always fail even if I try with high gas.

What can I do?

I tried this:

https://kb.myetherwallet.com/transactions/check-status-of-ethereum-transaction.html

But it is not found, no matter what network I use.

What the hell can I do?


texts: Why the gas estimation of erc20 approve() change with executation?

texts:
The approve function code in my ERC20 contract is below:

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

I tested approval gas cost estimation for multiple times in Rinkeby testnet, found that the estimation results will change like bellow:

Test configuration:

Account1 approve account2 to spend erc20 token,  account2 never spend the allowance after any approval;
Before first time approval,account1 never approve account2 to be able to spend token from its balance;
Before first time approval,account2 has no any balance of that token type.

First time: Account1 approves account2 to spend 1000 tokens

gas estimation:44895

Second time: Account1 approves account2 to spend 1000 tokens

gas estimation:25695

Third time: Account1 approves account2 to spend 1000 tokens

gas estimation:25695

Fourth time: Account1 approves account2 to spend 5000 tokens

gas estimation:29907

Fifth time: Account1 approves account2 to spend 1000 tokens

gas estimation:29895

Get confused by these results, how to understand and explain it?
Thanks.


texts:
I would like to compile older versions of solc contract source code using a solc compiler on my local machine. Is there a website from which to download old solc compilers?

Google revealed a GitHub of old solcs, but I tried using node to run the .js. files without success (could be using this wrong).


texts: Set watch for ethereum address transaction using web3js

texts:
I want to set watch for my public address. So i can get all transaction for that address.

My code is:

var filter = web3.eth.filter({ address: ["0x2A7146700BCe4A574eE36D5e9cd6CF7d8871aEB6"] });
    filter.watch(function (error, result) {
    console.log(error)
    console.log(result);
});

When any transaction occur from ethereum blockchain, i need to call my event.


texts:
I read about this privacy  attack to the BTC network : https://bitcoin.stackexchange.com/questions/193/how-do-i-see-the-ip-address-of-a-bitcoin-transaction

It is based on network observation from a malicious node.
Is that possible in the ETH network as well?

As far as i understand, when your node initiates a transaction, it sends a specific "create transaction" request to its peers,  which then know everything about that transaction  ( so input / output addresses too) as well as the IP of your node.


texts: How to view my contract's .send(value) activity?

texts:
I have my contract address = "0x70094cae9a74c9ae08aa2ae643bcfdd9fa9edfee"

My contract pay back ether to some account: msg.sender.send( amountToGain ) For example msg.sender should gain amountToGain amount. I would like to see this payment using geth if possible.

How could I view the list of value(ether) sent from my contract address to other addresses? The addr.send(amnt)'s act/transaction from=>to (value) does not show up on the block explorer. So by using this function we can anonymously sent money to other addresses and FBI cannot track us.

I have used this script(Common useful JavaScript snippets for geth) but it does not return anything when I used my contract address and msg.sender.send( amountToGain ) action is actually performed.

For example I view following:

  tx hash          : 0x98fb1385453e7f22662789dde2fb88fc4d9312371fc9326f5113599f6d036728
   nonce           : 8247
   blockHash       : 0x942aececdc56a5bdd3265f3c9e898152fdb66d7ea6e91ba1377896a46daf1c25
   blockNumber     : 1346471
   transactionIndex: 0
   from            : 0x6af0204187a93710317542d383a1b547fa42e705
   to              : 0x70094cae9a74c9ae08aa2ae643bcfdd9fa9edfee
   value           : 0
   time            : 1498054743 Wed, 21 Jun 2017 14:19:03 GMT

But the transaction: from contract(0x70094cae9a74c9ae08aa2ae643bcfdd9fa9edfee) to client(0x6af0204187a93710317542d383a1b547fa42e705) there is money has been transferred, which I cannot view as a transaction.

So basically we cannot trace/proof the sent money amount and whom the contract sent to.

[Q] Could we verify the value has been sent to specific account using web3.debug.traceTransaction( tx )?

Example Contract:

pragma solidity ^0.4.0;

contract TestSend {

    uint public balance ;

    function TestSend() {
        balance = 0 ;
    }

    function () {
        throw ;
    }

    function pay() payable public  {
        balance += msg.value ;
    }

     function withdraw(address addr,uint amnt)  public  {

        balance -=  amnt  ;

        if (! addr.send(amnt)) {
              balance +=  amnt ;
        }
    }
}


texts:
It is known that msg.sender must be used for authentication instead of tx.origin (the difference explained here). Some static analysis tools (e.g., in Remix) detect all usages of tx.origin as potential vulnerabilities and advise to use msg.sender instead.

What are the use cases where tx.origin is legitimate? If there are none, is tx.origin going to be deprecated?


texts: Why root and status is null in transaction receipts


texts: How to access content of mapping in a struct?

texts:
I'm aware of this post:

Accessing a mapping within a struct via Truffle console

However, it seems to me, it does not provide a clear answer. Also, my question is more generic and not just for truffle. Also, there's similar code in here (section "structs") but couldn't find any answer to the below questions.

Case 1:

Assume we have the following pseudo-code in solidity:

mapping (uint => BB) public map_1;

struct BB{

  mapping (uint => address) map_2;
}

Question : Given a key, how can I access the content of map_2 in Geth or a user interface?

Case 2:

Assume we have the following pseudo-code in solidity:

mapping (uint => BB) public map_1;

struct AA{
uint val;
}

struct BB{

  mapping (uint => AA) map_2;
}

My question for this case remains the same as the one for case 1.


texts: How do I send all eth deposited to another address

texts: How to receive ether in wallet address and forward to another address immediately on successful deposit?


texts: How to connect to contract via javascript deployed using truffle

texts:
I have deployed a contract using truffle on the testrpc network. I need to write a Javascript code that can connect to the contract and run the functions of the contract but I can't figure out how to do that.

Edit:

I am now using truffle-contract and truffle-artifactor in order to connect to deployed contracts. Here is the artifactor code :

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

var abiVal = JSON.parse(fs.readFileSync('./build/contracts/DINRegistry.json'))

var contractData = {
    contract_name: "DINRegistry",
    abi: abiVal
}

var dirPath = temp.mkdirSync({
    dir: path.resolve("./"),
});

var my_path = '/home/lee/Music/DIN-master';
var expected_filepath = path.join(my_path, '/build/contracts/DINRegistry.json')

function artifactCreator() {
    const artifactor = new Artifactor(my_path);

    artifactor.save({
        contract_name: "DINRegistry",
        abi: abiVal
    }, "./DINRegistry.sol.js")
}

artifactCreator();

The code isn't able to create the file DINRegistry.sol.js. What is incorrect in this code?


texts: What's the best way currently to get events to a Go app that uses go-ethereum?

texts:
I have generated and used Go bindings to deploy a few contracts and that worked very well, but I see events are not implemented yet. Is this work discussed somewhere?

I'd like to understand what options there are for a server-side app in Go to watch events on deployed smart contracts?

I know events are wrappers around EVM log ops and reside as entries inside transaction receipts. Also, watching events are done per contract instance (not by class).

I would like to avoid manually parsing out events which I could do using either polling JSON RPC log changes or RPC pub/sub for logs.

What is the currently suggested way in Go? Please show with an example in code. Thanks!

UPDATE

Opened an issue for go-ethereum to add events for Go bindings so please +1. :)


texts:
How to create a log file of node activity ?

Is it possible to track nodes activity(sending transaction,finding transactions,mining new blocks)?

How to track which nodes are connected/disconnected,time of its activity?

Thanks.


texts: Interacting with an already deployed smart contract in web3.py

texts:
My question is related to the question that is available in this post. However, the answer I'm looking for is not available in that post.
Assume that the seller (owner) deploys the following contract.
contract Purchase {
    uint public value;
    address public seller;
    address public buyer;
    enum State { Created, Locked, Inactive }
    State public state;

constructor() public payable {
    seller = msg.sender;
    value = msg.value / 2;
    require((2 * value) == msg.value, "Value has to be even.");
}

modifier condition(bool _condition) {
    require(_condition);
    _;
}

modifier onlyBuyer() {
    require(
        msg.sender == buyer,
        "Only buyer can call this."
    );
    _;
}

modifier onlySeller() {
    require(
        msg.sender == seller,
        "Only seller can call this."
    );
    _;
}

modifier inState(State _state) {
    require(
        state == _state,
        "Invalid state."
    );
    _;
}

event Aborted();
event PurchaseConfirmed();
event ItemReceived();

function abort()
    public
    onlySeller
    inState(State.Created)
{
    emit Aborted();
    state = State.Inactive;
    seller.transfer(address(this).balance);
}

function confirmPurchase()
    public
    inState(State.Created)
    condition(msg.value == (2 * value))
    payable
{
    emit PurchaseConfirmed();
    buyer = msg.sender;
    state = State.Locked;
}

function confirmReceived()
    public
    onlyBuyer
    inState(State.Locked)
{
    emit ItemReceived();

    state = State.Inactive;

    buyer.transfer(value);
    seller.transfer(address(this).balance);
}

}
Once the seller deploys the contract how can a buyer (address) can interact with this already deployed contract (making sure the new msg.sender is the buyer) in web3.py. This can be done in Remix using the "At address" option.
Note: I'm using Ganache as the local test network.


texts:
versions:
solidity 6.0.0
python3.8
web3 5.13.1
I am trying to get return data from a smart contract function that changes a struct  on the contract. I cannot do that using return because the transaction changes the blockchain, so I read that I can use a Solidity event. Now running my code I am getting the following error:
 web3.exceptions.SolidityError: execution reverted: VM Exception while processing transaction: revert Request not approved yet.

Below is some of the contract. The getKYCData is what is giving me the problem.
pragma solidity ^0.6.0;

contract ReturnData

    struct KYCData {
        string name;
        string home;
        string tin;
        string phone;
    }

    event WalletData(
        string name,
        string home,
        string tin,
        string phone
    );

    Request[] public requests;
    uint[] public request_ids;
    address public manager;
    address public owner;
    KYCData private data;
    uint public serviceCost;

    modifier restricted() {
        require(msg.sender == manager || msg.sender == owner);
        _;
    }

    constructor (address wallet_owner, address admin, string memory name, string memory home,
        string memory tin, string memory phone, uint serviceFee) public {
        manager = admin;
        owner = wallet_owner;
        data = KYCData({
            name: name,
            home:home,
            tin: tin,
            phone: phone
        });
        serviceCost = serviceFee;
    }

    function getData() public restricted view returns (string memory, string memory, string memory, string memory) {
        return (data.name, data.home, data.tin, data.phone);
    }

    function makeRequest(string memory name, string memory description) public payable returns (uint) {
        require(msg.value > serviceCost, "Did not meet fee requirement.");

        Request memory newRequest = Request({
            requestor: msg.sender,
            name: name,
            description: description,
            approved: false,
            active: true
        });
        requests.push(newRequest);
        uint val = request_ids.length;
        request_ids.push(val + 1);
        return val;
    }

    function approveRequest(uint index) public restricted {
        Request storage request = requests[index-1];

        request.approved = true;
    }

    function getKYCData(uint index) public returns (string memory, string memory, string memory, string memory) {
        Request storage request = requests[index-1];

        require(request.approved, "Request not approved yet.");
        require(request.active, "Request is not active");
        require(msg.sender == request.requestor, "Must be requested from request originator.");

        request.active = false;
        emit WalletData(data.name, data.home, data.tin, data.phone);
    }


texts: can anybody help me? It is a simple quesiton:eth_subscribe: notifications not supported

texts:
My geth verison is :

  ./geth version
Geth
Version: 1.5.8-unstable

and run geth with the command below:

 ./geth --identity "helloworld"   --ws  --wsaddr 192.168.241.128 --wsport 8545  --rpc  --rpcaddr 192.168.241.128 --rpcport 8545 --rpccorsdomain "*"   --datadir "$basepath/chain" --port "30303"  --rpcapi "db,eth,net,ssh,miner,web3,personal,admin" --networkid 88888 console

and typed command below in another console:

curl 192.168.241.128:8545 -X POST --data '{"id": 1, "method": "eth_subscribe", "params": ["newHeads"]}'
{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"notifications not supported"}}

when I　typed command changed the port to 8546:

curl 192.168.241.128:8546 -X POST --data '{"id": 1, "method": "eth_subscribe", "params": ["newHeads"]}'
bad method

I found from https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB :
From version 1.4 geth has experimental support for pub/sub using subscriptions as defined in the JSON-RPC 2.0 specification. This allows clients to wait for events instead of polling for them.

So  my geth version is higer than 1.4, So what's the problem??
  Thank you.


texts: Solidity function that accepts mapping as input

texts:
Is it possible for Solidity to accept mappings as input parameter in a function? I've been trying to create a function with a second parameter mapping (string => string) aMapping,

pragma solidity ^0.4.6;

contract testInputArray {
    // Events
    event LogFunctionWithMappingAsInput(address from, address to, string message);

    function sendMessage(address to, mapping (string => string) aMapping) {
        LogFunctionWithMappingAsInput(msg.sender, to, aMapping["test1"]);
    }
}

but compiler throws the following error:

Untitled:7:35: Error: Type is required to live outside storage.

According to Can I call mapping as arguments of function? the function must be internal or private to accept a wrapping struct, but I need the function be callable from outside the contract, directly by an Ethereum transaction.

Is there any way to pass a mapping (associative array or dictionary) as an input parameter in Solidity? Thx!

Refs.:

Passing an array as a parameter from javascrpt (web3) to a Solidity function
A solidity function to accept two mappings and return a single combined map


texts: Comparing values of fetched data with input data of different contracts

texts:
Given two contracts as follows, contract TestData calls contract Reg to fetch data that had already been stored in its map using get_attributes function.

pragma solidity ^0.4.21;
contract Reg {
    mapping (address=>bytes32[5]) Map;

    //Filling the map
    function fill_map(bytes32[5] _attributes) public  {
            Map[msg.sender] = _attributes;
    }

    //Returns data in the map corresponding to an address
    function get_attributes(address _id) view public returns (bytes32[5]){
        return Map[_id];
    }
}

contract TestData {

    address Address;
    function get_address (address _Address) public{
        Address = _Address;
    }

    //Retreive data from Reg contract
    bytes32[5] fetched;
    function fetch(address _reg_Adress) public view returns (bytes32[5]) {
        Reg r = Reg(_reg_Adress);
        fetched = r.get_attributes(Address);
        return (fetched);
    }

    //Retreive input data from user
    bytes32[5] inputs;
    function getInputs(bytes32[5] _inputs) public view returns (bytes32[5]){
            inputs = _inputs;
            return (inputs);
    }

    //Compare input data with fetched data
    bool[5] a = [false,false,false,false,false];
    function compare() public view returns(bool[5]){
        for(uint i=0;i<5;i++){
            for(uint j=0;j<5;j++){
                if(inputs[i] == fetched[j]){
                    a[i] = true;
                }
            }
        }

        return (a);
    }

}

This is how I test it:

Fill the map with ["0x0","0x1","0x2","0x3","0x4"]
For user input I also input ["0x0","0x1","0x2","0x3","0x4"]

The output is correct returning [true,true,true,true,true].

However, if I change the input say, ["0xA","0x1","0x2","0x3","0x4"], the output remains [true,true,true,true,true] although it should be [false,true,true,true,true].

Does something happen to the data as it is being fetched from the Reg contract? When I try testing the same code but with two input arrays rather than fetching the data, it works fine.

Also, I have been looking for other ways to do the comparisons. Is there any other efficient way other than looping?


texts:
I am using web3js, I've set up an ethereum node in my network in a laptop via mist, now I'd like to run a web3js script that uses that node as provider;

var PROVIDER = "192.168.1.40:8545" // I've also tried 30303
var web3 = new Web3(new Web3.providers.HttpProvider(PROVIDER))
web3.eth.getBalance(TARGET_WALLET_ADDRESS);

This throws error

  CONNECTION ERROR: Couldn't connect to node 192.168.1.40:8545.

Port 30303 shows as open, while 8545 shows as filtered. Is there any configuration step I'm missing? I'm supposed to use port 8545 right?

Also, I have a question:

Can I use the node if it's not fully synced? By use I mean get balance of an account and do transactions

Thank you


texts: Is gas limit constant for regular transfers?

texts:
Afaik the minimum amount of gas, required for a regular ETH transfer is 21000.

Is 21000 specific to the protocol itself, or does it depend on the particular network?

Does it depend on custom data, attached to transaction (e.g. does adding more data make the tx more expensive in terms of gas)?

Does it make sense to allocate gas limit more than 21000 for a regular transfer?


texts: How to correctly send RPC call using Golang to get smart-contract owner?

texts:
Update 12 November 2018

Someone shared a very close solution to what I was looking for here.

Update 10 November 2018

Since I'm not able to achieve this using the approach in this question, I created my own library to do the same thing (link). It doesn't rely on go-ethereum package but use the normal net/http package to do JSON RPC request.

I still love to know what I did wrong in my approach below.

Definitions:

owner = public variable in contract with address type
contract = smart-contract that has owner

This is the curl request to get the owner of a contract. I managed to get the owner.

curl localhost:8545 -X POST \
--header 'Content-type: application/json' \
--data '{"jsonrpc":"2.0", "method":"eth_call", "params":[{"to": "0x_MY_CONTRACT_ADDRESS", "data": "0x8da5cb5b"}, "latest"], "id":1}'

{"jsonrpc":"2.0","id":1,"result":"0x000000000000000000000000_OWNER"}

But when I try to replicate it in Golang (code below), I got json: cannot unmarshal string into Go value of type main.response error.

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/ethereum/go-ethereum/rpc"
)

func main() {
    client, err := rpc.DialHTTP(os.Getenv("RPC_SERVER"))
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    type request struct {
        To   string `json:"to"`
        Data string `json:"data"`
    }

    type response struct {
        Result string
    }

    req := request{"0x_MY_CONTRACT_ADDRESS", "0x8da5cb5b"}
    var resp response
    if err := client.Call(&resp, "eth_call", req, "latest"); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%v\n", resp)
}

What did I miss here?

Expected result:

Address in string format. E.g. 0x3ab17372b25154400738C04B04f755321bB5a94b

P/S — I'm aware of abigen and I know it's better and easier to do this using abigen. But I'm trying to solve this specific issue without using abigen method.


texts: Create new UI for deployed contract with remix?

texts:
Is there any way to create new UI for a contracted deployed with Remix?
I know, I can use remix and Metamask to deploy contracts to real ethereum networks (Main, Rinkeby,...) and remix provides us a simple ui to interact with the deployed contracts.
But is there a way to create a new UI using frameworks (like react.js) for a deployed contract?
If it is possible, how?


texts:
I would like to create a multi currency wallet as a POC. I am currently able to make a wallet for Ethereum (Like balance, tx and all) but would like to create it for other as well (like Bitcoin).

I have looked into universal wallets available on the net namely:

Ethos
Jaxx
Atomic
Trust

and was thinking about making something along those lines

I would like to get answers to some questions

Just like using web3js for ETH, is there a way to do it for BTC? Same way like Infura, metamask etc etc for bitcoin exist or not?. If not, what are the alternatives? One is bitcore but I dont want to run a full node on my side

I am looking for directions and resources to start somewhere. Any advice would be useful


texts: geth console cannot attach to geth docker container

texts:
I ask this question again although a similar question is asked here.
I answered that question with what I read and thought is the correct method but heck it doesn't work for me too.
Basically I run a geth instance in docker container and tried to connect geth console from my host computer.
The docker command is as follows:

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
else
  docker container run --network etherdev_net --rm --name etherdev_$1 -p 8545:8545 -v $gethdir/$1:/root/.ethereum -v $gethdir/$1/.ethash:/root/.ethash -v $bootnodedir:/root/bootnode etherdev
fi

The docker container entry point basically invoke a shell script
geth --networkid 5493 --bootnodes "$(echo -n 'enode://'; bootnode --writeaddress -nodekey /root/bootnode/nodekeyfile | tr -d '\n'; echo '@192.168.2.2:30301')" --mine --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal,net --etherbase 0 --unlock "$(cat /root/.ethereum/geth/security/coinbase)" --password /root/.ethereum/geth/security/password.sec

then I run this command on my host to attach a geth console but it returns an error message "Fatal: Failed to start the JavaScript console: api modules: Post http://localhost:8545: EOF"
geth attach http://localhost:8545

I had verified that I can connect to geth using the same command "geth attach http://localhost:8545" if I do a "docker container exec -it ... /bin/sh"
What is wrong here? Is the 8545 port published incorrectly?


texts: Rinkeby Authenticated Faucet: "nonce too low"

texts: I'm trying to use the Rinkeby Faucet to get ether for testing/development purposes. I've made a public Google Plus post with my account address but when I select the amount of ether I want, a message at the top of the screen says "nonce too low". Any suggestions on what I might be doing wrong?


texts: What is the current state of Swarm and Whisper?

texts:
What is the current state of Swarm ? Are they decentralized as they claim they are or they are still in development ?

I am asking this because I've seen that there is no incentive for the nodes to support Whisper and that is optional to support it.
Meanwhile, Swarm is still centralized because it hasn't fully launched.

So my questions are:

What is the incentive for the nodes to run Whisper ?
What is the    incentive for storing data with Swarm rather than IPFS
?


texts: How Blockchain system maintenance is done without downtime in real world?

texts:
I have a question regarding the maintenance of blockchain system.
Whenever any new release comes up then how are the changes made in blockchain without downtime in real world? or is downtime there?
I am not talking about smart contracts, rather i am talking about entire blockchain system, for example: if consensus mechanism is to be changed for a blockchain system.

I am specifically talking about public blockchains like etheruem.


texts: Working around the 16 local variable limit?

texts:
I have a function which negotiates an agreement between two parties using a state channel, to accomplish this I need two signatures bytes32 e, uint8 v, bytes32 r, bytes32 sx2 for the state channel, and I need some variables for each persons agreement that are signed by the state.

This results in a stack too deep error. My workaround is to compress the signatures and variables into a bytes32[] array and type cast where needed. This seems dumb. Anyone have a better way?


texts: Is it possible to have an optional property or method in an interface?

texts: I currently can't deploy any contract which doesn't adhere 100% to the specified interface(s). Is there a way to mark some properties or methods as optional and, if not, is this a planned feature?


texts: Setup Ganache with Metamask. What and where is a Chain ID?

texts:
I am following these instructions.
The problem is that the above instructions don't mention Chain ID  and it appears Chain ID  is required to even make it work. Thus, I'm stuck.

What is the Chain ID? How do I get it to set it?


texts: How to use own custom token instead of gas price in ether?

texts: I want to make my token and want that the token should be used as gas price. Is that possible,if yes please guide me for the same.


texts: Is it possible to access storage history from a contract in solidity?

texts:
With web3, I can access the history of the blockchain like this:

web3.eth.getBalance('0x1234') // returns current balance at address 0x1234
web3.eth.getBalance('0x1234', 1000) // returns balance at block 1000

Cf. https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethdefaultblock

I have not been able to find anything similar in Solidity. Is there a corresponding pattern in Solidity? Or in EVM bytecode? Or fundamental reasons why it cannot be done?


texts: How different clients, with different implementations communicates through the network?

texts: sorry for the dumb question, but i'm wondering how different Ethereum clients, like for example Trinity, Geth, or Parity, written in different languages, communicates over the network. I did not found a specific answer for that question.


texts:
In Quorum, while deploying a 54KB smart contract via truffle migrate, I am getting the error "oversized data"

Tried adding maxCodeSize to genesis.json but did not work


texts: Not able to convert and access Tuples of bytes array and convert to string in Java using web3j

texts:
I am new to the development of smart contract using web3j. I am facing issue, while converting Bytes32[] returned from wrapper of contract(.sol) method to array.

I have contract as:

pragma solidity ^0.4.4;
contract Person
{
    Person[] public people;

    struct Person
    {
        bytes32 firstName;
        bytes32 lastName;

    }

    function addPerson(bytes32 _firstName, bytes32 _lastname) returns (bool success)
    {
        Person memory newPerson;

        newPerson.firstName = _firstName;
        newPerson.lastName = _lastname;

        people.push(newPerson);
        return true;
    }

    function getPeople() constant returns (bytes32[], bytes32[])
    {
        uint leng = people.length;

        bytes32[] memory first_names = new bytes32[](leng);
        bytes32[] memory last_names = new bytes32[](leng);

        for (uint i = 0; i < people.length; i++ )
        {
            Person memory currentPerson;
            currentPerson = people[i];
            first_names[i] = (currentPerson.firstName);
            last_names[i] = (currentPerson.lastName);

        }
        return (first_names,last_names);
    }
}

Function from generated java wrapper as:

    public RemoteCall<Tuple2<List<byte[]>, List<byte[]>>> getPeople() {
        final Function function = new Function("getPeople",
                Arrays.<Type>asList(),
                Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Bytes32>>() {}, new TypeReference<DynamicArray<Bytes32>>() {}));
        return new RemoteCall<Tuple2<List<byte[]>, List<byte[]>>>(
                new Callable<Tuple2<List<byte[]>, List<byte[]>>>() {
                    @Override
                    public Tuple2<List<byte[]>, List<byte[]>> call() throws Exception {
                        List<Type> results = executeCallMultipleValueReturn(function);;
                        return new Tuple2<List<byte[]>, List<byte[]>>(
                                (List<byte[]>) results.get(0).getValue(),
                                (List<byte[]>) results.get(1).getValue());
                    }
                });
    }

In my main function, I am trying access Bytes of Array returned from getPeople method. But I am not note able to converted Bytes of array to string.
I am storing tuples values in main method as:

Tuple2<List<byte[]>, List<byte[]>> x = contract.getPeople().send();

I want to convert value, x.getValue1() to string. Can anyone please tell me how to do it.


texts: What uint type should be declared for unix timestamps?

texts: I try to specify uint type to uint16 instead of just doing uint or uint256 when dealing with time stamps but it says that I must use at least uint24. It works with uint24, but shouldn't uint16 be plenty enough?


texts:
I'm reading this article which says coinbase could charge you for gas fees.

However, when Ethereum gets congested, Coinbase will charge you for
gas fees too. When it comes to gas, Uniswap and Coinbase are a wash.

Is this actually true?
The fee page on coinbase makes no mention of gas fees.


texts: Is there an API for the amount of Ethereum mined in a given time frame?

texts: I'm looking for an api that will give me both historical information and realtime information about how many blocks were mined in a given time frame. I'm also looking for data regarding the total current amount of Ethereum. I need this information in the form of a consumable api (REST api). I've made several searches for data regarding this and I haven't found anything other than historical data in the form of an csv.


texts: I am following a tutorial to use oracle from Provable, so I have to import "https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol". I notice that the contract is very big but all I need is the function provable_query. A big imported contract make the deployment consume more gas, right? Is it a good practice to delete things unrelated to the desired function provable_query before deployment?


texts: Is there a way to separate return values using spaces or newlines in Solidity?

texts:
I want every return value printed by a function form an array to be in new line, or separated by blank spaces. Is it possible? Here is the code snippet:
 function listThem() public view returns(uint[] memory) {
        return(value);
 }

What I get from above code are array elements separated by comma (,). I want to either have them printed in new line or separate them using blank spaces instead of commas. Is it possible?


texts: Convert Uint to boolean array / convert uint to binary

texts:
I would like to convert a uint number to its binary representation, but have so far failed. What would be the best way to make it happen?

Thanks!


texts: Stream ethereum (ERC20) transactions (node.js)

texts:
I would like to get discord message every time when address receive ERC20 token. Is there any way to stream Ethereum transactions?

I tried https://github.com/AlexanderC/ethereum-transaction-stream but it's not working as I want (it start scanning all transactions including old ones).


texts: Permanent deployment of contracts in Geth

texts:
My current method of deploying smart contracts in geth is by generating the bin and abi files of the corresponding sol and then loading the bin and abi files of the contract into geth using the commands:

loadScript('contract.bin)

loadScript('contract.abi)

But the issue I am facing with this is that every time I close geth and open it again, the contracts have to be re-deployed again as the existing contracts seem to be missing.

Is there anyway to ensure a permanent deployment of contracts? Or am I missing any critical step?


texts: Wrong contract balance shown by web3.eth.getBalance

texts:
I want to test if the balance updates when I send some eths
it("the balance matches the price of a person", async function(){
  let instance = await People.deployed()
  await instance.createPerson("BOB2", 89, 110,  {value : 1000000000000000000});
  let balance = await web3.eth.getBalance(instance.address);
  console.log(balance);

});

function createPerson(string memory name, uint age, uint height) public payable costs(100){
        Person memory newPerson;
        newPerson.name = name;
        newPerson.height = height;
        newPerson.age = age;
        insertPerson(newPerson);
        creators.push(msg.sender);
        assert(keccak256(abi.encodePacked(people[msg.sender].name,  people[msg.sender].age, people[msg.sender].height, people[msg.sender].senior)) == keccak256(abi.encodePacked(newPerson.name, newPerson.age,newPerson.height, newPerson.senior)));
        emit personCreated(newPerson.name, newPerson.senior);

    }

The problem that I am facing is that when I send for example 1 eth, the balance in the console updates from 0 to 1, but then if I run "truffle test" again ,the balance does not change, same thing if the I change {value : 1000000000000000000} to {value : 1000000000000000001}.
but if I change {value : 1000000000000000000} to for example {value : 2000000000000000000} it outputs the right balance, 3 eths so what am I doing wrong here?
and one last thing , this has nothing to do with the old problem:
why does
"await truffleAssert.fails(1 == 9);"
return false and
"await truffleAssert.passes(balance == 9);"
return true?, isn't it supposed to be the opposite?


texts: Why is automatically transferring fund is not recommended?

texts:
I think a code and program would be nicer if some functions, such as transferring fund, are done automatically.

However, there are some examples that try to explain it is not a good idea.

For instance, it's said:

"Because of the maximal stack depth of 1024 the new bidder can always increase
the stack size to 1023 and then call bid() which will cause the
send(highestBid) call to silently fail "

Question 1 : How is it possible t increase stack size and carry out the attack?

Question 2: Is it really a bad idea to transfer money automatically in a smart contractor? can we do it if we take some care?


texts: Is there a dead man switch functionality in Ethereum? Say I died and I wanted to send all my coins to my children

texts: If I died one day, would there be some type of function where I can send all my coins to another account I trusted? How would this be done? Say we had an oracle that just monitored public death records and if something matches, it would send all my coins elsewhere. Obviously its not going to be as simple as that. What are some things one would need to account for?


texts: What's the proper way to store a long string (like a news article) in Solidity?

texts: I'm working on Layer 2 so gas/efficiency aren't primary concerns, assuming the function can be executed by the EVM


texts: Can't deploy a contract via MyEtherWallet

texts:
I'm trying to deploy a contract on etherscan.io via MyEtherWallet. I copied bytecode and connected my Ledger Nano, but I can't sign transaction, gas input is not filling up automatically. There are no errors in console. It worked fine with test network.

Is it network problem?


texts:
Error Says Method shh_getPublicKey not Supported.
How can i solve this and get public key.


texts: Reclaiming ETH from "The DAO" on Both ETC and ETH Chains

texts:
If before the fork I invested all my ether in "The DAO", then, if I understand correctly, after the fork, on the ETH chain I can withdraw my ETH from "The DAO" and get all of it back, which I have already done, but on the ETC chain I'm supposed to still be a holder of "The DAO" tokens, which, theoretically, I can exchange for ETC. Am I correct? If so, is there a way to do it?

To phrase it differently, there should be two "The DAO" token versions, one for each chain (call them DAOH and DAOC). However, the token that appears on exchanges is only one of them (I'm guessing DAOH). Right?


texts: unable to deploy contract on rinkeby network

texts:
I am trying to deploy my contract to rinkeby test network but unable to do so here is my contract code.

pragma solidity ^0.4.17;
contract Inbox {
    string public message;
    function Inbox(string initialMessage) public {
        message = initialMessage;
    }
    function setMessage(string newMessage) public {
        message = newMessage;
    }
}

and here is deploy.js code

const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode }  = require('./compile');

const provider = new HDWalletProvider(
  'key pharase',
  'https://rinkeby.infura.io/v3/keyhere'
);

const web3 = new Web3(provider);

const deploy = async ()=> {
  const accounts = await web3.eth.getAccounts();
  console.log('Attempting to deploy from account ',accounts[0]);
  const result = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({ data: bytecode, arguments: ['Hi there!'] })
    .send({gas: '7200000', from:accounts[0]});
  console.log('Contract Deployed to ',result.options.address);
};
deploy();

I am getting this errror

(node:8808) V8: /home/ace/Desktop/ETH/inbox/node_modules/solc/soljson.js:3 Invalid asm.js: Invalid member of stdlib
Attempting to deploy from account  0x3F04693634c13e1FE3dC6345867C389e8A2Ea1AD
(node:8808) UnhandledPromiseRejectionWarning: Error: Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
    at /home/ace/Desktop/ETH/inbox/node_modules/web3-core-method/src/index.js:390:42
    at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:8808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


texts: How to delete element of array, without index?

texts:
When i add element into array, and after adding, i don't know index of this element.
How to delete element in this case?
I can find index, using while, but i think it's very bad thing, because its cause many additional code in contract.

uint[] messageIds;
...
function a(uint _id) {
messageIds.push(_id);
}

May be there is other solution?


texts: Is Mist Wallet a node on the Ethereum network?

texts: I am new to Ethereum.  I've just installed the Mist Wallet, and I find that it keeps the CPU running HOT.  Is the wallet a node on the Ethereum Network?  If so, should I be able to mine stuff?


texts: I'm confused about decimals and total Supply with my erc20 token

texts:
I created erc20 token. I want total supply of 50,00,000.
And I want to give 7% tax on every transaction.
So if anyone sends single coin then, how can I get 7% and transfer remaining to receiver?
For this problem I decided to give 2 decimal places. I.e. value of decimals method I set 2.
So now
I should increase total supply by 2 zeros
Or what
I'm confused
Please help.


texts: Tutorial on Ethereum wallet, create your token: strange behaviour

texts:
I've followed the tutorial here using ethereum-wallet (mist) 0.5.0.

I'm running geth on a custom network launched as:

geth --datadir ~/ethprivatechain/testing/01/ --networkid 42371325 --nodiscover --maxpeers 0 --ipcpath /home/user/.ethereum/geth.ipc  console

I've created three addresses, let's call them : base, Acc2 and Acc3.

I've created two wallet contracts: one for base, one for Acc2.

I've created a token contract as described in the tutorial, using base as the source of ether - the base had 10000 units of these tokens.

I sent 50 of these tokens from base to Acc3.
(I would expect now to have base with 9950 tokens and Acc3 with 50)

What I have: base with 50 tokens, 9950 disappeared and nowhere to be found, Acc3 with 50 tokens.

Is it a bug of the contract found here?


texts: Overwriting of constant variables by inheritance: Why are parent variables only overwritten in functions of the child?

texts:
Let's assume I have the following two contracts Hello and Goodbye, and Goodbye inherits from Hello. Both declare a constant variable aString, i.e. the child contract  Goodbye overwrites the parent's value:

pragma solidity ^0.4.17;

contract Hello {
    // This will be overwritten by child
    string public constant aString = 'Hello World!';

    // Prints Hello World
    function printMe() returns (string){
        return aString;
    }
}

contract Goodbye is Hello{
    // Overwrites `aString` of parent
    string public constant aString = 'Goodbye World!';

    // Why does this print Hello World, too???
    function printMe() returns (string){
        return super.printMe();
    }

    // Prints Goodbye World as expected
    function printMe2() returns (string){
        return aString;
    }
}

So if I call printMe() of contract Hello it returns 'Hello World!' as expected.

Moreover, if I create the contract Goodbye and call its function printMe2() it returns 'Goodbye World!' because aString overwrites the parent's definition of 'Hello World!'. However, if call printMe() of Goodbye which, in turn, calls super.printMe() it returns 'Hello World!'?

Why does printMe() in Goodbye not return 'Goodbye World!'? Why is the overwriting of aString by Goodbye ignored by the super.printMet() call?


texts: How to find out the value using call() method in truffle and testrpc?

texts:
pragma solidity ^0.4.2;

       contract Transfer {

                address public owner;
                mapping (address => uint) balances;

               // constructor
               function Transfer() {
                             owner=msg.sender;
                             balances[owner]=1000;
               }

               function transferToUser(address _to, uint _value) returns (bool success)  {

                 if(balances[msg.sender]< _value){
                     return false;
                  }

                  balances[msg.sender] -= _value;
                  balances[_to] += _value;
                  return true;
           }
          function getBalance(address _user) returns (uint _balance){
                  return balances[_user];
          }

     }

This is the code for contract i have deployed using testrpc and truffle.

I have used the following commands in truffle.

      var contract=Transfer.deployed();
      contract.owner.call().then(console.log);

The owner is printed correctly.Then used call() method to print balance.

      contract.balances[owner].then(console.log);

This call method returned error.How can we print the value in balances[owner]?

The functions defined in contract is called as follows.

          contract.transferToUser("0x4f91a3661a18328bc5d995a1f8b63cc69778a529",300).then(console.log)

         contract.getBalance("0x4f91a3661a18328bc5d995a1f8b63cc69778a529").then(console.log)

Both functions returned hash value of transaction.How can we check the balances returned from the function getBalance() such as balances[msg.sender],balances[_to],balances[_user]?


texts: ETC Mining - DAG File to big in Phoenix miner but Claymore works without any complains

texts:
I am confused, when trying to mine ETC with Phoenix miner, as I did for a long time, it calls the error:

GPU1: Not enaugh VRAM for DAG epoch 329

GPU1 is a RX580 with 4GB, but it is dedicated.
I also have an R7 installed and as the default GPU it gets used by Windows.

If I start up Claymore, mining just works without an error.
I would like to mine with Phoenix, since I get more stable clocks on my R7.

Any suggestions why it behaves like that?
Sincerely


texts: Deposit and withdraw from multiple accounts

texts:
I have a scenario of deposit the amount on a particular address and keep the record of the total amount deposited at this address. The same way one can also withdraw the amount from this address and total should be deducted the withdrawn amount for that particular address.

Here, twick is there can be multiple accounts so there can be multiple addresses and we need to store final amount(deposit/withdraw) account wise. Here we are storing just random amount, not ether.

So my questions are

To store the accounts we need to use the mapping but how to calculate the amount(deposit/withdraw) by using mapping?
can we use the array here?

Thanks

Edit the below part

My program

pragma solidity ^0.4.18;

contract Banking {
  uint deposit;
  uint amount;
  mapping(address => uint) accountBalance;

  function setDeposit(uint amt)
  {
   uint new_deposit = deposit + amt;
   accountBalance[msg.sender] = new_deposit;
   deposit += amount;
  }
  function getAmount() constant returns (uint)
  {
    return(accountBalance[msg.sender]);
  }
  function withdraw(uint amt)
  {
    uint withdrawAmount = amt;
    uint newBalance = accountBalance[msg.sender] - withdrawAmount;
    accountBalance[msg.sender] = newBalance;
  }
}


texts: web3.js can I call a smart contract function without knowing the ABI?

texts:
In a web3 JS dApp (eg.with Metamask),
If I know just the address of a contract and the method name, how can I call that method ?

I don't know the ABI.


texts:
When I run truffle develop it starts a testnet listening at localhost:9545. Is there a way to change the port this testnet is running on?
EDIT: I'm not looking for a way to configure which network truffle connects to. I'm trying to run truffle's development testnet on another port than 9545, which it takes by default. The reason is that it would make it easier to run the code on TestRPC as well.


texts: How can I completely automate a Docker image and Dockerfile for a geth test network

texts:
I would like to create a Docker image for a test network that has everything ready to go - pre-created accounts with ether already allocated.

The problem is there doesn't seem to be a way to do this the Docker Way(tm).  In order to create ether out of thin air, I have to put addresses in the genesis.json 'alloc' section.  In order to get the addresses, I have to create accounts with multiple invocations of geth and then manually edit genesis.json.  Manual steps are not the Docker Way(tm), you are supposed to create a Docker file that does all these steps automatically.

My current best bet seems to be to to create a script that creates the accounts I need and the gets the account addresses from the geth command line option for that and then edits genesis.json on the fly.  That seems... rather crude, and adds more tools to the docker image to do this (at least something that can parse JSON).  Creation of accounts is not idempotent, so I can't just run the same script every time I start the container.

I'm sure the geth community has solved this problem for their own automated testing.  Please share :-)

I've read everything on the first page of this Google Search.  They all have manual steps, which doesn't work for automation that Docker and automated test systems demand.


texts: eth_sendTransaction for function with address type parameters

texts:
I'm interacting with my local private blockchain created using geth. I'm able to use eth_call, but now I have some problems with eth_sendTransaction.

The signature of the function is this:

function addContract(bytes32,address)

So in python I do:

addContract = sha3hex8('addContract(bytes32,address)')

sha3hex8 is a function I've created that I'm sure works correctly because I use it for all the eth_call I've done.
Then I need to add the two parameters.

How can I attach the two parameters with the right encoding? Should I simply concatenate at the end the address parameter without the starting 0x?


texts: Solidity "now" does not update in view function?

texts:
I've noticed that this always returns the same value:

 function getNow() public constant returns (uint) {
        return now;
    }

But when I use the now keyword in an function that changes the state of the network then it seems to work.

Can someone explain why this happens? Is there a way to use "now" in a view function?

Basically I'm just trying to set a timer and figure out how long the timer has left without paying any gas.

Thanks!


texts: how to disable a contract by changing some internal state which causes all functions to revert?

texts:
In official documentation of Solidity about Self-destruct instruction is written:

  If you want to deactivate your contracts, you should instead disable
  them by changing some internal state which causes all functions to
  revert.

Reference: https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#deactivate-and-self-destruct

Can Some one explain me what does mean?

It's sufficient and correct this code to destroy a contract?:

function kill() public {
    if (msg.sender == owner)
    // only allow this action if the account sending the signal is the creator
        selfdestruct(owner);
        // kills this contract and sends remaining funds back to creator
}

Thanks a lot,
I'm learning...


texts:
I want to generate a large number of single user private/ public key pairs and store the public keys in a smart contract. Private keys will be distributed non electronically to users. If a user inputs a successfully private key (via a Dapp) and that key unlocks the public key, they will be rewarded with some ETH from the smart contract.

Steps have been broken down as follows:

Generate private and public key pairs 1000+.
Public Keys are stored in a smart contract
Private Keys are distributed non-digitally to users (lets say printed on paper)
A user coming from some address interacts with our DApp with the aid of MIST and enters the private key they have received.
DApp sends the TX  to the smart contract. Since interaction with DApp is via MIST the msg.sender will be the users address.

As far as I can see there are two possible solutions, to verifying the private/public key combo and sending a reward to msg.sender:

a. A public key is generated from the private key on-chain (let's say using https://github.com/jbaylina/ecsol). If they are a match. Remove public key from the contract and payout msg.sender.

OR

b. Before sending the TX to the smart contract, generate a public key from the private key off-chain (inside our DAPP). Check against the public key in the smart contract. If they are a match.. Payout.

The problem I'm having is choosing between a. and b. Each one has a downside:

a. Performing decrypt on chain is costly. But at least we know msg.sender (where to release the funds to) which is difficult to determine in b.
 OK so I reveal the private/public key combo, but since each private and public key combo are unique, exposing one private key should not affect the integrity of the remaining ones. Public / Private key combos are unique and will be single use.

b. Once I verify the public/private key are a match offchain how can I then let the contract know that the decryption was a success and that it should release funds to msg.sender? In my mind ideally this would occur via a callback.. For example: decrypt off chain, if successful, callback and release funds to calling address. But solidity doesn't offer this functionality. Perhaps I could sign the and validate the transaction for example using (https://medium.com/@angellopozo/ethereum-signing-and-validating-13a2d7cb0ee3). So I record the match came from msg.sender and then get my Dapp to send another request which will trigger a msg.sender.transfer ?

I should note that we do not know the user address beforehand (and in fact it can be any ETH address).

I hope my question clear. Perhaps I'm missing something? Thoughts?


texts:
how to generate public and private key for each user on my decentralized app?
After filling the app on ethereum network?


texts: Solidity mapping struct and search question, how to search by name?

texts:
In this example, how would I write a function for

  getPersonByName(string _name) returns (_address) {}

// Code Example
pragma solidity ^0.4.13;

contract Project
{
    struct Person {
        string name;
        uint funds;
    }

    // this is the mapping for which we want the
    // compiler to automatically generate a getter.
    mapping(address => Person) public people;

    // this is what the automatically generated getter
    // looks like (we don't need to implement this ourselves).
    function getPerson(address id)
        public
        returns (string name, uint funds)
    {
        // copy the data into memory
        Person memory p = people[id];

        // break the struct's members out into a tuple
        // in the same order that they appear in the struct
        return (p.name, p.funds);
    }
}


texts: Possible to run Geth with two data directories (one for full blockchain, one for --fast option)?

texts:
I'm running Geth as well as Mist. I know I can run Geth, run Geth with console, run Geth and attach the console in a new terminal, as well as run Mist on its own. For some reason Mist doesn't seem to boot up when Geth is already running...

Either way, I want to do analysis on the live/main net so I want to download the full blockchain as well as have the fast version for transactions for when the full blockchain is not fully synched for a few days.

Is this possible/recommendable to do simply by specifying one of two separate data directories that I explicitly call when I run geth depending on if I want to update the full blockchain with geth or the light blockchain with geth --fast?


texts: How can I get ETH balance with pending transaction?

texts:
I use web3.eth.getBalance to get balance of a specific address. I want to get how amount of unconfirmed ETH the address has.

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://xxx:xxxx"));

var balance = web3.eth.getBalance("0xbddf0bf3ac858d7fb8a2bdda55884d61779ba5a9");
console.log(balance.toNumber()); // Only confirmed balance is showed. I want to know unconfirmed balance

Update 1

Thanks to @niksmac. I tried to use web3.eth.filter. It seems that pending txes are showed. But it is a little bit strange. I set 0x11fd3ffc4243cac293ee3d349ec906a2786087fe as a specific address, however the address was not showed in the result. And I may have to get the amount of ETH by the transactionHash.

filter.js

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://xxx:xxx"));

var options = web3.eth.filter({address: "0x11fd3ffc4243cac293ee3d349ec906a2786087fe"});
var filter = web3.eth.filter(options);
var myResults = filter.get(function(error, logs){ console.log(logs); });

result

[ { address: '0x2a98c5f40bfa3dee83431103c535f6fae9a8ad38',
    topics:
     [ '0x5a690ecd0cb15c1c1fd6b6f8a32df0d4f56cb41a54fea7e94020f013595de796',
       '0x0000000000000000000000000000000000000000000000000000000000000002',
       '0x0000000000000000000000002e8520ef2806ea0c0c3f02b24dddf0d23e58b5f8',
       '0x0000000000000000000000000000000000000000000000000000000000000000' ],
    data: '0x58425455534400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    blockNumber: 1620014,
    transactionHash: '0xfc93b988bc65686b7f01f5f522ce13cd80c800674de386a82512d77246721b07',
    transactionIndex: 0,
    blockHash: '0x1e932b4902300dd352e5a0f1a446c92ac1d6373c1551acfc83d4b458171009ee',
    logIndex: 0,
    removed: false },
  { address: '0x2a98c5f40bfa3dee83431103c535f6fae9a8ad38',
    topics:
     [ '0xa9c6cbc4bd352a6940479f6d802a1001550581858b310d7f68f7bea51218cda6',
       '0x5842545553440000000000000000000000000000000000000000000000000000' ],
    data: '0x0000000000000000000000000000000000000000000000f53bab9c227ae40000',
    blockNumber: 1620014,
    transactionHash: '0xfc93b988bc65686b7f01f5f522ce13cd80c800674de386a82512d77246721b07',
    transactionIndex: 0,
    blockHash: '0x1e932b4902300dd352e5a0f1a446c92ac1d6373c1551acfc83d4b458171009ee',
    logIndex: 1,
    removed: false },
  { address: '0x2e8520ef2806ea0c0c3f02b24dddf0d23e58b5f8',
    topics:
     [ '0xa609f6bd4ad0b4f419ddad4ac9f0d02c2b9295c5e6891469055cf73c2b568fff',
       '0x0000000000000000000000002e8520ef2806ea0c0c3f02b24dddf0d23e58b5f8' ],
    data: '0x0000000000000000000000000000000000000000000000f3f22f14ecd9910000',
    blockNumber: 1620014,
    transactionHash: '0xfc93b988bc65686b7f01f5f522ce13cd80c800674de386a82512d77246721b07',
    transactionIndex: 0,
    blockHash: '0x1e932b4902300dd352e5a0f1a446c92ac1d6373c1551acfc83d4b458171009ee',
    logIndex: 2,
    removed: false }
]


texts: A contract after selfdestruct cannot manage transactions, and as such any ether sent to it is lost. Wouldn't be better to switch to a contract defined state "dismissed" and reject any ether sent by mistake when in such a state?


texts: Truffle: 'func.call()' retrieves the return-value of a non-constant function

texts:
I've just learned that one can easily obtain the return-value of a non-constant function, by using myContract.func.call() (instead of myContract.func(), which retrieves a response object).

Up until now, I've always added inside func an event containing the return-value, and then parsed the response object returned from myContract.func() in order to extract that value.

This has also been the guidance in dozens of answers across his website!

Questions:

How is it possible that so many people here have missed this?
Is it possibly just a tweak added in Truffle, or can one rely on it when writing an operational Web3.js script?

For the record, I am using Truffle v4.1.14, which relies on Web3 v0.20.6.

Here is the contract that I've used for testing this:

pragma solidity 0.4.24;

contract MyContract {
    uint public kkk;
    function func() public returns (uint) {
        kkk += 100;
        return kkk;
    }
}

And here is the actual test:

contract("Test", function(accounts) {
    it("MyContract", async function() {
        const myContract = await artifacts.require("MyContract").new();
        const x = await myContract.func();
        const y = await myContract.func.call();
        console.log(x);
        console.log(y.toFixed());
    });
});

Thank you!


texts:
A bit ago I bought ETH through Coinbase and now I can't find it. I have been trying to hunt it down all day with my luck. My overall knowledge of crypto is limited so I may be doing it wrong.
When I go to the transaction page on Coinbase I am taken to Etherscan and it shows the address I sent it to, within minutes of buying it. I do not remember transferring it that day, but I am sure I could have.
What I do remember is buying a Ledger Nano S to keep it on, with some other coin. I did not receive the Ledger for months after the purchase. When I boot up the Ledger it shows an account for all my various coins. Each account is there, including ETH. But the ETH is the only one with a 0 balance. I transferred less than 1 full coin but there is no part of a coin showing either.
I have been searching all of my paperwork and apps to see where I would have sent it that day. All I have on my PC that could be relevant is a file called wallet which contains an alphanumeric string with over 600 characters.
Is there any way to track this down? Anything I should be looking for?


texts: how to match python list and integer to solidity smart contract uint256[] and uint256. web3.py

texts:
web3.exceptions.ValidationError:
Could not identify the intended function with name `storeSurvey`, positional argument(s) of type `(<class 'int'>, <class 'list'>, <class 'numpy.ndarray'>)` and keyword argument(s) of type `{}`.
Found 1 function(s) with the name `storeSurvey`: ['storeSurvey(uint256,uint256[],uint256[])']
Function invocation failed due to no matching argument types.

i am trying to call a transaction with arguments of type((uint256,uint256[],uint256[])) and i am passing aruguments of types(int ,list, numpy.ndarray) ,but it shows argument error.how can i solve it?

smart contract part

function storeSurvey(uint _sNo, uint[] memory _response, uint[] memory _diseasesPredicted) public{
  surveyCount++;
  survey[surveyCount] = Survey(surveyCount,_sNo, _response, _diseasesPredicted, msg.sender);
  // survey[surveyCount] = surv;
  bool snr = seniorRegistered[msg.sender];
  // bool pers = peopleRegistered[msg.sender];
  if(snr)
  {
    senior[msg.sender].surveys.push(surveyCount);
  }
  else{
    people[msg.sender].surveys.push(surveyCount);
  }

  emit surveyStored(surveyCount,_sNo,_response,_diseasesPredicted,msg.sender);
}

python

.
.
.

contract = web3.eth.contract(address=deployed_contract_address, abi=contract_abi)
.
.
.
@app.route('/predict',methods=['POST','GET'])
def predict():

    if request.method == 'POST':
        usersym=request.form.getlist('symptom')
        print(usersym)
        for i in range(0, len(usersym)):
            usersym[i] = int(usersym[i])
        symp=[]
        for i in range(132):
            symp.append(0)
        for x in usersym:
            symp[x]=1
        print(symp)
        final=[np.array(symp)]
        prediction=model.predict_proba(final)
        p=prediction.tolist()
        tx_hash = contract.functions.storeSurvey(1,symp, p).transact({'from': account1})
        tx_receipt = web3.eth.getTransactionReceipt(tx_hash)
        .
        .
        .


texts:
I've created a contract.

When I try and add it in to MKEF to MyEtherWallet it says it is not a valid ERC-20 Token?

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

Here is the contact address.

I am very new to this as you can probably tell.


texts: Getting data from contract to the DApp without provider

texts:
I have a DApp that uses metamask or mist as a provider. The DApp can read some info from the contract and show it on page using mist or metamask.
Is it possible to read contract and show information without using metamask or mist?

I think I have a few options:
1) Run a node on a dedicated server and just open default localhost:8545 to use it as a provider. But there will be a lot of security issues then...
2) Maybe use some public nodes like infura.io or blackapps.net(?)

I just want to know the right way to do it. Thank you.


texts:
I was wondering what is the best approach to deploy a contract through a web UI. I am using meteor as framework and geth version 1.7 so i was thinking of using fs in my javascript to create a textfile on the server side with the contract and then writing some script so the contract would compile solidity automatically but then I need to do the following in geth console and i am not sure how it could be done automatically

 var abi = <abi from solc>;
 var myContract = eth.contract(abi);
 var bytecode = '0x' + <bytecode from solc>;
 var txDeploy = {from:eth.coinbase, data: bytecode, gas: 1000000};
 var myContractPartialInstance = myContract.new(txDeploy);


texts: How to readin javascript code into the geth console?

texts:
In the contracts tutorial, quite a long piece of code is provided on the geth console to the client:

[...]
function(e, contract){
  if(!e) {

    if(!contract.address) {
      console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");

    } else {
      console.log("Contract mined! Address: " + contract.address);
      console.log(contract);
    }

  }
}

How could I provide this function definition from an external file to the console?, such that I don't have to write it all on the console which is quite inconveniente i find.


texts:
var CredentialOrgFactory = artifacts.require("CredentialOrgFactory");
var CredentialFactory = artifacts.require("CredentialFactory");
var ApplicantFactory = artifacts.require("ApplicantFactory");
//var ProcessCredentials = artifacts.require("ProcessCredentials");

module.exports = async(deployer) => {
    let deployCredentialOrgFactory = await deployer.deploy(CredentialOrgFactory);
    let deployCredentialFactory = await deployer.deploy(CredentialFactory);
    contractCredentialFactory = await CredentialFactory.deployed()
    let setAddress = await contractTwo.setAddress(
        CredentialOrgFactory.address,
        { gas: 200000 }
    );
};

with the message:

(node:13120) UnhandledPromiseRejectionWarning: Error: VM Exception while processing transaction: revert
//some unimportant stuff  //
(node:13120) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13120) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

what is the proper coding in the 2_deploy_contracts.js file?   maybe i'm not setting the address of CredentialFactory properly?  thoughts?  i'm a bit stuck atm.

it could be part of the test file.
    pragma solidity ^0.4.21;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/CredentialFactory.sol";

contract TestCredentialFactory {
CredentialFactory credentialFactory = CredentialFactory(DeployedAddresses.CredentialFactory());

    function testIsActiveValid() public {
        bool r = credentialFactory.isCredentialActive(0x2259aA88Cc0aa3d83d5ec5aF6096C627778FBD06, 0);
        Assert.isTrue(r, "Valid isActive Test.");
    }

    function testIsActiveInvalid() public {
        bool r = credentialFactory.isCredentialActive(0x5a186B7FeC36909678211F69beB67EC3b1E4fFBB, 5);
        Assert.isFalse(r, "Outside Range IsActive Test");
    }
    function SelectOrgCredentialCount() public {
        uint256 testVal = uint256(credentialFactory.SelectOrgCredentialCount(0x2259aA88Cc0aa3d83d5ec5aF6096C627778FBD06));
        uint256 expected = 1;
        Assert.equal(testVal, expected, "Expected Credential Count (1)");
    }

}


texts:
Summary: tokens shown on Mist have a balance of 0, while I can see a positive balance on etherscan.
DISCLAIMER: My geth is sync & I did add the token under the contracts tab.

I have some tokens in a ETH wallet I made using Mist. My Mist version is the latest (9.2), under ubuntu. Some Tokens I bought, some others I received by airdrop, like Xenon. They are all ERC-20. As everybody who has ether received some xenons, I will use this one as example. I can see them all on etherscan.io but it is stuck to 0 on Mist (and ethereumwallet).

No other question accross the web is helpful. When there are answers, they speak of some functions that I have no idea about (these functions don't work on the mist>toggle develop tool>mist UI>console).

Steps I have done:

Went to Contracts tab
clicked "add token" under "custom tokens"
entered Xenon address : 0xab95E915c123fdEd5BDfB6325e35ef5515F1EA69
entered Xenon under token name
entered XNN under token symbol
entered 18 under decimals

It shows 0.

My geth is sync in "light" mode. Back in the days, it was synced in normal mode, token balance was also 0 so the light mode is not the root of the problem. (not syncing in normal mode anymore, too slow).

I have tried the following:

added the token contract under "custom contracts", JSON interface was the one I found on etherscan: https://etherscan.io/address/0xab95e915c123fded5bdfb6325e35ef5515f1ea69 (under contract source, copied contract ABI). Did not help.
deleted all files under /home/[username]/.config/Mist (folder can be found under file>backup>application data) and restarted. Did not help.

Other possibly useful info:

I have a single account under the Wallets tab. It has >1 ether. There is no wallet contracts listed.
in the contracts tab, there is nothing else than the xenon custom contracts, the xenon token or the unicorns token (by default after fresh install of mist).
there are two errors showing up in the developper window that look irrelevant to my issue (unless the SourceSansPro font is used to show balance > 0?):

|                                                                 |

SourceSansPro.otf Failed to load resource: net::ERR_FILE_NOT_FOUND
/sockjs/info?cb=h2d0g47fwv Failed to load resource: net::ERR_FILE_NOT_FOUND


texts: Factory pattern for multiple contracts inheriting from same abstract contract exceeds size

texts:
I have a base abstract contract which is inherited by 3 other contracts (all having the same interface). I am trying to use a factory contract to conditionally create instances of the derived contracts but the overall size of the factory is becoming too large (>24KB) on importing all 3 of them. I suspect it's because of the redundant code of base abstract contract which is common to all.
What would be the correct/best possible way to achieve this?
Thanks


texts: How to set the timeout for truffle test's before block?

texts:
I'm running my tests on a private chain and some of them times out:

  1)  "before all" hook:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I tried to set timeout to the whole test or to the before part as per mocha documentation:

contract("looong tests", accounts => {
   this.timeout();

or

before( done => {
   this.timeout(40000);

I got this error:

  1)  "before all" hook:
     TypeError: _this.timeout is not a function

Adding -t command line parameter doesn't seem to have any effect:

truffle test myTest.js -t 40000
truffle test myTest.js --timeout 40000

I see an old pending fix in truffle: https://github.com/trufflesuite/truffle/issues/261

How can I increase the timeout for the before statement?

Adding timeout to individual test cases works but not for before statement :(

   it('one long test', () => {
        ....
    }).timeout(40000 );

EDIT:
I've a workaround for now, moved the code from before to the first test which I've made sync:

   it('should go to before block but can't set timeout there', done =>  {
        new Promise( async function (resolve, reject) {
          // my before code
          resolve();
        }).then( res => {
         done();
        });
    }).timeout(40000 );


texts:
How can I revert a transfer of ETH funds to my smart contract?
I would like to instantly revert any ETH being sent to my smart contract.


texts: Truffle compile gives Parser Error: Error parsing openzeppelin-solidity/contracts/ownership/Ownable.sol

texts:
I installed the latest version of truffle, solc, node and also installed new version of openzeppelin-solidity library in my project.

Changed the truffle-config.js to use new solc version. My contract inherits from the openzeppelin library. Now when i run truffle compile, it give me the following error.

Error parsing openzeppelin-solidity/contracts/ownership/Ownable.sol: ParsedContract.sol:8:1: ParserError: Source file requires different compiler version (current compiler is 0.5.2+commit.1df8f40c.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
contract Ownable {
^------^

Here are the versions for everything I'm using:

$truffle version
Truffle v5.0.0 (core: 5.0.0)
Solidity - 0.5.2 (solc-js)
Node v11.4.0

$ solc --version
solc, the solidity compiler commandline interface
Version: 0.5.2+commit.1df8f40c.Linux.g++

openzeppelin-solidity package.json has this
"_from": "openzeppelin-solidity",
"_id": "openzeppelin-solidity@2.0.0",
....
"version": "2.0.0"

Now the Ownable contract uses compiler version ^0.4.24, which would be the case for all the contracts in the library.

Any ideas why this is happening and how to fix this?


texts: Solidity Error Address / Address Payable

texts:
I'm currently learning solidity programming to create a basic smart contract based on a 2018 tutorial where solidity was using version 4. I'm currently using truffle v5.0.21. I understand that there was an update from "address" to "address payable", but i'm still not able to get it to work after referencing to similar threads. Appreciate any help. Thanks!

Code for ApprovalContract.sol:

pragma solidity >=0.4.18;

contract ApprovalContract {

    address public sender;
    address public receiver;
    address public constant approver = 0xAFXXX;

    function deposit(address _receiver) external payable{
        require(msg.value > 0);
        sender = msg.sender;
        receiver = _receiver;
    }

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

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

}

Error that comes out on CMD:

//start of error code

TypeError: "send" and "transfer" are only available for objects of type "address payable", not "address".
                receiver.transfer(address(this).balance);
                                     ^---------------^

Compilation failed. See above.

//end of error code


texts: Who gets the gas for confirming transactions in geth?

texts:
I am seeing lines in my geth log like this

INFO [07-20|10:32:55] Imported new chain segment               blocks=1  txs=143  mgas=5.957   elapsed=129.755ms mgasps=45.910  number=4049412 hash=9b6bc7…174802

It seems logical to me that I would get at least part of that gas for verifying blocks but I can't find any evidence of this being the case.  What is the mgas and mgasps and does anyone get this gas/transaction_fees for verifying or does it simply evaporate?


texts: Where can I learn how to develop DApps using the solidity programming language?

texts: What resources exist to help people learn the solidity programming language and create smart contracts & DApps on Ethereum?


texts: Should allowance amount have to be reduced on each successful call to transferFrom?

texts:
I'm confused about this issue.

Description of approve function states

  Allow _spender to withdraw from your account, multiple times, up to
  the _value amount.

If I'm understanding this correctly then it means that amount of what _spender is allowed to transfer will stay the same till this function is called again and _value changed.

But then description of allowance says

  the amount which _spender is still allowed to withdraw from _owner

Which makes me think that allowance gets reduced after each transfer? Or it just mens that even if _spender is allowed to spend 1000, he actually will be able to spend only x if the x is current balance and it is less than 1000?


texts: How to cast address to address payable in solidity 0.5.0

texts:
Got address from 3rd-party library:

address wallet = rlp[5].toAddress();

And wanna transfer some funds to it:

wallet.transfer(amount);

Got error:

TypeError: Member "transfer" not found or not visible after argument-dependent lookup in address.
        wallet.transfer(amount);
        ^-------------^

And casts not works:

((address payable)(wallet)).transfer(amount);


texts: Is this possible ti pay for ERC721 token with other tokens not eth?

texts: I want to create nft where people buy it using another erc-20 token not eth or bnb is this possible where to start?


texts: Geth is stuck 60-100 blocks behind main net for 3 weeks, how can I solve this issue?

texts:
I've been trying to sync the Ethereum Blockchain using Geth and as a full node on my MacOS for almost 3 weeks now, however I am still stuck 60-100 blocks behind the main net, as you can see below:
currentBlock: 12256818,
highestBlock: 12256898,
knownStates: 534379826,
pulledStates: 534200595,
startingBlock: 0
My MacOS has the following specifications:
Processor: 2.6 GHz 6-core Intel Core i7
Memory: 32 GB RAM
it should be strong enough to sync the blockchain!
Please advise on what to do? should I switch to Parity?


texts: What's the advantage of using mainnet over testnet for contract tokens?

texts:
Let's say that I crowdfund a project by selling shares in form of tokens on the Ethereum platform to investors. It seems that I can do this on the testnet without any disadvantage.

Are real Ether needed for this situation? Is the idea that my shares must only be sold for real Ether on the mainnet and not any other currency?

If so, how is that enforced?


texts:
I have ubuntu server. I tried to make

root@vid:~# swarm up 1.txt
65b03c05950213ae7d3d55659aabe1828c07ea79c30a4e61e44342a8b5d41653
root@vid:~#

How can I see this file from my local Mist browser?

bzz://5c7568a22427698bb6f92dd2e0cb560e2d17ec64228e3965052830d6e1fe393e


texts: How to download/install alethzero ethereum client download windows 10?

texts:
I am new to Ethereum and when  i see some videos i found they are using alethzero ethereum client installed and running contracts.

I am unable to find from where can i download alethzero ethereum client
How can i install and run alethzero ethereum client ??

Thanks in advance


texts: What are the limitations of proof of authority

texts:
The parity implementation of Ethereum provides proof of authority as an alternative consensus mechanism.

I have not found much commentary about the advantages/limitations of this model for permissioned blockchains. For example let's imagine that there is a consortium of banks which want to interact with each other through a permissioned ethereum blockchain. Each bank owns one authoritative node which can sign blocks, and all the banks sign blocks in a round robin fashion.

What kind of attacks could one of the authorities do at the expense of the others?


texts: What encoding is used for Ethereum addresses?

texts: Is it Base58Check, which is used for Bitcoin addresses? Or something else?


texts: Result of calling web3.version.getNetwork() from browser-side code is always undefined?

texts:
I'm trying to get the network ID from the Web3 object on the client side (i.e. - while running Javascript code in the browser).  I have code that confirms that the object exists and it does.  I have the Metamask extension installed and configured in Chrome.  I have clicked on the extension and I am definitely connected to the Ganache network client (Localhost 8545).  However, every time I call **web3.version.getNetwork()** the result is **undefined**.  Does anyone know why this is happening and how I can fix it?

UPDATE: I tried the same test with web3.eth.getAccounts() and that too is coming back undefined.  I'm guessing I'll get the same result with any of the Web3 methods/properties I try.

    // Make sure the Web3.js object has been defined.
    web3_helpers.web3AndMetamaskCheck();

    if (typeof gameDetailsObj == 'undefined' || gameDetailsObj == null)
        throw new Error(errPrefix + 'The game details object is unassigned.');

    if (typeof currentUserObj == 'undefined' || currentUserObj == null)
        throw new Error(errPrefix + 'The current user object is unassigned.');

    // >>>>> getNetworkCall is ALWAYS 'undefined'.
    var getNetworkCall = web3.version.getNetwork();


texts: Where does Whisper store encryption keys?

texts: I've noticed that whisper persists symmetric and asymmetric keys created in the geth console by referencing their id, but where does it save these keys, and can the directory be configured? Geth's --datadir seems like the obvious place where they would be saved, but I've looked and it doesn't seem like they're saved there


texts: Are there any official resources or websites for contract appraisal?

texts: Obviously people can post specific questions here but, since everything is open source anyway, is there a place for people to post contracts and allow other people to point out vulnerabilities or problems. Seems like a reasonable idea to help reduce faulty contracts. Thanks


texts:
When I launch geth with ipcapi:

geth --testnet --rpc --rpcapi "eth,web3,txpool" --ipcapi "admin,db,eth,miner,net,shh,txpool,web3"

geth returns me an error:

flag provided but not defined: -ipcapi

What's wrong ?


texts: How to handle library function prototype changes?

texts:
One great thing about using a library is that the library code can be modified, and as long as the api function prototype stays the same, all we need to do is point to the new address of the updated library.

What happens if we need to add a new function, or change the function prototype of a library?  Since the signature needs to be declared in the main contract, is there a trick to update those?


texts: How to get a variable from the smart contract with web3 and abi?

texts:
I use web3.js and try to take a value of the variable from the smart contract.

My code for it is:

var contract = web3.eth.contract(abi).at(address);

where abi - json array and address - valid working address.

Part of abi json object is

{
      "constant": true,
      "inputs": [],
      "name": "weiRaised",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "payable": false,
      "type": "function"
},

When I use this code:

console.log(contract.abi[0].abi[6].name);

I see "weiRaised" in the console.

But if I use

console.log(contract.abi[0].abi[6].inputs);

I see 'undefined'.

What I am doing wrong?
How Can I get the variable from the smart contract, based on abi and web3.js?


texts:
Is it possible in Ethereum blockchain to have two or more events simultaneously occurred?

Regarding the following solidity code:

    function _transfer(address _from, address _to, uint _value) internal {
    // Prevent transfer to 0x0 address. Use burn() instead
    require(_to != 0x0);
    // Check if the sender has enough
    require(balanceOf[_from] >= _value);
    // Check for overflows
    require(balanceOf[_to] + _value > balanceOf[_to]);
    // Save this for an assertion in the future
    uint previousBalances = balanceOf[_from] + balanceOf[_to];
    // Subtract from the sender
    balanceOf[_from] -= _value;
    // Add the same to the recipient
    balanceOf[_to] += _value;
    Transfer(_from, _to, _value);
    // Asserts are used to use static analysis to find bugs in your code. They should never fail
    assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}

What if some burning or minting operations have occurred and changed the balance of _to or _from  after balances update  but before assertion.

For example:
Balance of (_from) = 10 , Balance of (_to) = 0
uint previousBalances = 10

function _transfered triggered and _value = 5 so after updating balances we will have
Balance of (_from) = 5 , Balance of (_to) = 5
uint previousBalances = 10

What if after balances update but before assertion 3 tokens were minted to the address of (_to)
Balance of (_from) = 5 , Balance of (_to) = 5+3
therefor assertion would be failed
uint previousBalances = 5 + 5 + 3 = 13

IS THIS ASSERTION A RIGHT WAY TO CONTROL UPDATING BALANCES??


texts:
I am trying to connect remix to testrpc, but anything at all I run there gives me an "out of gas" message.

I started the testrpc using

testrpc -l 4500000000000

So I would have thought it would be OK, the contract itself is nothing right now - just a test contract with a setter and a getter function for a byte32 field.

The usual answer to this seems to be to increase the gas using the -l parameter, but whatever I set doesn't seem to be enough.

Edit: The same error doesn't occur when running on the Javascript VM, only when I connect to testrpc.

There are no arrays or anything like that. The function is just a placeholder for now while I work out how the integration side works.

pragma solidity ^0.4.0;

contract Functest {
    bytes32 foo;

    function setFoo(bytes32 _foo) public {
        foo = _foo;
    }

    function getFoo() constant public returns (bytes32) {
        return foo;
    }
}


texts: web3.eth.getAccounts() returns no output

texts:
const deploy = async () => {
  const accounts = await web3.eth.getAccounts();
  console.log("Attempting to deploy from contract ", accounts);
};

The code runs but returns nothing and even the next line doesn't get logged to the console. I am using HDWalletProvider v1.0 and using Infura rinkeby test network and when I tried to log the provider used, it returned the correct object with my account and everything.


texts: What is the correct way of launching contract from contract

texts:
Simplified version of my contracts works

MyContract

await contract.methods.info().call() Works indicating that there is
no error in the MyContract itself.

Launchpad

There is no issues when launching MyContract using launchpad contract since I get address to a newly published contract.

The problem is that when I call the contract created with Launchpad contract in JavaScript I get the following error

  Uncaught (in promise) Error: Couldn't decode uint256 from ABI: 0x

contract MyContract {
  function info() external view returns(uint min, uint max) {
    return(1, 2);
  }
}

contract Launchpad {

 function launch() public returns(address) {
   MyContract myContractAddress = new MyContract();
   return myContractAddress;
 }

}


texts: Iterating over transactions in a private blockchain using web3.js

texts:
This question is similar to this one. I'm trying to iterate through all transactions in a private block chain and look for specific data sent in the 'data' fields of each transactions. Is the following approach valid:

    // Fetch all transaction logs with the specified address
    filter = web3.eth.filter({fromBlock: 0, toBlock: 'latest', address: to_addr});
    // Get all entries
    results = filter.get((function(error, result){
          if (!error)
            console.log("[I] Fetched all transactions sent or sent to " + to_addr);
           else
            console.log("[E] An error has occurred " + error);
    });

    var json_tuple;
    // Iterate through the transactions in the logs
    for(var log in results) {
        var log_tx_hash = log.transactionHash;
        // Lookup transaction with hash
        var tx = web3.eth.getTransaction(log_tx_hash);
        // Check the to and from addresses. We skip transactions unrelated to the current sender
        if(tx.from === from_addr) {
            // Parse transaction data and check recipient
            json_tuple = JSON.parse(tx.input);
            if(field in json_tuple) {
                //Do something with a field of the input data sent
                // as a JSON object
                console.log("We have found a transaction with data: " + json_tuple[[field]]);

            }
         }
    }

Is this a correct way of iterating through transactions based on a recipient address filter?