texts: Vyper and ethereum: how do I read a public constant function on another contract?

texts:
I'd like to call a constant function on one contract (X) from another contract (Y). I have the ABI and address for X. X and Y are both on Ropsten. I can interact with X fine using, for example, MEW.

Here is the code for X:

@public
@constant
def read() -> bytes32:
    return 0x0000000000000000000000000000000000000000000000059f43ef8557c30000

And the ABI:

[{"name": "read", "outputs": [{"type": "bytes32", "name": "out"}], "inputs": [], "constant": true, "payable": false, "type": "function", "gas": 283}]

Contract Y looks like this:

feedaddress: public(address)
feed: public(bytes[32])

@public
def __init__():
    self.feedaddress = 0xAb3F6737b0cf41e8a6AE297A3833021f8af2a3aC

@public
def myread():
    self.feed = raw_call(self.feedaddress, 'read', outsize=32, gas=msg.gas)

@public
def setfeedaddress(_new: address):
    self.feedaddress = _new

It returns "Warning! Error encountered during contract execution [Reverted]" on etherscan. What am I doing wrong?


texts:
We create a mapping when creating a token to link donator addresses to the sum of tokens that belongs to this user. This mapping contains addresses which are ETH wallet addresses.

Piece of this mapping can be interpreted like this string:

0x1234567 => 50 //that means ETH address 0x1234567 has 50 tokens

My question is: most of ICOs accept both ETH and BTC donations, so how do they organize that main token mapping if ETH and BTC have different addresses?


texts: If Address and private key doesn't get stored in Ethereum,then how will it validate users?

texts:
I think in a normal database,the username and password gets stored in the database and when a user enters his/her credentials,it checks with the content in the database to know his/her Authenticity.
But in Ethereum,The Address and Private key doesn't get stored,so how will it validate users?


texts:
for (uint8 i = 0; i < total; i++) {
  if (myarray[i].my_int >= maximum && my_array[i].my_second_int <= maximum) {
        result = my_array[i].id;
        break;
  }
}

I've been trying to see if there's any way to optimise this loop so that it consumes less gas, as it is executed a very large number of times in my contract, however, I can think of any obvious optimisations. Am I missing something?

UPDATE

  for (uint8 i = 0; i < total; i++) {
            assembly {
                //We only add 32 bits because my_int is first in the struct.

                my_int := mload(add(add(myarray_slot, 0x20), mul(i, 0x2A0)))

                //We add 288 because my_second)int is second in array

                my_second_int := mload(add(add(myarray_slot, 0x120), mul(i, 0x2A0)))
            }
            if (my_int >= maximum && my_second_int <= maximum) {
                assembly {
                    //We add 512 to get to address position in struct (2 * 256 bit ints) and we multiply with 672 (total size of struct (2 ints * 256 + address of size 160 bits))

                    result := mload(add(add(myarray_slot, 0x220), mul(i, 0x2A0)))
                }
                break;
            }
    }

So I added the following code, however now result is always 0. I'm not sure what I'm doing wrong...Please note my_int and my_second_int are both uint256 and id is an address


texts: Saving balances of address array through function call

texts:
I have many addresses that map to values in an external program. I want to feed this into a smart contract's state, but I'm wondering what is the most cost-effective way to do this.

Right now I have the simple solution:

 function storeValues(address[] addresses, uint[] values) public {
        for (uint i = 0; i < addresses.length; i++) {
            balances[addresses[i]] = values[i];
        }
 }

The problem is that balances is a state variable and for each iteration, it saves to this state, which is expensive. I tried to create a temporary mapping inside the function and save to that instead, but apparently, it wasn't possible to create a dynamic mapping like that


texts: Is it possible to create batches of transactions without using smart contracts?

texts:
Scenario: Suppose that I have to make three transactions simultaneously to Alice, Bob and Claudia. Now the condition is if any one transaction fails the other two must also not go through.

Query: Is there any way to achieve this without using smart contracts? Is there any in-built feature of Ethereum Blockchain that can create batches for multiple transactions?


texts: Can anyone assist with this contract code project of transferring any deposited eth in my contract to another contract?

texts:
const TX = require('ethereumjs-tx').Transaction

let Web3 = require('web3')
let url ='HTTP://127.0.0.1:7545'

let web3 = new  Web3(url)

const contract_account1 ='0x68B010FEd863Cdb12F6bA28e0C19d08773CeCEF2'
const privatekey = Buffer.from('232637df74dbf18a029851f375e6c6888a5a4382411b8ffe4ecb809c84e0e77d','hex',)
const receive_account2 = '0xf74f4dB0F0E05aF8409454867cE8059aBdd3CF8d'
const contract_abi = ''
const contract = new web3.eth.Contract(contract_abi, contract_account1)

web3.eth.getTransactionCount(account1, (error,txCount)=>{
  // build a transation object

  const txObject  ={
    nonce:web3.utils.toHex(txCount),
    to: receive_account2,
    value: web3.utils.toHex(web3.utils.toWei('2', 'ether')),
    data:contract.method.transfer(receive_account2, web3.utils.toWei('2', 'ether')),
    gasLimit:web3.utils.toHex(21000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
  }
  console.log(txObject)

  //sign transaction with private key of sender

  const tx = new TX(txObject)
  tx.sign(privatekey)

  //serialize the transaction

const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')

  //broadcast transaction to the network

  web3.eth.sendSignedTransaction(raw, (error,txHash) =>{
    console.log(txHash)
  })
})


texts: Checking if input is a viable Ether value

texts:
QUESTION:

Does web3.js have a function that checks if a value (Number | String | BigNumber) is a valid Ether Value? If not, what might be an efficient way of doing so? Would I have to manually make a function to make sure that the input value doesn't have more than 18 decimals, isn't negative, etc?

ELABORATING:

My application is using web3.js with geth and users will be able to withdraw funds from their balances at any time. Now during the withdraw process, they input the amount they wish to withdraw. To my understanding, These are the characteristics of Ether:

18 decimal points
Greater or equal to zero

I could make a function that measures how many decimal points exist in the users input, but would I be reinventing the wheel?


texts: My wallet has been compromised, how can I transfer all remaining funds to another wallet

texts:
Some scammers managed to get hold of my Private Key and trashed my wallet, using an automatic script.
They didn't get hold of everything, because there was not enough Ethereum in it for paying gas prices.
Is there a way that i can quickly transfer the remaining tokens to another address?
If I have to transfer them one by one it will probably take too long, since i am guessing that as soon as some ETH reaches that wallet they will run that same script again.


texts:
I am trying to return a matrix in React that I get from a contract function.

This is the function that resonate the matrix:

    int[][] public publicData;

    function handleAddData(int[] memory data) public {

    publicData.push(data);

    }

   function getData() public returns(int[][] memory data) {
    return publicData;
   }

I'm using solidity version 0.5.

In React, I try to get the data as follows from the app.js file:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import web3 from './web3';
import datastorage from './datastorage';

class App extends Component {

  state = {
    data: []
  };

  async componentDidMount() {
    const data = await datastorage.methods.getData().call();
    this.setState({ data });
  }

  render() {

    return (

Data:

Aqui: {this.state.data}

  );

}
}

export default App;

If i use {this.state.data.length} it returns me the size, but when I try to get the data inside the matrix, I can't.


texts:
I am trying to re-compile the ChainlinkEthPrice contract found in the Kaleido Sample Gallery here: https://kaleido-io.github.io/kaleido-samples-gallery/#/kaleido-samples-gallery/chainlink.

Codes as follows:

pragma solidity ^0.4.24;

import "./Chainlinked.sol";

contract ChainlinkEthPrice is Chainlinked {

    struct EthPriceAtBlock
    {
        uint    blockNumber;
        uint    blockTimestamp;
        bytes32 requestId;
        uint256 reportedPrice;
    }

    EthPriceAtBlock[] public ethPrices;
    bytes32 jobId;

    constructor(bytes32 _jobId, address linkTokenAddr, address oracleAddr)
        public
    {
        jobId = _jobId;
        setLinkToken(linkTokenAddr);
        setOracle(oracleAddr);
    }

    function requestEthereumPrice(string _currency)
        public returns (bytes32 requestId)
    {
        ChainlinkLib.Run memory run = newRun(jobId, this, "fulfillEthereumPrice(bytes32,uint256)");
        run.add("url", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD,EUR,JPY");
        run.add("path", _currency);
        run.addInt("times", 100);
        requestId = chainlinkRequest(run, LINK(0));
    }

    function fulfillEthereumPrice(bytes32 _requestId, uint256 _reportedPrice)
        public checkChainlinkFulfillment(_requestId)
    {
        ethPrices.push(EthPriceAtBlock({
            blockNumber: block.number,
            blockTimestamp: block.timestamp,
            requestId: _requestId,
            reportedPrice: _reportedPrice
        }));
       emit RequestEthereumPriceFulfilled(_requestId, _reportedPrice, block.number, block.timestamp);
    }

    event RequestEthereumPriceFulfilled(
        bytes32 indexed requestId,
        uint256 indexed reportedPrice,
        uint256 blockNumber,
        uint256 blockTimestamp
    );

    function getDataCount()
        public view returns (uint length)
    {
        return ethPrices.length;
    }

    function getData(uint idx)
        public view returns (uint blockNumber, uint256 reportedPrice)
    {
        return (ethPrices[idx].blockNumber, ethPrices[idx].reportedPrice);
    }
}

Received the following errors:

browser/chainlink.sol:27:59: TypeError: Invalid type for argument in function call. Invalid implicit conversion from literal_string "fulfillEthereumPrice(bytes32,uint256)" to bytes4 requested.
    ChainlinkLib.Run memory run = newRun(jobId, this, "fulfillEthereumPrice(bytes32,uint256)");
                                                      ^-------------------------------------^

browser/chainlink.sol:31:43: TypeError: Type is not callable
    requestId = chainlinkRequest(run, LINK(0));
                                      ^-----^

browser/chainlink.sol:31:43: TypeError: Invalid type for argument in function call. Invalid implicit conversion from tuple() to uint256 requested.
    requestId = chainlinkRequest(run, LINK(0));
                                      ^-----^

Wondering if anyone can help with this. Thank you!


texts: How to convert a smart contract into a library?

texts:
I have this code which does work.

pragma solidity ^0.4.18;
// this stores keys in state
// a key is a hash of data, eg as used in IPFS
contract DBKeys {

    struct keyStruct {
        bool keyStatus;
    }
    mapping(bytes32=>keyStruct) public zkeys;
    function addZkey( bytes32 newkey) public returns (bool) {
    if (zkeys[newkey].keyStatus) {
        return false; // already added
        }
        zkeys[newkey].keyStatus=true;
        return true;
    }
    function delZkey(bytes32 newkey) public returns (bool) {
        if (zkeys[newkey].keyStatus) {
            delete zkeys[newkey];
            return true;
        }
        return false;
    }
}

I tried to convert into a library which would basically provide the function of building an array of hashes. But I ended up with numerous compile errors.

I understand libraries do not hold any storage but they can define a struct. I saw an example in the docs but that did not delete array members. I want to delete array members to free up storage: I assume that would free up storage.

How is the struct/mapping coded in a library which then also allows the array members to be deleted?


texts: How to sign a erc20 contract call with key using web3

texts:
I am making a call to the Dai contract on the Kovan testnet to facilitate transactions between any two addresses entered as input. I was able to successfully make read calls but I realized I needed to sign transcations using a key for every write call. How do I do this using web3? I have my code below for clarity :

const Web3 = require("web3");
const axios = require('axios');
const WebSocket = require('ws');
const Web3Utils = require('web3-utils');

   if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.WebsocketProvider("wss://kovan.infura.io/ws/v3/d28ff5674c0848ada11af62d25c6a2f1"));
    }
    web3.eth.defaultChain = 'kovan';
    var DaiContract = new web3.eth.Contract('ABI-HERE','0xC4375B7De8af5a38a93548eb8453a498222C4fF2');
$("#button").click(function() {
        DaiContract.methods.transferFrom($("#address1").val(), $("#address2").val(), $("#amount").val()).call()
        .then(function(result){
            $("#result").html("Successfully transferred " + $("amount").val() + " Dai.");
            DaiContract.methods.balanceOf($("#address1").val()).call()
            .then(function(result){
                console.log('Remaining balance in address1 : ' + value);
            })
            .catch(function(error){
                console.error('Error : ' + error);
            });
        })
        .catch(function(error){
            console.error('Error : ' + error);
            $("#result").html("Transfer failed");
        });
    });

Gives the following error :


texts: Calls to RPC sometimes gets Error: Connection refused or URL couldn't be resolved

texts:
I have a backend server that constantly gets logs and parses data from my client node (Clique non-sealer). I restrict the number of calls from my backend server -> client node to 25 at a time.

Is this count too high?
Is there a limit as to how many simultaneous connections the node can have?

FYI, I also have Cloudflare routing to resolve the domain name that goes to the AWS EC2 instance where its hitting the client node. The EC2 instance is also behind an Nginx server as well. I am thinking that the Nginx might be rate limiting or throttling the requests?

Anyone have similar experience with this sort of setup?


texts:
I am really happy to see that arithmetic operations will revert now on overflow and underflow, since the alternative of using SafeMath library was making code quite harder to read.
However, when is the right / safe time to start using Solidity 0.8.x in a production environment based on your experience and previous major releases?
I assume there might be some limitations if we need to deploy our project with other contracts using lower versions, but if we start a clean project without dependencies, is it still too early to start using it? are there any common drivers to decide it (audits, community feedback, established companies already using the new version, etc.)?


texts: How to compute ecrecover parameters in solidity?

texts:
There are many answer which explain how to compute _r, _s, _v with an other language.
But how to compute parameters in solidity itself ? Is there a built-in function like ecrecover ?


texts: Ganache with Metamask is filling command window with "eth_getBlockByNumber" string

texts:
When connecting Metamask with Ganache-Cli, as soon it generates the accounts and keys, the command window is getting filled with "eth_getBlockByNumber" continuously, has anyone else faced the issue?

Thanks.


texts:
By following this tutorial. I have created a private chain based on Proof-of-Authority. Please see my CustomGenesis.json file.

I have started my chain:

> geth --datadir /Users/ethereum/POA/private --unlock 0xd531eab21f883abe0f79103188bfc6468712f409 --mine --rpcaddr 127.0.0.1 --rpcapi eth,net,web3,personal console

INFO [01-16|15:53:58] Unlocked account                         address=0xD531EAb21f883aBe0F79103188bfc6468712f409
INFO [01-16|15:53:58] Transaction pool price threshold updated price=18000000000
INFO [01-16|15:53:58] Starting mining operation
INFO [01-16|15:53:58] Commit new mining work                   number=22 txs=0 uncles=0 elapsed=116.62µs
INFO [01-16|15:53:58] Successfully sealed new block

I observe that: Balance of my each account remains unchanged if there is no transaction on the block. If there is a transaction, authorities' balances, slightly increase (I couldn't figure out with what percent each account gain a reward).

Also at each mined block,miner address returns: 0x0000000000000000000000000000000000000000

web3.eth.getBlock(179).miner
"0x0000000000000000000000000000000000000000"

[Q] How does reward mechanism works on Proof-of-Authority consensus? Is there any gas price? Who gains the used GAS via transaction with what percent as a reward on the each block?

Thank you for your valuable time and help.


texts:
I'm attempting to understand how solidity resolves multiple inheritance. As explained in the docs, Solidity uses C3 linearization. The relation between my classes is displayed on the image below:

I want to understand in which order super is working when called from SampleCrowdsale. I ran the C3 linearization algorithm manually as well as using this tool. The results I get:

1) SampleCrowdsale
2) CappedCrowdsale
3) RefundableCrowdsale
4) FinalizableCrowdsale
5) TimedCrowdsale
6) MintedCrowdsale
7) IndividuallyCappedCrowdsale
8) TieredCrowdsale
9) Crowdsale
10) Ownable

Then I tried to confirm my findings empirically. I added a method log to every contract in the inheritance chain, the method fires an event with the contract name. My findings using this method differ from the analytical approach:

1) SampleCrowdsale
2) TieredCrowdsale
3) IndividuallyCappedCrowdsale
4) MintedCrowdsale
5) RefundableCrowdsale
6) FinalizableCrowdsale
7) TimedCrowdsale
8) CappedCrowdsale
9) Crowdsale
10) Ownable

Can anyone explain to me how to solve this?


texts: Keeping Backend databases in sync with blockchain transactions

texts:
I have created a solidity contract to store the states and the data of a Dapp but to power the frontend, I need different view of that data! While I can use solidity as my backend but I don't think it makes much sense to have the complex logic of building the views on user's end! Furthermore, it would require querying 100's of variables to build the UI every time the page is loaded!

So, I have decided to create a backend database in sql/mongodb to power the UI and will use solidity events to keep the backend data in sync with the contract's state changes!

I am interested in knowing if this is the right thing to do or are there any other approaches that I can use to tackle the situation. Furthermore, what's the best way to listen for solidity events!

Do I need to run a ethereum node locally and use node.js to listen to events and make the necessary changes in database whenever there is a new event or are there any other easier options? A Rest api or something?


texts:
The documentation contains, as one of the Data Manipulation built in functions, the function concat(); the example given is
@external
@view
def foo(a: String[5], b: String[5], c: String[5]) -> String[100]
    return concat(a, " ", b, " ", c, "!")

How would I go about replacing (for example) b with the String[5] representation of  a uint256 variable with a value of (for example) 100?


texts: JSON-RPC: TheDao contract returning not null values for not existing methods in the contract

texts:
When using the geth JSON-RPC eth_call to retrieve some ERC20 token contracts symbol and name information, it comes up the case of TheDao contract.
I was expecting to receive a null/empty string like 0x in response to calling the non-existing methods in any contract when using eth_call. But for TheDAO I have noticed I'm getting a 32 bytes word 0x0000000000000000000000000000000000000000000000000000000000000001.

Is it a right assumption to expect a null/empty word when querying non existing methods for any contract? Do other contract returns not empty words for non-existing methods too?

P.S.: this is a call against my local geth node to retrieve name information for TheDAO:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to": "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "data":"0x06fdde03"}, "latest"],"id":<id>}' -H "Content-Type: application/json" http://geth.local.node:8545


texts:
I am trying to assign the value of a matriz to two arrays as follows:

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract ArrayExamples {

    int[][] public matriz;

    // Os dados são recebidos da seguinte forma: [0,0]
    function receive_data(int[] data) public {
        matriz.push(data);
    }

    function teste() public returns (int[] v) {

        int[] x;
        int[] y;

        uint t = matriz.length;

        for(uint i = 0; i < t; i++) {

            x[i] = matriz[i][0];
            y[i] = matriz[i][1];

        }

        return x;
    }

  }

The array is dynamic, but in the example above defaults to an array with two elements. [0.0]

When I assign the values of x and y in for, only the values of y are assigned correctly. x is responsible for taking only the first value from the dynamic array of the matrix and y takes the last value.

When I check the value of x, it appears that he took the last value from the dynamic array, and he should get the first value from the array.

If I enter the following array: [4,5] - both x and y get 5, where x should get 4.


texts: How can I assign the value that I'm fetching using Oraclize to a member in a structure

texts:
I have the following code:

contract CheckBet is usingOraclize {
    struct Weather {
        uint curr_temperature;
        uint high_temperature;
        uint low_temperature;
    }
    Weather weather;

function get_weather_status() payable{
    Log("Oraclize query was sent, waiting for the answer..");
    (oraclize_query("URL","json(http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22).main.temp_min"));

}

//callback function for Oraclize
function __callback(bytes32 _myid, string _result) {
    require (msg.sender == oraclize_cbAddress());
    Log(_result);
    assign_value_to_weather[low_temperature]= parseInt(_result, 2);
}

Please help me out.


texts: How we can integrate truffle with Jenkins?

texts: is it possible to add truffle on Jenkins pipeline?


texts: Why is UTXO model better than Account model?

texts:
According to this I infer that UTXO is better (or at least more secure) than Account model.

  The reason why transactions work this way is because it’s an easier and more secure way of doing it from a programming perspective.

Why is that?


texts: Is it possible to get direct access to a contract?

texts:
All contracts have addresses. Is it, in theory, possible to find the private key of this address and then get access to this contract? Questions if this is possible:

If one gets access to the contract, can they send transactions from this contract? Or even drain the balance of the contract?
What if someone gets access to this contract address before creating the contract itself? This would mean TX already exist in this contract before it is created. Does that have any consequence?

This sounds like a very interesting attack vector to me. Imagine someone creating a contract which attracts a lot of ether. The code in the contract states that the owner cannot drain ether. However, the owner has the private key of this contract and suddenly sends a transaction draining all the ether.

It is claimed that 'contracts have no private key'. But I can create a private key which gives me the same address as the contract. What if I call extcodesize in another contract on msg.sender? What if I send a transaction from the contract and one from the EOA? The creation of a contract should create code in an address and hence extcodesize changes from 0 to nonzero when a contract is created, hence both calls from EOA and contract come from the same source and extcodesize returns nonzero. Hence contracts have private keys.


texts:
I'm trying to sign my raw transaction and each time I'm getting a different signature (r, s). Please help me how to sign transactions properly in C++ OpenSSL. I'm trying the following way but Etherscan doesn't push this transaction because of invalid sender or insufficient funds (I'm sure this is because the signature is invalid). I have a NodeJs example that calculates signatures and for one hash it generates the same signature each time. And one more question - how to get a RecoveryID from the signature to set V variable properly? Thank you

OpenSSL_add_all_algorithms();

const unsigned char* privKey = /* Private Key 32 bytes */;
const char* rlpTx = /* nonce, gas limit etc encoded to RLP */;

const uint8_t c_chainID = 1; // Mainnet

BIGNUM* bn  = BN_bin2bn(privKey, 32, nullptr);
EC_KEY* key = EC_KEY_new_by_curve_name(NID_secp256k1);

EC_KEY_set_private_key(key, bn);

unsigned char* hash = nullptr;
int size = 0;

Keccak256::calcHash(rlpTx, hash, &size);

ECDSA_SIG* sign = ECDSA_do_sign(hash, key);

unsigned char* r = new unsigned char[BN_num_bytes(sign->r)];
unsigned char* s = new unsigned char[BN_num_bytes(sign->s)];
uint8_t        v = c_chainID * 2 + 35;

BN_bn2bin(sign->r, r);
BN_bn2bin(sign->s, s);

ECDSA_SIG_free(sign);
BN_free(bn);
EC_KEY_free(privKey);

delete[] s;
delete[] r;


texts: Problem reading chaindata that generated by ganacha gui

texts:
my intention is to write a script to analysis eth data from scratch.
i run ganache gui in window with about 200 blocks up to now, and i quite sure that chaindata is keep growing big, then i simply run a nodejs script below.
var levelup = require('levelup');
var leveldown = require('leveldown');
var level = require('level');

var db = levelup(leveldown("C:\\Users\\Madx Radicle\\AppData\\Roaming\\Ganache\\workspaces\\TokenZendR\\chaindata"));

var readStream = db.createReadStream({});
readStream.on('data', function (data) {
    console.log(data.key, '=', data.value)
});

and i encounter no output. Next i test to put new random key-value, and i saw output data was appear right away, there i assume that my script was really connected to leveldb.
I need help on this, Thanks in advance.


texts: Where to find the Ethereum wallet contract?

texts: In Mist wallet, there are WALLET CONTRACTS. I can not find it in Github and could somebody tell me the location of the sol code?


texts: Create account via infura - ropsten network

texts:
I connected node with infura via web3js:

 var currentProviderr = new web3.providers.HttpProvider("https://ropsten.infura.io/...");

How to create accounts in infura? How to view them?

web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      infurawallet = accounts[0];
     }

infurawallet is showing undefined...


texts: How to store the balance in a variable when running on client-side?

texts:
Context
I am learning web3 after having written some smart contracts on the Ropsten and Kovan test networks.
I'm trying to simply read the balance of an address and store it in a variable, in order to display it. The next steps would be to add smart contract interactions using a browser wallet such as Metamask.
I'd like to write a script that would run on the client side, one of the motivations being that the website would then be static.
Code and errors
I imported the web3js library with the following line, please tell me if there's a better way:

then, to connect to a provider, I created an Infura account and got a url associated to my project. In order not to display it entirely, I will write it like so
    var url = "https://kovan.infura.io/v3/my_project_id";

As you can see in the following code, I have created an input element where the user would write an address of which it would like to know the balance. When pressing the button, the paragraph should be changed and show the balance (in wei).

    <input type="text" id="address" placeholder="Enter an address here">
    <button onClick="displayBalance()">Get balance</button>

This paragraph would show the balance

The error I get when calling displayBalance() with a valid address in the input element is an Uncaught ReferenceError telling me that balance is not defined. Note that the error is shown on the last line of the function. Also, it is worth to be noted that I managed to obtain a successful result when running each instruction at a time in the browser console. My guess it that the promise hasn't finished running when the next line is executed.


texts: The geth init --datadir node/ genesis.json command generates an empty keystore directory and a geth directory. Its only after running the node that the geth folder is populated with the nodekey. Is it possible to generate the node.key file via the geth init command? Appreciate any help!


texts: Using the RPC, I want to import and delete wallets programmatically without messing with the filesystem.  Anyway to do this?


texts:
Lisk is going to be a full stack DApp development framework for building and distributing decentralized applications. It's currently in the crowdfunding stage but got also added to Microsofts Blockchain-as-a-Service stack.

It advertises that you can build decentralized applications by simply writing Javascript. But since you can also build JS-DApps for Ethereum, I wonder, what's the difference?


texts:
I think I need a second pair of eyes to take a look at this as I can't see what I'm doing wrong :-(

I'm trying to get the bigesst value using a simple function, but the results are not what I'm expecting.

Here is the code...

pragma solidity ^0.4.21;

contract GetBiggest {

uint public val1 = 1;
uint public val2 = 2;
uint public val3 = 3;
uint public val4 = 0;

        function getBiggestValue() public view returns(uint) {

            uint x = val1;

            if(x < val2) {
                    x = val2;

                }

            if(x < val3) {
                    x = val3;

                }

            if(x < val4) {
                    x = val4;

                }

        }

}

I'm expecting the value of 3 to be returned when I call the function, but I get 0

What's up with this?

thanks


texts: Latest Zeppelin SampleCrowdsale.sol token moved outside of contract?

texts:
Really new to Solidity, but I was following this guide: https://blog.zeppelin.solutions/how-to-create-token-and-initial-coin-offering-contracts-using-truffle-openzeppelin-1b7a5dae99b6

Only, I used the latest zeppelin-solidity (1.7.0) which according to this commit, they moved token creation outside the crowdsale contract.

If I have the following TestTokenCrowdsale.sol:

pragma solidity ^0.4.18;

import "zeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "zeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol";
import "zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "zeppelin-solidity/contracts/token/ERC20/MintableToken.sol";

/**
 * @title SampleCrowdsaleToken
 * @dev Very simple ERC20 Token that can be minted.
 * It is meant to be used in a crowdsale contract.
 */
contract SampleCrowdsaleToken is MintableToken {

  string public constant name = "Sample Crowdsale Token"; // solium-disable-line uppercase
  string public constant symbol = "SCT"; // solium-disable-line uppercase
  uint8 public constant decimals = 18; // solium-disable-line uppercase

}

/**
 * @title SampleCrowdsale
 * @dev This is an example of a fully fledged crowdsale.
 * The way to add new features to a base crowdsale is by multiple inheritance.
 * In this example we are providing following extensions:
 * CappedCrowdsale - sets a max boundary for raised funds
 * RefundableCrowdsale - set a min goal to be reached and returns funds if it's not met
 *
 * After adding multiple features it's good practice to run integration tests
 * to ensure that subcontracts works together as intended.
 */
contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale {

  function SampleCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, MintableToken _token, uint256 _goal) public
    Crowdsale(_rate, _wallet, _token)
    CappedCrowdsale(_cap)
    TimedCrowdsale(_openingTime, _closingTime)
    RefundableCrowdsale(_goal)
  {
    //As goal needs to be met for a successful crowdsale
    //the value needs to less or equal than a cap which is limit for accepted funds
    require(_goal <= _cap);
  }

}

Here's my 2_deploy_contracts.js:

const SampleCrowdsale = artifacts.require(“./TestTokenCrowdsale.sol”)

module.exports = function(deployer, network, accounts) {
    const openingTime = Date.now()/1000|0 + 120;
    const closingTime = openingTime + (3600 * 1 * 1); // *1 hour *1 days
    const ethRate = new web3.BigNumber(100);
    const wallet = accounts[0];
    const cap = 100000000000000000000;
    const goal = 200000000000000000000;

deployer.deploy(SampleCrowdsale, openingTime, closingTime, ethRate, wallet, cap, goal);
};

When I run turffle migrate --reset, I get the following error:

~/src/test-token $ truffle migrate --reset
Using network 'development'.

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x2e09c8647174d6fd5b26e2269d3d725b75d44881f27ad735323aca8fd19a517f
  Migrations: 0xecfcab0a285d3380e488a39b4bb21e777f8a4eac
Saving successful migration to network...
  ... 0xd656595c57159a378d57439d8f0297d077c03ec39adfdac561dbfb8260758db3
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying SampleCrowdsale...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: SampleCrowdsale contract constructor expected 7 arguments, received 6
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:390:1
    at new Promise (<anonymous>)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:374:1
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)

What am I missing?


texts: Calculate how much space can be saved after self-destructing a contract

texts:
I want to do some brief analysis to quantify how much one could free when self-destructing a contract. How could I calculate how much space can nodes save when selfdestructing a given contract?

I understand that "nothing on the blockchain is destroyed", but I also understand that there is no need to locally store the state of a contract if this contract is now self-destructed. No-one can call this contract onward and the future state trie will forever be unaffected by this contract after the self-destruction, since the state of the contract can't change (apart from ETH sent to it) nor be called. In addition, there is an incentive built in the SELFDESTRUCT upcode (i.e. negative gas) that doesn't really make sense if nodes gain nothing from having contracts destroyed. Why create an incentive for something that would have no benifits? There must be a potential benefit from freeing contracts.

Is this dealt at the client level? If so, I assume different clients might deal with self-destructed contracts differently. In either case, how can I calculate this?

Examples:
Looking at the KyberNetwork crowdsale contract,
 it's clear that this contract will never be used again, a similar situation in most token sale contract. How much space could nodes free by not storing the state of this contract?


texts: Migrating 2 contracts in one Contract.sol script using 'truffle migrate'

texts:
I have 2 contracts in 1 .sol file and when I run 'truffle migrate', it tells me that it has deployed 1 of the contracts and given me an additional error:

  Blockquote

Invalid number of parameters for "undefined". Got 0 expected 4!

Here is my 2_intitail_migration.js file

const AuctionBox = artifacts.require("AuctionBox");
const Auction = artifacts.require("Auction");

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

How can I got about it?


texts: Fetching stored values for use in function logic

texts:
Are there any benefits from fetching stored data into other functions by calling a function to call a private variable, instead of calling the private variable directly? What is best practices?

example

 contract PlayerExample {

    uint private maximumPlayers

    uint private players;

    function playersCount() public view returns (uint) {
        return players;
    }

    function playerSlotsLeft() public view returns (uint) {
        return (maximumPlayers - players);
        //or is it better to do
        //return (maximumPlayers - playersCount());
    }
 }


texts:
I unboxed petdapp and done some editing where I need to import bcrypt-nodejs in app.js and used following steps.

npm install bcrypt-nodejs --save

npm install require --save

app.js

var bcrypt = require('bcrypt-nodejs)

While executing application it gives an error Cannot find module bcrypt-nodejs.

Do I need to specify the path anywhere?

bs-config.json is as follows:

{
 "server": {
"baseDir": ["./src", "./build/contracts"]
}
}

I added ./node_modules under "baseDir" along with folder path src and contract. It did not resolved the issue.

I tried package aes256 module and get same error with warning as :

[ts] File is a CommonJS module; it may be converted to an ES6 module.
[ts]
Could not find a declaration file for module 'aes256'. '/home/Documents/Dapp/node_modules/aes256/index.js' implicitly has an 'any' type.
  Try `npm install @types/aes256` if it exists or add a new declaration (.d.ts) file containing `declare module 'aes256';`

I tried another method : import { default as aes } from 'aes256';. Still same issue.


texts: Error Testing on Remix: Note: The constructor should be payable if you send value

texts:
I'm running into some trouble testing in Remix. The contribute function doesn't give me an input filed when I deploy the campaign. I want to test if the contribute function meets the minimumContribution criteria.

pragma solidity ^0.4.17;

contract CampaignFactory {

    address[] public deployedCampaigns;

    function createCampaign(string description, uint minimumContribution, string campaignCategory, string endDate) public {
        address newlyCreatedCampaign = new Campaign(description, minimumContribution, campaignCategory, endDate, msg.sender);
        deployedCampaigns.push(newlyCreatedCampaign);
    }

    function getDeployedCampaigns() public view returns (address[]) {
        return deployedCampaigns;
    } }

contract Campaign {

    struct NewCampaignType {
        string description;
        uint minimumContribution;
        string campaignCategory;
        string endDate;
        address managerAddress;
    }

    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    mapping(address => NewCampaignType) public campaigns;
    Request[] public requests;
    mapping(address => bool) public approvers;
    uint public approversCount;
    address public currentManagerAddress;

    modifier restricted() {
        require(msg.sender == campaigns[currentManagerAddress].managerAddress);
        _;
    }

    function Campaign(string description, uint minimumContribution, string campaignCategory, string endDate, address managerAddress) public {
        NewCampaignType memory createCampaign = NewCampaignType({
            description: description,
            minimumContribution: minimumContribution,
            campaignCategory: campaignCategory,
            endDate: endDate,
            managerAddress: managerAddress
        });
        campaigns[managerAddress] = createCampaign;
    }

    function contribute() public payable {
        require(msg.value > campaigns[currentManagerAddress].minimumContribution);
        approvers[msg.sender] = true;
        approversCount++;
    }

    function createRequest(string description, uint value, address recipient) public restricted {
        Request memory newRequest = Request({
           description: description,
           value: value,
           recipient: recipient,
           complete: false,
           approvalCount: 0
        });

        requests.push(newRequest);
    }

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

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;
    }

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

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
    }

    function setCurrentManager(address managerAddress) public {
        currentManagerAddress = managerAddress;
    }

    function getSummary() public view returns (
      uint, uint, uint, uint, address
      ) {
        return (
          campaigns[currentManagerAddress].minimumContribution,
          this.balance,
          requests.length,
          approversCount,
          campaigns[currentManagerAddress].managerAddress
        );
    }

    function getRequestsCount() public view returns (uint) {
        return requests.length;
    } }


texts: Getting Blockchain Domains From Transaction Hashes

texts:
I am compiling a list of some blockchain domains (.eth, .crypto, etc.) and was wondering what would be the best approach.

My strategy is to take something like this:

https://etherscan.io/address/0xb485d89aba096fc9f117fa28b80dc8aac7971049

which is the wallet for Unstoppable Domains, who are one of the blockchain domain registrars. I understand that their wallet doesn't have all of the blockchain domains, as there are other registrars, but it's a good start. I can write up a scraper to grap the transaction hash for each of these transactions, but here's where I'm stuck:

Would it even be possible to pull the domains from the transaction hash if decoded? If not, is there any other method that might work? If it is possible, then how might I go about doing that? I've tried so many things in Golang, which is what I would prefer to use, but to no avail. I've already tried all of the stuff in go-ethereum, but the posts on here regarding decoding transaction hashes in go-ethereum are outdated, so you have to dig through the current source code and try and see how to decode the data. Is there also a JavaScript solution? Would web3js do what I'm looking for? Again, I would prefer to use Golang, but I'll use whatever is necessary.

In short, how do I decode a transaction hash in Golang? (Or JS if necessary)

Thanks for your time!


texts: What were the key assumptions and analyses that went into setting Ethereum's gas price?

texts:
Frontier was launched with a default gas price of 0.05e12 wei.  In Homestead, the default was reduced to 0.02e12 wei.

If this gas price is too low and operations on Ethereum are too cheap, for example, if a single ether can run all the dApps and contracts a user could ever want in their lifetime, then demand for ether will be low and there is little rational reason for its price to increase.

If the price is too high and operations are expensive, people will not use dApps, and also little reason for the price to increase.

What assumptions and analyses suggest what an optimal gas price is, and how much does the current gas price deviate from it?


texts: How do I deposit an Ether amount to the smart contract function, namely deposit ? (Metamask version 0.20.7)

texts:
I have a problem with using the deposit () function on a smart contract. How do you use metamask 0.20.7 ?

const contractInstance = web3.eth.contract(contractAbi).at(contractAddress);
contractInstance.deposit({ from: web3.eth.accounts[0], value: web3.toHex(web3.toWei(0.1, 'ether'))}, function(err, result){ console.log(result); } );

How is it so that a user can only click and automatically release it in metamask with a number of 0.1 ETH ? I can't spend that amount when using it, but only get 0 ETH from it.

Image Here


texts: Make a struct member optional when initializing struct

texts:
struct Petition {
    uint id;
    string name;
    string description;
    uint voteFor;
    uint voteAgainst;
    address[] addressOfVotedForUsers;
    address[] addressOfVotedAgainstUsers;
    mapping(address=>bool) usersVotedFor;
    mapping(address=>bool) usersVotedAgainst;
}

function addPetition(string memory _name, string memory _desc) public {
    petitions[petitionCount] = Petition(petitionCount,_name,_desc,0,0);
    petitionCount++;
}

s/VoteCast.sol:42:34: TypeError: Wrong argument count for struct constructor: 5 arguments given but expected 7. Members that have to be skipped in memory: usersVotedAgainst usersVotedFor
  petitions[petitionCount] = Petition(petitionCount,_name,_desc,0,0);

I have a struct where I don't want the value of the address[] arrays to be intialised. But I get a error expected 7 arguments, instead got 5. Is there any work around for this?


texts: How to decode input data from a transaction?

texts:
I'm sending a transaction to an account with some data with the following command:

eth.sendTransaction({from:eth.accounts[0],to:eth.accounts[1],value:web3.toWei(1,"ether"),data:web3.toHex("http://localhost:8545")})

I'm getting this result, by extracting the log of the transaction (running with testRPC):

   tx hash         : 0xf654aee5ed23f9aeebd2d73c69c7b9c21a4862787966d09bcb09ed44efc1f252
   nonce           : 0
   blockHash       : 0x6ff8a0e3ac606abd2ede4331b82af52a0daa98448025051fb3b3d50f749aa49f
   blockNumber     : 1
   transactionIndex: 0
   from            : 0xf64918835bc21dff9e8210a807b3964d1be35dd0
   to              : 0x08f986b7535c2b72687d3cb193135f1c6e27c336
   value           : 1000000000000000000
   time            : 1483614904 Thu, 05 Jan 2017 11:15:04 GMT
   gasPrice        : 1
   gas             : 90000
   input           : 0x687474703a2f2f6c6f63616c686f73743a38353435

I want to decode the last line "input" and try to get "http://localhost:8545".
I saw some work similar to my question here and here, but this is not working in my case. Moreover, i tried .toString('hex')) but it remains as hex.

How can I achieve this?

Thanks in advance


texts: working with balance management in a game

texts:
I'm working in a online game project, Where users will deposit ETH into their account for playing game.

My problem is, Once a user deposit some ETH into his wallet. Example 0.10 ETH

So how we can track this balance and update user balance into our database, And allow user to play game. So while playing game user's balance will deduct or increase from our database balance not from directly their ETH wallet built into our website.

So how is it possible to track users deposit only once, So same deposit amount can not be grabbed by our code?

How peoples do this kind of stuff?


texts: Solidity public variable getter call doesn't return

texts:
I have deployed a very basic solidity contract (pragma solidity^0.4.0) to Rinkeby. When I call the getters on my state variables, nothing is returned and I do not understand why. To compile the contract I'm using "solc": "^0.4.25"

Using Remix to test, the call to the getter works locally without issue. However, the call doesn't work on my contract on Rinkeby.

Here is my solidity code...

pragma solidity^0.4.0;

contract Contest {
    address public manager;
    uint public submissionCost;
    uint public votesPerSubmission;

    constructor (uint _submissionCost, uint _votesPerSubmission) public {
        manager = msg.sender;
        submissionCost = _submissionCost;
        votesPerSubmission = _votesPerSubmission;
    }

    modifier restricted() {
        require(msg.sender == manager, "Not authorized.");
        _;
    }

    function adjustSubmissionCost(uint newCost) public restricted {
        submissionCost = newCost;
    }

    function adjustVotesPerSubmission(uint newVotes) public {
        votesPerSubmission = newVotes;
    }

    function getManager() public view returns (address) {
        return manager;
    }
}

The address of the deployed contract on Rinkeby is

0x0f1828ED7Be0232fd153218EFb2fA78A09c09b53
https://rinkeby.etherscan.io/address/0x0f1828ED7Be0232fd153218EFb2fA78A09c09b53

When calling any of the public variables from Remix, I expect a return value, however I only receive the message call to Contest.manager in the Remix console and nothing more.

I get the same behavior in my web3 dapp, with zero return when I try...

await Contest.methods.manager().call()

When I submit a transaction on Remix this also hangs on pending... Is it a versioning issue? Can't figure it out...


texts: Connection between peers never happen on custom blockchain

texts:
My app connects and mine the same blokchain on every instance, it uses the same genesis.json and network ids.

Genesis: https://github.com/AugustoL/OpenContent/blob/master/genesis.json

Web3 service that connects using the same network id: https://github.com/AugustoL/OpenContent/blob/master/js/services/web3.js

When I run it on two different computers the existent blockchain isnt recognized. SO it starts mining two different blockchains with the same genesis and network id :S

What is the error? What im missing? I have been reading a lot and its supposed to work.


texts: Writing to storage string vs bytes for token parameters

texts:
I'm wondering why string is used to define token parameters such as name, and symbol? Why can't I use any form of bytes such as bytes8 etc.

I understand that it's a public parameter and non-devs will be able to check up the name etc in string encoded readable format but I want to use bytes where ever possible to decrease gas-costs.

How would I go about describing following line in bytes format? string constant public name = "Nowsy Token"


texts: Ethereum resources to build a decentralized application

texts:
I was searching the dApp Decentralized application
 topic and many resources recommend Ethereum to build a dapp. What I plan to do is to build a decentralized mobile app with a distributed database. I have a Qt/QML code that I like to base my app on it but python/kivy and react native are also options. I have seen Ethereum clients but don't know whether i have to use them to build the network or something else. Please provide some resources (Especially related books) for those who want to build a network on top of Ethereum.


texts: How to calculate the costs of storing data in a contract?

texts:
Lets say, I want to create a smart contract that can receive a record of data per hours, e.g. hourly rates of ETH/EUR. These data would be stored in an array.

What would each transaction cost me and how can I estimate these costs?


texts: Does Ethereum support bilinear pairing calculation?

texts: Ethereum pre-compiled x08 address can do pairing checks, but if I just want the smart contract to calculate a pairing, such as e(a,b), instead of checking whether the pairing e(a,b) is equal to e(c,d), what should I do？


texts: Detect if var is inside a variable range

texts:
I need some help.

I would like to know the best way to detect if a var is inside a range knowing that the range is dynamic, it can change (the owner could change the range).

e.g.

v = 4

is v inside any range in the list?

0-29 > yes
30-100 > no
101- 2 ** 256 > no

In the future, maybe I would need to add/remove ranges.

Any help?
Thanks.


texts: How to call a write function of contract from Dapp?

texts:
I have created a smart contract in which a "stop()" function should be called once a deadline is reached. Dapp is keeping check of the deadline and as soon as the deadline is reached I need to call this function, the function itself actually sends some amount of ethers to 3 different addresses.

Here is the stop function:

function stop() public{
    require(now > deadline, "deadline expired");
    require(address(this).balance >= 1 ether, "contract doesnot have sufficient ethers");
   // quickSort(top, 0, top.length-1);
   for(uint i = 0; i < registeredStudents; i++)
        sort(i);
    // distribute the tokens
    for(uint i = 0; i <= 2; i++){
        students[top[i]].wallet.transfer((3-i) * 100000000000000000);
        emit Transferred(students[top[i]].wallet, top[i], 3-i);
        students[top[i]].totalBalance += (3-i) * 100000000000000000;
    }
}

How can I call this function from the Dapp? I tried using call() but it is not working and I tried send() too but send() wants me to give from address as well, which I dont know should be what in this case.

Please suggest. It is urgent task.
Thanks in advance.


texts:
Is it possible to connect the nodes that are listed on ethernodes.org

I chose one of the listed nodes and try to connect with web3 but I get connection not open on send() error.

const Web3 = require("web3")
const web3 = new Web3(new Web3.providers.WebsocketProvider("wss://185.117.74.46:48346"))

const getBlockNumber = async() => {
    try{
        const r = await web3.eth.getBlockNumber()
        console.log(r)
    }catch(error) {
        console.log(error)
    }
}
getBlockNumber()

Is there any way to connect a public node?


texts:
I'm running ethereum node with this command

  geth --fast --rpc --rpcaddr 127.0.0.1 --rpcport 8545 --rpccorsdomain * --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3

And I've created an ethereum address, but and when I deposit some money to this ethereum address from external wallet, money did not arrrive into the new wallet address.

What could be missing?

Blockchain is fully downloaded with above command and syncing is upto date.


texts: why could I not transfer by using msg.sender instead of passing address as an argument to the function?

texts:
The function withdraw() is not working, it can not transfer. But the function withdraw2() is working. What's wrong with my code?

pragma solidity ^0.4.18;

contract SupportPay4 {

    function() public payable {

    }

    function deposit() public payable {

    }

    function withdraw() public {
        msg.sender.transfer(getBalance());
    }

    function withdraw2(address addr) public {
        addr.transfer(getBalance());
    }

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


texts: Use modifier function to create heirachy of smart contracts

texts:
I have 3 contracts that I want to implement. The contracts are master , admin and customer. So the master contract is initiated by a single person, the owner of the private chain (based on geth). The admin contract provides access to certain addresses. These admin instances are created by the master. I am using a modifier to ensure this. The customer contract can be interacted with only by the admin and master contract.

I have mapped these addresses to accounts (with username and pw) stored on my local Redis db. Snipper of my contract structure is below:

Master Contract

contract MasterContract{
    bool public state = false;
    address public masterAddress;
    bool permCheck;

    // ACL
    // Subject(Role) - Object/Subject - permission - On/Off
    mapping (uint => mapping(uint => perm)) public acl;

    // Init Function
    function masterContractInit(string name,string detail){
      if(msg.sender!="0x0"){
        throw;
      }else{
        masterAddress = msg.sender;
      }
    }

    modifier onlyMasterAccess{
      if (msg.sender == masterAddress) _
      else throw;
    }
}

The admin contract

contract AdminContract{
  bool state=false;
  struct Admin{
      bool status;
      string name;
  }
  mapping (address => admin ) public admins;

  // How to reference this masterAddress?
  modifier checkMasterAndAdminAccess{
    if (msg.sender == masterAddress || admins[msg.sender].status) _
    else throw;
  }

  function initAdminContract() onlyMasterAccess{
    state = true;
  }

  function addAdmin(address addr, string name) onlyMasterAccess{
    admins[addr]=Admin(true, name);
  }

  function revokeAdmin(address addr) onlyMasterAccess{
    if(addr!="0x0"){
      throw;
    }else{
      admins[addr].status = false;
    }
  }
}

Customer contract

contract Customer{
  bool public state = false;

  function initCustomerContract() onlyMasterAccess{
    state = true;
  }

  function foo() checkMasterAndAdminAccess{
    // Do something here
    // only admin or master can call this function
  }

  function bar(){
    // Do something, but allow others to modify this
  }
}

Now I need to further understand how to combine these contracts and reference the master and admin address in customer contract to use the modifier checkMasterAndAdminAccess. Ideally when compiling into ABI and using it in my Nodejs app, I would want to place these contracts into separate files as they will become massive.

Is this a recommended practice?

There will only be one instance of master contract controlled by only person (so only one address will have access to it). The other contracts may be instantiated more than once

Can I get some guidance on how to achieve the above.


texts: Can I call someone else's public function/contract

texts:
Still new and learning. Forgive me if this is a stupid question.

Since all contracts are uploaded to the same blockchain, if I wanted, could I use someone else's public contract in my own front-end app?

Does it work that way?


texts:
I am a newbie with blockchain and I have a few questions please, I've already googled but I have misunderstood some points:

How data is stored in the block in blockchain? in bit format, text or
other?
What is the benefit of the block less?
Can we store in the same block unrelated transactions?
How to explain censorship-resistant for blockchain?


texts: Can I write a Dapp in Javascript and just write the smart contract in Solidity?

texts: Can I make the Dapp in Javascript and just write the smart contract in Solidity?


texts: This code is only displaying 0 output on the input of either 15 or any number why is that so? Is there something wrong with the code?

texts:
pragma solidity ^0.4.24;

contract sec
{

    uint age= 15;
    uint agePer;

    modifier onlyPer (){

        if(age==agePer)
        {
            _;
        }
    }

    function getage(uint agep) onlyPer() public returns (uint){

        agePer=agep;
        return agePer;
    }
}


texts: Location of parity blockchain in Windows

texts: Where is the blockchain used by parity located in Windows? I get a crash during the database migration after a parity upgrade and would like to start from scratch.


texts: Unable to print event without JSONstringify

texts:
I am trying to understand the difference among following cases while printing the event:
At web3.js

listenToEvent: function(){
    Contract.deployed().then(function(instance){
      instance.HelloWorld().watch(function(error, event){
        document.getElementById("demo").innerHTML += JSON.stringify(event);

        console.log(event); //1. It is not working
        console.log(event.args); // 2. It is giving all arguments
        console.log(event.args.name); // 3. It is not working

      });
    });
  },

console.log(event); //1. It is not working
console.log(event.args); // 2. It is giving all arguments
console.log(event.args.name); // 3. It is not working; here name is the first argument in the event.

My question is If the object can't be print then why it is working for 2nd condition and if it is working then why it is failing for 3rd.

To access the arguments we can use this:
console.log(JSON.stringify(event.args.name));

While printing the event
console.log(JSON.stringify(event));
It gives the transaction details too, how to get that?

Appreciate any help in advance.


texts: The question is i want to create new account per user on the ethereum blockchain. I want to display a form where in the user will enter information and on clicking register, his account should be created. How can this be done?


texts:
I have two contracts. One inherits a function that gets the value to be paid by the second one.

If I remove the 'is Reference' and replace the values from the external function, the code pays, without problems.

Am I doing something wrong here?

contract Reference {
    function getAmount(string) public returns(uint);
}

contract Payment is Reference{
    uint Value;
    address sender=msg.sender;// for the suicide

    function Payment (Reference _address, address _receiver, string _NR) payable {

        Value = _address.getAmount(_NR);

        if(!_receiver.send(Value)) {//pay
          throw;
        }
    }

    //receive remainder of the money allocated to the contract
    function kill(){
        if (msg.sender == sender)
            suicide(sender);
    }
}

Thanks for any feedback!

Addition: If I define the values (amount to pay, recipient address) in the payment contract manually it doesn't get mined - this is as long as it still inherits from the other contract...

The extrnal function works fine...


texts:
The basic download instructions on the Ethereum repo are producing this brew error: Error: No available formula with the name "ethereum".

Things I've done:

brew update
brew upgrade
brew tap ethereum/ethereum
brew install ethereum

Any suggestions or am I missing something?


texts: Web3 not connecting with ropsten through infura

texts:
so my truffle based application is communicating fine with my smart contracts on my private network, ganache and ganache-cli.

I then deployed it to ropsten where i used the endpoint i got from infura.io as my api-key

Now if i use that same api-key(endpoint) as my httpProvider, everything stops working but if i turn on metamask, it starts working again so i figured it's most likely my connection with ropsten that went wrong.

Here's my script for connecting to ropsten:

import Vue from 'vue'
import App from './App'
import Web3 from 'web3'
import router from './router'

Vue.config.productionTip = false

window.addEventListener('load', function () {
  if (typeof web3 !== 'undefined') {
    console.log('Web3 injected browser: OK.')
    window.web3 = new Web3(window.web3.currentProvider)
  } else {
    console.log('Web3 injected browser: Fail. You should consider trying MetaMask.')
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/<My-API-Key>'));
  }
  console.log(window.web3.eth.accounts) // returns an empty array, but it's meant to contain the address in that wallet
  /* eslint-disable no-new */
  new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
  })
})

Please help me figure out what i'm doing wrong that's making my connection to ropsten not work.

Truffle - 5.0.4

Node - 10.15.0

Web3 - 0.20.6

Windows 10


texts: Can I get back lost ETH in splitting attempt?

texts:
Please can I have some info if I can get my lost ether back.

I had eth in presale wallet. I imported the presale json file on Ethereum Wallet 0.8.9.

That created a new wallet with correct amount of ether form presale wallet.

Than I have imported json file on ETC Wallet chrome extension. I recieved the same amount of ETC. Than I have sent that ETC on Poloniex ETC address. After that my ETH disappeared from Ethereum wallet.

Can anything be done to retrieve eth?

EDIT:
got ETH later along with ETC on Polo. interesting


texts: How does The DAO transfers balances to another contract?

texts:
Imagine The DAO wants to change it's source code.

There is a proposal for DAO to call contract creation with new code for the DAO. After such proposal all ether are transferred to new contract.

But what happens to the DAO token balances owned by users. Are they transferred to another contract? Or since that moment there are two different versions of DAO ?


texts: If I have an exported binary copy of the block chain how can I import it but to a different directory than the default location? For example if I run geth import /mnt/blockchains/ETH/eth.bak it will begin importing to the default location if I run geth --datadir "/mnt/blockchains/ETH/" it will begin syncing the blockchain from scratch.


texts: Or if Mist is simply starting Geth, how can I tell Mist to start Geth in RPC mode?


texts: Is there any case where a contract will use gas?

texts:
I was wondering, why and when is it important to fund your contract with ether?
Is this really only ever if you want to send ether from your contract?

Does a contract ever need to pay gas for something rather than the caller?

Thanks!


texts:
I use truffle for solidity development.

I have this solidity code:

pragma solidity ^0.4.4;

contract MetaCoin {
    uint256 public totalSupply;

    function MetaCoin() {
        totalSupply = 1000;
    }

    function addOne() public returns (uint256 newTotalSupply)
    {
        totalSupply = totalSupply + 1;
        return totalSupply;
    }
}

And this HTML+javascript code to interact with the contract after doing truffle migrate, having testrpc running on port 8545:

<!doctype html>
<html lang="en">
  <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
  <script type="text/javascript" src="./bower_components/web3/dist/web3.min.js"></script>
  <script type="text/javascript" src="./bower_components/jquery/dist/jquery.js"></script>
  <script type="text/javascript" src="./javascript/truffle-contract/truffle-contract.js"></script>
  <script>
  window.onload = function() {
    var url = "http://localhost:8545";
    if (typeof web3 !== 'undefined') {
      web3 = new Web3(web3.currentProvider);
    } else {
      web3 = new Web3(new Web3.providers.HttpProvider(url));
    }
    $.getJSON("./contracts/MetaCoin.json", function(MetaCoin_json) {
      var MyContract = TruffleContract( MetaCoin_json );
      MyContract.setProvider(new Web3.providers.HttpProvider(url));
      MyContract.deployed().then(function(instance) {
        contract=instance;
        return contract.totalSupply.call();
      }).then( function(totalSupply) {
        console.log("totalSupply from init " + totalSupply);
        return contract.addOne.call();
      }).then( function(totalSupplyIncremented) {
        console.log("Value returned " + totalSupplyIncremented);
        return contract.totalSupply.call();
      }).then( function(updatedTotalSupply) {
        console.log("totalSupply after adding one " + updatedTotalSupply);
      });
    })
  };
</script>

I was expecting to have an output like:

totalSupply from init 1000
Value returned 1001
totalSupply after adding one 1001

so at the beginning I have a total supply of 1000. I add 1 so I have 1001, and the new total supply is 1001

But instead I got:

totalSupply from init 1000
Value returned 1001
totalSupply after adding one 1000

Looks like my addOne() method did not update the public totalSupply var. And I can not see why.


texts: How to send transaction using ethereum contract?

texts:
I made ethereum contract according to sample code. And then generated ethereum wallet. The abstract contract is as follow.

pragma solidity ^0.4.18;

/**
 * @title ERC20Basic
 * @dev Simpler version of ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/179
 */
contract ERC20Basic {
  function totalSupply() public view returns (uint256);
  function balanceOf(address who) public view returns (uint256);
  function transfer(address to, uint256 value) public returns (bool);
  event Transfer(address indexed from, address indexed to, uint256 value);
}

Now I want to send ether to other using this contract. How to send transaction using contract? plz help me.


texts:
Does anyone know how fast I can deploy to the Ropsten network?

I am using the following command:

truffle migrate --network ropsten

and I have an instance of geth running.

In the geth console, when I run txpool.status (before I run the truffle migrate command), together with the txpool.status command, I get the following output:

> txpool.status
{
  pending: 1991,
  queued: 0
}

Do I have to wait until all 1991 transactions are completed before my contract gets deployed/migrated?

Thank you.


texts: ERC721 how does tokenOfOwnerByIndex() list tokens owned by a user?

texts:
Per eip-721, there's an optional "enumeration extension". So what I did was I called balanceOf to get the number of tokens owned by the account and called tokenOfOwnerByIndex in a loop to get each owned token ID.

for(var i = 0; i < balance.toNumber(); i++) {
  myERC721Token.tokenOfOwnerByIndex.call(web3.eth.accounts[0], i)
  .then((id) => { ... });
}

As a result, it actually listed tokens owned by a user.

However, I am not sure how the code actually works because tokenOfOwnerByIndex returns mapping variable ownedTokens, but I've never assigned any value to ownedTokens! But how can it still return the tokens of an owner? FYI, I mint the token like below.

import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";

contract MyERC721Token is ERC721Token {

  function createNewToken(...) {
    _mint(msg.sender, index);
  }
}

If you take a look at openzeppelin's contract, _mint that I called here never assigns any value to ownedTokens. Can anyone see the relationships between the contracts that I can find out why tokenOfOwnerByIndex is working for me?


texts: Why this delegatecall attack not working?

texts:
I am confused by this simple contract. The main purpose is to bypass the OnlyContract() modifier.
Victim contract.
pragma solidity 0.7.6;

contract Victim {

    modifier OnlyContract() {
        require(msg.sender == address(this), "You are not this contract");
        _;
    }

    function withdraw(uint256 amount) external {
        (bool success,) = msg.sender.call{value : amount}("");
        require(success, "Withdraw failed");
    }

    function ContractWithdraw(address payable to_, uint256 value) external OnlyContract {
        require(address(this).balance >= value, "No funds");
        (bool success,) = to_.call{value : value}("");
        require(success, "Contract Withdraw failed");
    }
}

Malicious Contract
pragma solidity 0.7.6;

contract Malicious {
    address payable owner;

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

    receive() external payable {
        address x = address(0x0000000000);
        (bool success, bytes memory data) = x.delegatecall(abi.encodeWithSignature("ContractWithdraw(address,uint256)", address(this), 1000000000000000000));
    }

    function Attack() public {
        x.withdraw();
    }

    function withdraw_all() public {
        owner.transfer(address(this).balance);
    }
}

The flow is like this:

Attacker call Attack() on Malicious contract.
Victim contract send ETH to Malicious contract.
Victim contract go into Malicious fallback contract and delegatecall to his own contract.
From here, msg.sender delegatecall has changed to Victim contract.

But in reality, the delegate call transaction reverted.
I think I've bypassed the OnlyContract() modifier.
Why did the attack fail?


texts: How do I know the command that output Total Ether Supply?

texts:
I can see the amount of Ether in https://etherscan.io/stats/supply

More detail can be seen a pre-sale amount, Mining Block amount, Mining Uncle amount.

Is there a JSON-RPC or geth command can be seen this?
Even as I see myself surrounded by Ethereum wiki, any community, there is no in sight.


texts: What happens if transaction runs out of gas before transaction completes?

texts:
As gas cost can only be estimated until the transaction is executed against the actual contract state at the time of execution on the blockchain, what happens if transaction runs out of gas before the transaction is completed?

Presumably the contract rolls back as if the transaction never happened.

If this is the case, then what prevents malicious users from spamming Ethereum nodes with complex transactions that do not carry sufficient funds?


texts: Writing an array with a for loop doesn't work

texts:
I am trying to fill an array of cards in a deck with values from 0 to 51 using an array. It doesn't seem to work and I always end up with an empty array. Is this an issue with gas even though I experimented with fairly big values for gas limit. Here is my code:

contract Blackjack {

   uint[52] public deck;

   function Blackjack() public {

       for (uint i = 0; i < 52; i++) {
            deck[i] = i;
       }
    }
}

Edit: I just realized that you need to give a parameter when calling the free getter for deck in remix. I was expecting it would return the whole array so this isn't really an issue. Thanks to everyone who helped out and sorry to have wasted your time.


texts: recommended datatype for "data" in ethereum transaction

texts:
I am sending data with my transaction by using following way

var tx = {from: eth.coinbase, to:eth.accounts[1], value: web3.toWei(1, "ether"),data:web3.toHex("Test Data")}

personal.sendTransaction(tx, "password")

As we can see I am using simple string in data which is converted to hex,
I have some questions around it

Is there any recommended datatype to use it within data field
Is there any standard way to put JSON data in that data field.

(note:currently I am sending JSON data by manually converting the data to JSON string by following way
data:web3.toHex("{\"key1\":\"Data1\",\"key2\":\"Data2\"}"))


texts: Need an example to make a state variable reactive in Meteor

texts:
I'm having trouble properly understanding Meteor's reactivity and it's relation to contracts.

I've included the Ethereum Meteor packages ethereum:web3 and ethereum:blocks and read that EthBlocks.latest is reactive but my question is, how do I make a contract's function return reactive also? Am I suppose to hook into EthBlocks.latest somehow to run custom callbacks?

In the following DAPP I have a basic getter/setter contract (pingpong.sol), a Meteor template and associated template helpers and events.

Example:

pingpong.sol

contract pingpong {

    string public pong;
    // accessor function:
    // function pong() { return pong; }

    function ping (string val) {
        pong = val;
    }
}

main.html

  <title>pingpong</title>

Ethereum DAPP Reactivity

  {{> pingpong}}

<Template name="pingpong">

PONG - {{pong}}

  <form class="set-pong">
    <input type="text" name="text" placeholder="Type new pong value"/>
  </form>
</Template>

main.js

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

// private chain
web3 = new Web3(new    Web3.providers.HttpProvider('http://localhost:8546'));

contract = web3.eth.contract([{"constant":false,"inputs":[{"name":"val","type":"string"}],"name":"ping","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"pong","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]);

ppInst = contract.at("0x8c3d23c31de790ac60a483ba47ea1b7fea08d67e");

EthBlocks.init();

Template.pingpong.onCreated(function pongCreated() {
    this.pong = new ReactiveVar(ppInst.pong());
})

Template.pingpong.helpers({
    pong() {
        return Template.instance().pong.get();
    }
})

Template.pingpong.events({
    'submit .set-pong'(event) {
        // Prevent default browser form submit
        event.preventDefault();

        ppInst.ping(event.target.text.value, {from:web3.eth.accounts[0]});

        //clear form
        event.target.text.value = '';
    },
})


texts: Can I rely on the fact that 'address(this).balance >= msg.value' is always true?

texts:
To my understanding, at the beginning of a payable function in a contract, an amount of msg.value ether is added to the contract's balance.

Therefore, the expression address(this).balance >= msg.value is always true.

Therefore, I can compute address(this).balance - msg.value without any risk of underflow.

Is that correct?

Thank you!


texts: "Elkrem:" Does it install an Ethereum client on a micro-controller?

texts:
I have read this article which describes the prototype of Ethkrem, a development board for IOT and Ethereum: https://devpost.com/software/elkrem-development-board-for-iot-ethereum .

However, it is not clear to me that this platform installs an Ethereum light client (Geth or Parity) on their micro-controller? Or they install Ethereum client on a routing connected to this micro-controller? like this example: https://www.youtube.com/watch?v=4BrvGnuGteI ?

Is it possible to install an Ethereum light client on Nano Pi using EthArmbian? (https://docs.armbian.com/#supported-boards)

Note: EthArmbian is a custom Linux image for ARM SoC devices that runs Geth or Parity Ethereum clients as a boot service and automatically turns your ARM SoC into an full Ethereum node. (https://github.com/diglos/userpatches#etharmbian)


texts: I'm thinking about installing extra videocards for GPU mining on a LAMP server that I actually use for developing and/or cronjob events (such as backups and similar), so I'd like to ask if this setup might affect also CPU time while mining or the CPU will still remain generally unaffected for its normal operations.


texts: How best to handle variable pricing during auction/sale

texts:
I'm building a contract for running multiple auctions, each selling individual ERC721 tokens from an array of token IDs, and the price increases with each one sold (the properties of the sale is defined in advance). If sales are made rapidly, then some sales may fail if the eth sent to the contract is too low (i.e. if it was correct at the time the payment was invoked, but has since increased before the tx completes).

I'm trying to think through how best to handle these rapid price changes from a UX point of view. Some initial thoughts:

Require an amount of ETH greater than the expected price to cover any potential increase, then return the difference to the user's address.
Have the calling code control the price. (Obviously this is a little riskier, and would need to be carefully implemented to prevent abuse).
A blend of the two: E.g. Have the contract control the base price, and the calling code can securely provide the delta above the base price.

Note: In addition to the variable pricing on the contract, the UI must also display the next price. Obviously this cannot be 100% accurate due to the length/timing of transactions, but hoping to provide the best possible user experience.

Any input/other suggestions would be greatly appreciated!


texts:
I'm trying to determine what the Uniswap Pair initial price was(initial tokens A and B).
Any idea how to do that without having to check every single token transfer and working backwards ?


texts: Why does creating an array in storage within a method change the state for something else?

texts:
I have a simple contract that sets an owner when the contract is initialized, but am having trouble understanding why it changes under certain circumstances.

I tried 3 ways of initializing and setting an array:

Using an array in memory
Defining a storage array outside of a method and pushing to it
Defining a storage array within a method and pushing to it

Cases 1 and 2 behave as expected, but Case 3 ends up changing the owner value and causes tests to fail. Can anyone provide insight on this behavior?

Smart contract:

pragma solidity ^0.4.4;

contract WeirdCase {

    address internal owner;
    uint256[] newArray;

    constructor() {
        owner = msg.sender;
    }

    function someMethod1() external {
        uint256[] memory newArray = new uint256[](10);
        for (uint256 i = 0; i < 10; i++) {
            newArray[i] = i;
        }
    }

    function someMethod2() external {
        for (uint256 i = 0; i < 10; i++) {
            newArray.push(i);
        }
    }

    function someMethod3() external {
        uint256[] storage weirdArray;
        for (uint256 i = 0; i < 10; i++) {
            weirdArray.push(i);
        }
    }

    function getOwner() view returns(address) {
        return owner;
    }
}

Test case:

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

contract('WeirdCase', function(accounts) {

  let weirdCase;

  beforeEach(async () => {
    weirdCase = await WeirdCase.new();
  });

  it("Case 1: succeeds", async function () {
    let beforeOwner = await weirdCase.getOwner();
    await weirdCase.someMethod1();

    let afterOwner = await weirdCase.getOwner();
    assert.equal(beforeOwner, afterOwner);
  });

  it("Case 2: succeeds", async function () {
    let beforeOwner = await weirdCase.getOwner();
    await weirdCase.someMethod2();

    let afterOwner = await weirdCase.getOwner();
    assert.equal(beforeOwner, afterOwner);
  });

  /*
   * DON'T KNOW WHY THIS FAILS!!!
   */
  it("Case 3: not sure why this fails", async function () {
    let beforeOwner = await weirdCase.getOwner();
    await weirdCase.someMethod3();

    let afterOwner = await weirdCase.getOwner();
    assert.equal(beforeOwner, afterOwner);
  });
});


texts: geth --testnet attach "getsockopt: connection refused", with blockchain saved on external storage

texts:
I have just finished syncing to the testnet, but I'm having trouble running geth console on it.

Storing the blockchain on an external usb drive, this is the command I used to start geth on the testnet
$ geth --testnet --datadir /media/removable/Lexar/ethereum/ --ipcpath ~/.ethereum/geth.ipc

and attempting to attach to the network with geth console
geth --testnet attach http://127.0.0.1:8545
gave me this error:

  Fatal: Failed to start the JavaScript console: api modules: Post
  http://127.0.0.1:8545: dial tcp 127.0.0.1:8545: getsockopt: connection
  refused

I read this answer here, but even with the --ipcpath flag as suggested, it doesn't work.

Please advise. Any help would be appreciated.


texts: Simple Solidity Question - Gettting Error in IERC20(path[0]).transferFrom

texts:
I am trying to call a simple contract, which I created, from ether.js to swap DAI to USDT on KOVAN.
Essentially, the sol function takes the passed array of address[] and is doing a transfer from sender (i.e. me) to the contract address.
Solidity :
function swapTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        uint256 deadline
    )
    external
    payable
    // returns (uint[] memory amounts)
    {
        // Transfer tokens from senders address to our smart contract
        // with the amountIn argument passed
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);

I am calling this via Javascript :
const signer = new ethers.Wallet(PRIVATE_KEY)
    const account = signer.connect(provider)
    let MY_CONT_ADDRESS_KOVAN = '0xF54f5E75B3cACe5706e27F5d44B2C06fcF28a8d6'
    const my_specific_cont = new ethers.Contract(
        MY_CONT_ADDRESS_KOVAN,
        ['function swapTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256 deadline ) external payable'],
        account
    )

const KOV_DAI_CONT_ADD = '0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa'
    const KOV_DAI_CONT_ABI = '… removed for brevity'
    const KOV_USDT_CONT_ADD = '0x07de306ff27a2b630b1141956844eb1552b956b5'
    const KOV_USDT_CONT_ABI = '… removed for brevity'

    const receiverWallet = new ethers.Wallet(PRIVATE_KEY, provider)

    const deadline = Math.floor(Date.now() / 1000) + 60 * 5

    const tx = await my_specific_cont.swapTokensForTokens(
        1,
        1,
        [
            KOV_DAI_CONT_ADD, //dai
            KOV_USDT_CONT_ADD  //USDT
        ],
        deadline,
        { value: 1 }
    )
    log('tx', tx)

Output Error :
(node:24236) UnhandledPromiseRejectionWarning: Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"reason":"cannot estimate gas; transaction may fail or may require manual gas
limit","code":"UNPREDICTABLE_GAS_LIMIT","method":"estimateGas","transaction":{"from":"0x2aeEcb55A573a6b4dea9C010020EaD9536E2606D","gasPrice":{"type":"BigNumber","hex":"0x04a817c800"},"to":"0xF54f5E75B3cACe5706e27F5d44B2C06fcF28a8d6","value":{"type":"BigNumber","hex":"0x64"},"data":"0xcf89fc450……………….removed for brevity"

When I comment the following line and all other lines in my sol function, transaction succeeds. So there is something wrong what I am doing here:
IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);

I have spent many hours but can't seem to figure out what am I doing wrong.
Any help will be really appreciated.


texts: MyEtherWallet is pending and dropping. It looks like it is stuck in a loop for 2 days?

texts:
EDIT: Solved, it got unstuck, haven't done anything but posted this message.

What I tried to do (3 times) is sending Ethereum to Shapeshift without realizing that the low gas will take longer to process. Then finally when I did realize, and when Shapeshift canceled the wait period to deposit the Ethereum, I wanted to cancel any transactions by putting a high gas with 0 ETH sending it to the same account.

As a result, I am somehow constantly pending a transaction. Nothing gets processed, no money lost, no transfers made. After two days, I do not believe that I have made such a large queue of transactions, and things look stuck in some kind of a loop.

The account in question is:

https://etherscan.io/address/0xedited !

The addresses that are pending are:

0x7641977940c27f2f48fe7ab9f1e10f1d12c7520a

0x6eceb6e0beec53cebd01526505e60be3d9c553c4

0xaee0cd00b37ab7d6a1f08226d1df91f34897ab0c

I do not want to make any transaction to any of those addresses! I only want this to stop, so I can move ETH to another account.

Any help would be appreciated.


texts:
I have an Ethereum wallet address (the public key is known by other people). I periodically receive payment on this address (and cannot change it/receive to other address).

I need:
When I receive a payment on it, automatically and immediately it sends/forward them to my new wallet address (the private key is known only by me).

Is this possible and how?
I am new to programming, kindly inform me on how to begin doing this.


texts: Griefing Attacks: Are they profitable for the attacker?

texts:
The following article explains one of the solutions for indirectly validate a block when cross-sharding transaction between two shards to prevent invalid blocks.

The article called one of these solutions "Fisherman" (without any more explanation about the term Fisherman in more details ...)

The article then mentions that the Fisherman (as a dominant solution) has two problems, one of which is as follows:

  "The existence of the challenge protocol creates a new vector of
  attacks when malicious nodes spam with invalid challenges. An obvious
  solution to this problem is to make challengers deposit some amount of
  tokens that are returned if the challenge is valid. This is only a
  partial solution, as it might still be beneficial for the adversary to
  spam the system (and burn the deposits) with invalid challenges, for
  example to prevent the valid challenge from a honest validator from
  going through. These attacks are called Griefing Attacks."

Link to the article: https://medium.com/nearprotocol/unsolved-problems-in-blockchain-sharding-2327d6517f43

Although, the article says that this attack, called "Griefing Attacks" might still be beneficial for the adversary, but in this answer (here: https://ethereum.stackexchange.com/a/62846/23024) says:

"Such an attack doesn't benefit the attacker ..."

So, eventually,

(1) Is Griefing Attacks profitable for the attacker or not?
(2) What is the exact definition of Griefing Attacks?

Please note that this question is different with another question (https://ethereum.stackexchange.com/a/62846/23024) that I have linked in my question. Because: (1) That question is: "What does Griefing mean?" but my question is: "Are Griefing attacks profitable for the attacker?" Also (2) I linked to that question, where I said that while in the answer of that question is mentioned: "Such an attack doesn't benefit the attacker ...", but in another article is said: "Griefing attacks might still be beneficial for the adversary". So the question is that eventually Griefing attacks are profitable or not? It might cause to define precisely Griefing attacks.


texts: What is the proof that Mainnet can't be reset?

texts: It has been argued that the Morden testnet can be reset any time. How can one verify that this is not possible with the mainnet?


texts: How can I change the state of a contract if it's stored on the blockchain

texts: Doesn't that contradicts the whole idea of blockchain that data stored there is immutable. If someone can alter the data stored in the state of the contract then how is it any different from any other databases.


texts: How much is the private-key in a keystore resilient to bruteforce?

texts:
I was wondering how safe would be my key if someone can put his hands on my Keystore File (UTC / JSON) created with MyEtherWallet.
I've used in the past hashcat and so I know it can easily find the plaintext of a medium length password in a reasonable time starting from his hash, even with just a normal GPU.
So can the keystore be bruteforced in the same easy way? Or in other words how long should be the password to be safe?


texts: Deploying a smart contract from hosted wallet or light client

texts:
At the moment I use the official Ethereum wallet / mist for deploying a contract to the Ethereum network.

Is there any other options for doing this either via different software clients or websites?

The reason I ask is that the Ethereum blockchain is becoming to large for my C: drive and the official Ethereum wallet / mist is hardwired to the C: drive (for the users) so I am unable to move it to a different drive.


texts:
So i deployed my smart contract on Kovan Network using Remix IDE, i after successful compilation I added the arguments of the constructor to create the token, it deployed successfully but the issue now is the token I created did not appear on etherscan even though I can see contract name and transaction hash.
However, I can interact with the functions on Remix IDE as you can see on the screenshot

Here is the link to the smart contract code on pastebin
Also see the deployed smart contract on etherscan here


texts: I know Bitcoin runs on a POW (Proof of work) concept and that there is a side chain of Ethereum using PoA but other than that what other blockchains/crypto currencies run using  these or different protocols?


texts: How to generate a signature with web3py like metamask does?

texts:
Most ethereum apps request signatures like this

How exactly do i recreate this signature in web3 py? Is there any way i can view the data that gets sent thru metamask?
I have tried the following code without success:
message = encode_defunct(text='Swap 0.04 ETH Minimum: 21.64184785 ZKS To: 0xc6f8a2d663250ad86c6c58fc310238e1e5e457d6 ChainId 10 Nonce: 14 Fee: 0.0 ETHAccount Id: 75463')
signed_message = w3.eth.account.sign_message(message, private_key=private_key)


texts:
I am trying to add static peers by static-nodes.json file but with this version it does not work. What is the way to do it ?

If I add peers with admin.addPeer() it works, but if I am using --syncmode light it doesn't.

Also, I am trying to use --mine in the command line and it does not work neither. It stops in INFO [02-05|16:45:52.368] Commit new mining work. It just runs if I add miner.start() in the console.

UPDATED: adding peers by static-nodes.json works but it doesn't if it is a light node


texts:
I'm running Mist Wallet 0.5.2 on OSX.

In both the Wallets and the Contracts views, there is no trash icon to delete the respective Wallet or Contract. Same goes for the particular Account or Contract view. Tutorials reference this icon, but it's nowhere to be seen.

I know I can delete a particular Account from the Keystore folder. However, how do I go about deleting a Contract that I am currently watching? Thanks for any input!


texts:
In this thread, an NFT cryptoart collector with deep pockets named beanie said,

I have bought a few pieces on FND cause they were significantly
cheaper, but now realize they were priced that way for a reason.
SR on-chain provenance is critical for galleries and investors.
The price premium is probably still understated.

and adds

The SuperRare platform is the on chain marketplace, just like Larva
Labs (CryptoPunks).
This is CRITICAL and adds immense value in so many ways.

What does he mean by the Foundation.app (FND) platform being off-chain and the SuperRare (SR) platform being on-chain? From what I understand, there is no economical way to store 5MB+ jpeg files on any blockchain at the moment so I doubt SuperRare even does what he is claiming. What is he really getting at?
Besides, doesn't FND and SR both upload images to the InterPlanetary File System (IPFS), meaning that they are both off-chain?


texts: Using Webpack getting the error 'Uncaught Error: Module parse failed: Unexpected token (32:44)

texts:
Here is the complete error
Uncaught Error: Module parse failed: Unexpected token (32:44)
You may need an appropriate loader to handle this file type.
|     if(typeof window.web3 !== 'undefined') {
|       return resolve(
>        new Web3(window.web3.currentProvider);
|     );
|     }
    at eval (index.js:1)
    at Object../client/index.js (bundle.js:96)
    at __webpack_require__ (bundle.js:20)
    at eval (webpack:///multi_(:8080/webpack)-dev-server/client?:2:18)
    at Object.0 (bundle.js:383)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:84
    at bundle.js:87

Here is my Webpack config file
const path = require('path');

module.exports = {
  mode: 'development',
  entry: './client/index.js',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js', // string
  },
  devServer: {
    contentBase: path.join(__dirname, 'public'),
    compress: true,
    port: 8080
  }
};

If there is any other information I need to provide to help resolve this issue I can add


texts: I want to store decimal value in a storage variable and later use that variable at same precision in the formula later internally

texts:
I want to store uint public MINTING_VELOCITY = 0.000002;
And later use it in the formula:  A x t x MINTING_VELOCITY ,where A = 2000 ,t(staking_duration_time) = 120
Issue is currently MINTING_VELOCITY is reading  0.
How to take the exact/fetch the decimal value with exact precision?Please follow the code shared in the screenshot to understand the scenario better
How to achieve that via solidity .Please help!


texts: interact with a contract deployed by another account

texts: How do I send transactions, subscribe to events and call methods from a contract already deployed on the blockchain? (in web3.js)


texts: Would it be possible to create a ERC721 Token for say a game item, but I want the Token to basically have ETH inside the token, so that a user could destroy the token to reclai


texts: Simplest transaction does not get mined for hours - why?

texts:
I have a send transaction that is pending for the longest time. I quardupled the normal gas price, but still no results - probably it has something to do with ongoing spam attacks? Any other reason?

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


texts: Parse an Integer to a String in Solidity?

texts:
How can I parse an integer (uint) to a string in solidity?

This is what I have attempted to do so far:

function bytes32ToString (bytes32 data) returns (string) {
    bytes memory bytesString = new bytes(32);
    for (uint j=0; j<32; j++) {
      byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
      if (char != 0) {
        bytesString[j] = char;
      }
    }
    return string(bytesString);
  }

But the following line returns an error:

string myString= bytes32ToString(bytes32(myInteger));

Type string memory is not implicitly convertible to expected type string storage pointer.

Why is this?


texts: Payable function that returns value: when is this example practical?

texts:
To quote an example from a book:

contract StockPriceOracle {
  uint quoteFee = 500;
  mapping (string => uint) private stockPrices;

  //...

  function getStockPrice(string _stockTicker) payable returns (uint _stockPrice) {
    if (msg.value == quoteFee) {
      //...
      _stockPrice = stockPrices[_stockTicker];
    } else {
      revert();
    }
  }
}

There is a payable function that returns a value. Correct me if I'm wrong, but as far as I understand, this example does not make any practical sense. For the caller to be able to retrieve the desired information (the stock price), the function would have to emit an event. Or is there a situation where the code above is actually practical?


texts:
I am new to this. So, how do I connect web3.py with Ganache. I've got Ganache up and running, smart contract deployed. I would like to interact with it from, lets say, a python shell. So, this is what I get:
>>> from web3 import Web3
>>> w3 = Web3(Web3.IPCProvider('http://127.0.0.1:7545'))
>>> w3.isConnected()
False

I can connect with Ganache using truffle. Is it possible to do it with web3.py?


texts:
There are many different Ethereum 2.0 testnets, among them

Medalla
Spadina
Zinken

What are the differences and what is their purpose?


texts: Does Solidity's constant keyword do anything?

texts:
It seems that the purpose of function foo() constant {} is to indicate that a function does not change the contract's state. And yet, as it states here, the compiler doesn't actually enforce this. So for the time being, is constant simply an unenforced convention? A way to let contract readers know that this function shouldn't change state?

In reality, this bar function works just fine:

contract Foo {
  uint x;

  function bar(uint y) constant {
    x = y;
  }
}