texts: Error when trying to open Ganache on Ubuntu: archive type not supported

texts:
After downloading a fresh copy of the latest Ganache and double click to run it, the following error is shown:

  archive type not supported

Versions
Ubuntu: 16 and 17

All Ganache versions: for example 1.2.3 and 2.0.0


texts: Is there a way to use constructor function as a fallback, example: "function Mycontract public payable () {}

texts:
In other words if I have a contract called "mycontract" and then simply add the same function with the same name "mycontract" as public and payable, will this mean that others can call it?

Since I tried this in remix but the function with the same name doesn't appear in the UI, I guess this means it's constructor and cannot be called more than once (after contract creation)? Thanks!


texts: problem when deploy smart contract in Quorum using web3j

texts:
I'm using web3J when i try to deploy contract i get

Error processing transaction request: Non-200 status code: &{Status:400 Bad Request StatusCode:400 Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[Date:[Mon, 29 May 2017 13:03:02 GMT] Server:[Warp/3.2.8]] Body:0xc425668cc0 ContentLength:-1 TransferEncoding:[chunked] Close:false Uncompressed:false Trailer:map[] Request:0xc42045a690 TLS:<nil>}

I used this methods

ClientTransactionManager transactionManager = new ClientTransactionManager(quorum,
            "0x0fbdc686b912d7722dc86510934589e0aaf3b55a", Arrays.asList(""));

    BigInteger contract = InstanceOkoro.deploy(quorum, transactionManager, GAS_PRICE, GAS_LIMIT, BigInteger.ZERO)
            .get().getGasPrice();

with

private static final BigInteger GAS_PRICE = new BigInteger("0");
private static final BigInteger GAS_LIMIT = new BigInteger("900000");


texts: How Ethereum stores its data in the blockchain

texts:
I am new to ethereum and the blockchain, but I am wondering about blockchain databases. Mainly I am wondering how exactly the database data and the blockchain merge. For instance, in a database you have basically SELECT, INSERT, DELETE, and UPDATE. The data is stored in tables or in a graph, etc. Then you query the data, that's basically it.

In a blockchain, the data seems to be stored in a Merkle tree. This seems to allow for storing versions of data, to handle the database versioning problem. It also has something to do with validating the data, but I'm not too sure how this works yet, but it seems valuable.

To merge the two, it seems you need to store the database in both a Merkle Tree and a graph database (if you're doing graph data). I don't see how this should really work. In addition, I would like to know at what granularity you are making the "blockchain transactions", because these seem processor intensive and so if you made them on every CREATE or INSERT, etc., it seems like that would bog down the db. Please advise.


texts:
I'm using https://iancoleman.io/bip39/#english to generate a random 12 word mneumonic with the following settings.

Mneumonic language: English
Coin: Ethereum
Derivation Path: BIP44

It generated the following mneumonic movie diesel same toe bachelor acquire roast ghost siege thought possible scale

The first address - public key - private key is the following
Address: 0x67D8641084F8088D5996E39Bae07F9Dc4130307F
Public Key: 0x030c8931742732ca2e0956ecf385acc886a54428ad84eb884aa2c72f1008a2c858
Private Key: 0x78f7e532bf8d7c79d8ef42c75a361f53a8db8c38e4cb1828788ef119c48f6896
I wrote this to generate the same public key from the private key.

var Wallet = require('ethereumjs-wallet')
var EthUtil = require('ethereumjs-util')

// Get a wallet instance from a private key
const privateKeyBuffer = EthUtil.toBuffer(
  '0x78f7e532bf8d7c79d8ef42c75a361f53a8db8c38e4cb1828788ef119c48f6896'
)
const wallet = Wallet.fromPrivateKey(privateKeyBuffer)

// Get a public key
const publicKey = wallet.getPublicKeyString()
console.log(publicKey)

the log statment prints 0x0c8931742732ca2e0956ecf385acc886a54428ad84eb884aa2c72f1008a2c8582bc50fd34eb9e111ae2969205d7af28e9b5050be4ae6ca43df74fc65b9af5803

This is not the same public key for the corresponding private key, why is this?


texts: Could someone explain basic transferFrom functionality

texts:
It seems to me that the following ERC20 function does not check where the message comes from and allow anyone to transfer tokens between two addresses:

function transferFrom (address _from, address _to, uint256 _value)
public delegatable payable returns (bool) {
  if (frozen) return false;
  else if (
    (addressFlags [_from] | addressFlags [_to]) & BLACK_LIST_FLAG ==
    BLACK_LIST_FLAG)
    return false;
  else {
    uint256 fee =
      (addressFlags [_from] | addressFlags [_to]) & ZERO_FEE_FLAG == ZERO_FEE_FLAG ?
        0 :
        calculateFee (_value);

    if (_value <= allowances [_from][msg.sender] &&
        fee <= safeSub (allowances [_from][msg.sender], _value) &&
        _value <= accounts [_from] &&
        fee <= safeSub (accounts [_from], _value)) {
      require (AbstractToken.transferFrom (_from, _to, _value));
      require (AbstractToken.transferFrom (_from, feeCollector, fee));
      return true;
    } else return false;
  }
}

In AbstractToken:

function transferFrom (address _from, address _to, uint256 _value)
public payable returns (bool success) {
  uint256 spenderAllowance = allowances [_from][msg.sender];
  if (spenderAllowance < _value) return false;
  uint256 fromBalance = accounts [_from];
  if (fromBalance < _value) return false;

  allowances [_from][msg.sender] =
    safeSub (spenderAllowance, _value);

  if (_value > 0 && _from != _to) {
    accounts [_from] = safeSub (fromBalance, _value);
    accounts [_to] = safeAdd (accounts [_to], _value);
  }
  Transfer (_from, _to, _value);
  return true;
}

Here are the approve functions

function approve (address _spender, uint256 _value)
public delegatable payable returns (bool success) {
  return AbstractToken.approve (_spender, _value);
}

In AbstractToken:

function approve (address _spender, uint256 _value)
public payable returns (bool success) {
  allowances [msg.sender][_spender] = _value;
  Approval (msg.sender, _spender, _value);

  return true;
}

Is that true ? I see a frozen variable, which seems to me the only way to control who transfers what and when.


texts: How external functions call works in Solidity? Synced or Asynced?

texts:
function redeem(uint256 _token) public {
    // transfering the token from tokenholder to owner
    token tokenBalance = token(tokenAddress);
    tokenBalance.transferToOwner(owner, _token);

    // the tokenholder gets the ethereum
    uint256 weiVal = (_mtcTokens * redeemRate);
    msg.sender.transfer(weiVal);
}

The first part of the function is transfering the token from the holder to owner by calling an external function in another contract. The second part is transfering the ethereum for each token transfered.

Does the first part will work in a synced manner (i.e. the code will run line by line) OR the execution of second part can happen even if the execution of first part is not completed?

Are there any security flaws (like re-entry attack etc)?


texts:
Already read this How is the price of a token determined on Etherscan? but still not understand how a new fresh token is priced.
I mean .. I just create a token named "ABCD" with 1.000 of suply and deploy it into the BSC. Well ... how much is it costing in BUSD for example?


texts: Why EVM and Solidity and not JVM and Java?

texts: Why wasn't JVM and Java used for Ethereum? But instead, EVM and Solidity was invented for the express purpose for Ethereum?


texts: How do Ethereum smart contracts work with external outcomes?

texts: Since every node has to execute a smart contract and receive the same result, Ethereum smart contracts can't go out to the Internet to verify data.  So, how do these sites that bet on the outcomes of sports game deal with this (e.g., Crypto Sportz)?  Or, maybe not even betting but whether other facts that are available online but would be hard to figure out without online access?


texts: geth sendTransaction error: insufficient funds for gas * price + value

texts:
I tried geth in a private network, and when I tried sendTransaction, it was failed saying "Error: insufficient funds for gas * price + value".

But the balance of accounts[0] is 4785 ether and it seems sufficient.

web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
4785

The command I tried is

eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(1, "ether"), gas: 1})

The genesis json file is

{
  "config": {
        "chainId": 0,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

geth version: 1.7.1

Does anyone know what is wrong?


texts: I would like to see what a PETH on Kovan is worth in DAI. How can you look for exchange rates on testnets?


texts: Does an Ethereum client need to download the entire state of a contract in order to use it?

texts:
A typical ERC20 token will store account balances in a mapping, something like this:

mapping(address => uint) public balances;

Does this mean that, to do a transaction or check a balance on this contract, I have to have the complete state available? Do I need to have every single balance for this token on my system?

With a blockchain-native token, like Ether or Bitcoin, a light client uses techniques like bloom filters to sync just a small subset of the universe of address balances. But this doesn't seem to be possible for tokens that store balances in a single mapping. What strategies can be employed by contract developers to get similar performance characteristics to a native token?


texts: is there any possibility to read struct via interface from deployed contract?

texts: the contract is deployed which has no view function for that particular struct, is there any way to read values via interface in another contract which I want to write and deploy ?


texts: Oraclize __callback function with unbounded gas usage

texts:
I am making a lottery contract and using Oraclize to select a winning number.

Here is what I have now:

The owner calls a finalize() function, which disallows new entries, and makes a call to Oraclize (using WolframAlpha as data source).
The oracle then calls my __callback function with the result, and my contract uses that to find the winner(s), distribute the winnings, and reset the contract to accept entries again. This operation involves loops, and takes steps proportional to the number of entries. Since the number of entries is not limited, I believe this operation's gas usage is not bounded.

I have thought about these options:

Estimating the gas usage somehow, and specifying that in the oraclize call.
Removing logic from the callback function, and only using it to set the winning number. The owner then has to call a distribute function to do the calculation-heavy steps.

I find both options problematic. It seems to me that oraclize callback functions were intended to be kept simple. However, I would like to avoid the owner having to call the contract twice (this second option also raises the problem of a dishonest owner not calling the distribute function when he sees the winning number).

Is there a common pattern for this type of usage? What is the correct way to go about this?

Thank you in advance.


texts: Any Pseudo Random Number Generator that can generate different numbers in the same block?

texts:
All the Pseudo Random Number Generators that depend on block hash or block time seems to generate the same "random" number for the same block. Is there any way to generate different numbers in the same block?

The use case is something like this, I have a game contract, people can send 1 Ether to this contract each time, and for a 1% chance, the sender may receive all the Ethers stored in the contract. Normally I use a PRNG with block hash and stuff, generate a uint256 number, mod it with 100 and award the sender when the result is 0.

However, there's a problem in that, as one person (address) may send multiple transactions to the contract at the same time (with incrementing nonce) and those transactions may be mined within a single block, then the "random" number ends up the same for all those transactions. That means if this person doesn't win the prize in the first transaction, he/she will not be able to win the prize in all the transactions that are mined in the same block. This seems to be unfair to this person, as I want to design the game so that on average if one person sends 100 transactions, he/she will be able to win once. But now if this person sends 100 transactions consecutively which are mined in 10 blocks (say each block included 10 transactions from this person), that means he/she only has 1/10 chance to win the prize.

Naturally, I'd like people to participate more in the game, instead of waiting for a transaction mined before sending the next transaction. So is there any way to make the PRNG generate random numbers for different transactions within the same block?

I've looked through the solidity docs, it seems the available variables that have the potential to be part of a PRNG are either block-related or something like the msg.sender, msg.value, msg.data, tx.gasprice, etc. which will all be the same for my use case when mined within the same block. And unfortunately nonce is not available in solidity? Am I forced to rely on some off-chain centralized random number generator for my use case?


texts: 0x: Is it possible to fill an order from a smartcontract?

texts:
When I try to fill an order with funds from a contract I get the following generic error:

  Error: Transaction:
  0x1d3161cd7f318c3b0b28fc34b2c6bca0cbf4efdb3b11fcf7ec3af7c9adfd821b
  exited with an error (status 0). Reason given: TRANSFER_FAILED.
       Please check that the transaction:
       - satisfies all conditions set by Solidity require statements.
       - does not trigger a Solidity revert statement.

I've got the following contract:

pragma solidity >=0.4.24;

Exchange exchange;
EthForERC20Token crowdsale;
WrapERC20Token wrapERC20Token;

constructor(
    address _exchangeAddress
)
public
{
    // The local 0x exchange intstance
    exchange = Exchange(_exchangeAddress);
    // Grand unlimited allownace to the exchange contract.
    wrapERC20Token = new WrapERC20Token(address(exchange));
}

function fillOrder (
    Exchange.Order memory _order,
    uint256 _assetFillAmount,
    bytes memory _signature
)
public
payable
{
    exchange.fillOrder(_order,_assetFillAmount, _signature);
}

function getWrappedERC20Address()
public
view
returns(address) {
    return address(wrapERC20Token);
}

I tested and the contract owns enough of the WrappedERC20Token which is just an ERC20 token with the option to pre-approve an address with unlimited allowance.

My 0x order creation is as follows:

const wrappedShareAddress = await contract.getWrappedShareAddress();
const maker = accounts[0];
const makerAssetData = zeroX.assetDataUtils.encodeERC20AssetData(etherToken);
const takerAssetData = zeroX.assetDataUtils.encodeERC20AssetData(wrappedShareAddress);
const contractWrappers = new zeroX.ContractWrappers(providerEngine, { networkId: 50 });

const order = {
            exchangeAddress: exchange,
            makerAddress: maker.toLowerCase(),
            takerAddress: NULL_ADDRESS,
            senderAddress: NULL_ADDRESS,
            feeRecipientAddress: NULL_ADDRESS,
            expirationTimeSeconds: (1581437362).toString(),
            salt: zeroX.generatePseudoRandomSalt().toString(),
            makerAssetAmount: new zeroX.BigNumber("5e17").toFixed(),
            takerAssetAmount: new zeroX.BigNumber("5e17").toFixed(),
            makerAssetData,
            takerAssetData,
            makerFee: new zeroX.BigNumber("0").toFixed(),
        takerFee: new zeroX.BigNumber("0").toFixed(),
        };
        // console.log(order);
        // Generate the order hash and sign it
        const orderHashHex = zeroX.orderHashUtils.getOrderHashHex(order);
    signature = await zeroX.signatureUtils.ecSignHashAsync(providerEngine, orderHashHex, maker);
        signedOrder = {...order, signature};
    const makerWETHApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(
            etherToken,
            maker,
        );

        await toTxhash.mineTx(makerWETHApprovalTxHash);

        const makerWETHDepositTxHash = await contractWrappers.etherToken.depositAsync(
            etherToken,
            new zeroX.BigNumber("2e18"),
            maker,
        );

        await toTxhash.mineTx(makerWETHDepositTxHash);

Then I call the smart contract function using:

    const res = await contract.fillOrder(
        signedOrder,
        new zeroX.BigNumber("5e17").toFixed(),
        signature,
        {from: maker, value: new zeroX.BigNumber("1e18").toFixed()}
    );


texts:
Before adding this function below, the contract works well. But after adding the function, when I trying to deploy the contract, the remix IDE keeps showing the error message of "Gas estimation failed". Did something wrong with the function?

 //return the user name by mapping the address
    function find_user_name(address _address) public view returns(string){
      uint256 i;
      string account_name;
      for(i=0; i < userlist.length; i++){//find the mapping user account name
            if(_address == userlist[i].useraddress)account_name = userlist[i].account;
      }

      return account_name;
    }


texts: Get the value of ERC20 tokens transferred using the Etherscan API

texts:
I am using Etherscan API to get transaction and other details for addresses.

I need to find out no. of tokens transferred between two addresses. For Ex - for Below TxHash I see 1564+ tokens transferred. When I use this API call I see from and to address but not token value.


texts: How to handle created contract instance on Remix

texts:
I am writing some contract code by using Solidity on Remix.

As you can see, TreasureBox contract creates Gold contract and it calls take() method on Gold contract. But I can check that TreasureBox contract is deployed only even I executed profit() method. How to handle and check the contract created by originally executed contract ? Does anyone have an idea ?

pragma solidity ^0.4.24;

contract Gold {
    bool public isTaken = false;

    function take() public {
        isTaken = true;
    }
}

contract TreasureBox {
    Gold g;

    constructor() public {
        g = new Gold();
    }

    function profit() public {
        g.take();
    }
}


texts: Why cryptokitties uses storage instead of memory?

texts:
There are a lot of explainations of storage and memory out there like this question or this question. But I'm wondering why cryptokitties for example uses storage instead of memory in many functions. In this case the auction is not modified. Wouldn't it be cheaper to use memory here?

function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {

    Auction storage auction = _getAuctionByTokenId(_tokenId);
    require(_isOnAuction(auction));

    uint256 price = _currentPrice(auction);
    require(_bidAmount >= price);

    address seller = auction.seller;
    _removeAuction(_tokenId);

    // Transfer proceeds to seller (if there are any!)
    if (price > 0) {
       ...
        uint256 auctioneerCut = _computeCut(price);
        uint256 sellerProceeds = price - auctioneerCut;
        // Ether transfer
        seller.transfer(sellerProceeds);
    }

    emit AuctionSuccessful(_tokenId, price, msg.sender);
    return price;
}


texts:
I'm a little bit confused by the fact that my GTX 1080 which has effective memory clock of 10.8 GHz gives only ~25 MH/s while people reporting their GTX 1070 cards give up to 40 MH/s.

As far as I know there are some technical differences between memory types GDDR5X and GDDR5, but does the first really slow down ethereum mining efficiency?

Anyone else using gtx 1080 for mining purposes, maybe there are some fixes available? Thanks in advance.


texts:
Low level function calls work in Truffle, Solidity is not the problem.
Other method invocations are working with the JS and HTML.
This is my first attempt at using .call instead of .send; I am not sure why I am getting this error.
For the record, I am using Web3 1.x

ERROR:

Error: Returned values aren't valid, did it run Out of Gas?

JS:

await this.KYCinstance.methods.readFraud(fraudID).call({from:this.accounts[0], gas:3000000});

SOLIDITY:

function readFraud (uint256 fraudID) external view returns(address, string memory, string memory, uint256, uint256) {
    Fraud memory fraud = frauds[fraudID];
    return(fraud.bank, fraud.accountNumber, fraud.routingNumber, fraud.amount, fraud.timestamp);
}


texts: Truffle Error: invalid argument 0: hex string without 0x prefix

texts:
I'm trying to deploy and test the smart contracts on the Goerli network using Truffle. While migrating getting below error.

Contract: Simple Storage Test suite
       Simple Storage Set
         Should check that the Value is updated successfully:
       Uncaught Error: Invalid JSON RPC response: undefined

 Contract: Simple Storage Test suite
       "after each" hook: after test for "Should check that the Value is updated successfully":
     Error: invalid argument 0: hex string without 0x prefix

Truffle Version
Truffle v5.1.19 (core: 5.1.19)
Solidity v0.5.16 (solc-js)
Node v12.16.1
Web3.js v1.2.1


texts:
I couldn't find an appropriate, simple fix of the tx.origin vulnerability, without having to use any modifier, any help is very much appreciated,

thanks,

PS: msg.sender is not what I'm looking for (if another contract calls your contract msg.sender will be the address of the contract and not the address of the user who called the contract)

contract Proxy {

    address myAddress;

    function callMyContract() public view returns(address) {
        MyContract(myAddress).doSomthing();
    }
}

contract MyContract {

    event Something(address sender);

    function doSomthing() public (address) {
        emit Something(msg.sender); // Proxy address
        emit Something(tx.origin); // User address (the one I need) but vulnerable
    }
}


texts: How to get the pending transactions in the whole network from ethereum?

texts:
I would like to get the pending transactions in the whole network of ethereum.
For example, the transaction '0xabcdefg' is right now pending in the pool, waiting to be mined by miners, after 12 seconds, '0xabcdefg' will be packeted in to blocks.
I just want to get the '0xabcdefg' in the pool before this 12 seconds.
In a word, I would like to get a list of the waiting list of the whole network of ethereum.
What should I do?
It seems that geth, infual, and the etherscan can not get all the pending transactions, is this caused by the mechanism of ethereum?


texts: Approve and Swap/Deposit at the same time

texts:
So one of the most annoying things for me is having to Approve before calling Swap or Deposit.
I would love there to be a proxy contract which just calls Approve and Swap/Deposit in the same function.
Are there any existing contracts that implement this already?


texts: `etherlime deploy` fails with Error: invalid sender

texts:
I am trying to deploy a contract with etherlime to a private permissioned Quorum network:

etherlime init    --> OK

etherlime compile --> OK

etherlime deploy  --> Error

Error:

Compilation finished successfully
Deployer set to deploy from address: 0xC58A28d310c76e8298FA456381E6F2da9F046V54

JSONRPC Deployer Network: http://localhost:22000/

Deploying contract: LimeFactory
{ Error: invalid sender ...

But the sender is actually valid! The address was derived from the privateKey I have passed to JSONRPCPrivateKeyDeployer and it is listed in personal.listAccounts when I make the check in the geth console, so what could be wrong?


texts: Do comments affect the contract size limit?

texts: I ran into the eip-170 contract code size limitation. I need to trim it down. Do comments affect the size of the contract as I have a lot of them and don't mind getting rid of them.


texts: How to Deploy non-Migratable Contract in Zeppelin OS?

texts:
I am using Zeppelin OS to create a migratable contract MyContract, which will be imported into another contract Foo. Foo calls the baz() function of MyContract, so when MyContract is upgraded, Foo should be calling the upgraded code automatically.

MyContract.sol

pragma solidity ^0.4.18;
import 'zos-lib/contracts/migrations/Migratable.sol';

contract MyContract is Migratable {
    uint256 public x;

    function initialize(uint256 _x) isInitializer("MyContract", "0") public {
        x = _x;
    }

    function baz() public returns (uint256) {
        decrement();
        return x;
    }

    function increment() public {
        x += 1;
    }

    function decrement() public {
        x -= 1;
    }
}

Foo.sol

pragma solidity ^0.4.18;

import './MyContract.sol';

contract Foo {
    uint256 public x;
    MyContract myContract;
    address myContractAddress;

    constructor(address _myContractAddress) public {
        myContractAddress = _myContractAddress;
    }

    function baz() public {
        myContract = MyContract(myContractAddress);
        x = myContract.baz();
    }
}

I am deploying MyContract and its proxy by running

zos add MyContract
zos push --network local
zos create MyContract --init initialize --args 42 --network local

How can I deploy Foo.sol?


texts: parity command failes due to missing c++ libs

texts:
Today I decided to switch to parity but after (successfully) installing I got the following after typing 'parity':

parity: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by parity)
parity: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by parity)
parity: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by parity)


texts: How to call a method after a specific tx in a block

texts:
With web3, it is possible to call a method of a smart contract at a specific block :
myContract.methods.methodName().call(transactionObject, blockNumber, callback)
Is there a way to call it after a specific tx in a specific block ?
Why do I want to do that ?
I would like to fetch the state of a specific variable. In the case multiple transactions interact with the same smart contract, I can only get the state of that specific variable at the last executed transaction of the block. However, I would like to be able to fetch the variation of this variable inside the block and in-between 2 transaction that are interacting with the same smart contract and changing the state.
I'm open to any idea, including without using web3


texts:
Any piece of code will have some degree of vulnerability, and any such code that attracts any level if attention is bound to be exploited  through these vulnerabilities.

In conventional (centralised) systems, these vulnerabilities are handled through regular incremental updates that the originator distributes to patch against any vulnerabilities discovered over time.

How are smart contracts vulnerability exploits meant to be secured against over time? Assuming that the code is free from exploits on deployment surely cannot be a solution.


texts: Acting to a transactions as soon as they are done

texts:
My app requires to act to paid transactions in a matter of seconds. In a worst case scenario it could be few minutes.

Problem is that my geth chain is never at the point where Etherscan chain is. It's tens of minutes or even hours away. So when I get a block where transaction was made user could've asked for a refund by that time.

My question is how do you make your chain as close to Etherscan's. Is it even possible with geth? If not, how Etherscan does it and what are alternatives to my problem?


texts:
var EthereumTransaction = require("ethereumjs-tx")

var Web3 = require('web3')

var web3 = new Web3('http://127.0.0.1:7545')

//Setting Receiving and Sending Address

var sendingAddress = acc1

var receivingAddress = acc2

//Checking the balance of each account in ether

web3.eth.getBalance(sendingAddress).then(console.log(web3.utils.fromWei('1', 'ether')))

web3.eth.getBalance(receivingAddress).then(console.log(web3.utils.fromWei('1', 'ether')))

//Creating a transaction

var rawTransaction ={
    nounce:0,
    to:receivingAddress,
    gasPrice:20000000,
    gasLimit:30000,
    value:100,
    data:""
}

//Sign the Transaction

var privateKey = 'private key goes here'

var senderPrivateKeyHex = new Buffer(privateKey,'hex')

var transaction = new EthereumTransaction(rawTransaction)

transaction.sign(senderPrivateKeyHex)

//Send transaction to the network

var serializedTransaction = transaction.serialize()

web3.eth.sendSignedTransaction(serializedTransaction)

Error Occurred is.
TypeError: EthereumTransaction is not a constructor


texts: I get this error when testrpc is launched. Somebody know how to solve this?


texts: Solidity - Remix - 0.7.1 - VM error: invalid opcode when I'ḿ trying to initialize ztruct containing a (nested) mapping

texts:
I could compile the code above, but when I call createRequest function, I got an error:
The code
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.7.1;

contract Campaign {
    struct Request {
        uint value;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    uint public numRequests;

    constructor(uint minimum) {
        manager = msg.sender;
        minimumContribution = minimum;
    }

    function contribute() public payable {
        require(msg.value > minimumContribution);
    }

    function createRequest(uint value) public returns (uint requestId) {
        requestId = numRequests++;
        Request storage r = requests[requestId];
        r.value = value;
        r.approvals[msg.sender] = true;
    }
}

The error when I call createRequest function on the Campaign contract deployed on Remix JavaScript VM environment:
transact to Campaign.createRequest errored: VM error: invalid opcode. invalid opcode The execution might have thrown. Debug the transaction to get more information.

I tried to write a code similar of the documentation (https://solidity.readthedocs.io/en/v0.7.0/types.html#structs), but I couldn't understand why I got this error.
Thanks in advanced.


texts: Gas issue on sendRawTransaction on the rinkeby network

texts:
I'm facing a gas issue on rinkeby network on sendRawTransaction.

Tested with various gas value to experiment and getting either
insufficient funds for gas * price + value
or
exceeds block gas limit.

Some more info:
Gas Estimate: 32872
Balance: 1100000 Gwei
gas: 87200

Any suggestions or anybody faced similar issue?

My code here: https://gist.github.com/anistark/2daf9295a4d5a03cb405ff5a47924b32


texts:
Is it possible to cancel a transaction after it has been broadcasted, but before it has been mined?
This could be useful on sending an erroneous transaction containing invalid data.


texts: Best practice for fetching ERC20 token balances for a given address

texts: Are there any best practices to fetching all ERC20 token balances for a given address? I am open to using external APIs.


texts:
I'm having trouble understanding the flow:

Contract <==observes/injects== Oracle <==requestdata==> API

I read several articles like this and I'm aware of the theory of the flow. But what exactly is an oracle? Is it a smart contract? Is it an external service that watches for smart contract events and consequently makes something? Who pays for the oracle state changes (gas)? Can the oracle be seen as the client sade of an application?


texts: How to properly estimate gas costs of function calls with go-ethereum and golang?

texts: I'm attempting to build out a program in golang to model ethereum gas costs of function calls for the smart contracts I write. I've successfully been able to estimate them using ethclient.EstimateGas however the reported gas costs seem incredibly underpriced, anywhere from 22K->24K gas to send tokens, and alter some boolean variables in storage? There is no way that's the correct gas cost. I'm unable to find out how websites like ethgasstation can reliably estimate gas costs, if the costs reported back by go-ethereum library barely even match real world costs?


texts: Deliver a dapp to a client, how to set as owner?

texts:
So, as a freelancer that wants to make a smart contract for a client, how do you set such client as the owner of the contract?
Would it be setting the owner variable to the eth address of the client, instead of msg.sender, when creating the contract?


texts: How to run test sample contract in the standard web browser?

texts:
I've got the Sample contract within Mix IDE which seems fine within embedded web browser.

However when go to the same URL appearing in Mix embedded page using Chrome web-browser (e.g. http://localhost:54614/index.html), it opens fine, but when I'm trying to store some values, I've got the error:

  index.html:9 Uncaught TypeError: Cannot read property 'Sample' of undefined

I believe it's missing web3.js (since it's not loaded from the source) and probably other things.

How do I solve these dependencies and integrate my sample project to run the page using a standard web browser?


texts:
Currently chaindata size is more then 10.02 GB.

Is there any solution to reduce the size of stored data?
Is there a way to store particular database and keep entirely the functionality of client (e.g. eth/geth) in this case?


texts: Calculate most frequent value in a array in solidity

texts:
I have an array something like [0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2]. I want to find the most frequent value. If two are more are having highest frequency, the first occurance should be the result. I am passing it to function to get result. I don,t know where the error is but the result is not right. My function is not working as required.

function mode(uint[] memory array) public pure returns(uint)
    {
        uint  modeValue;
        uint[] memory count;
        uint  number;
        uint maxIndex = 0;
        //uint zero=0;

    for (uint i = 0; i < array.length; i += 1) {
        number = array[i];
        count[number] = (count[number]) + 1;
        if (count[number] > maxIndex) {
            maxIndex = count[number];
        }
    }

    for (uint i =0;i<count.length; i++)
        if (count[i] == maxIndex) {
                modeValue=count[i];
                break;
            }

    return modeValue;
    }```


texts: onlyOwner modifier works in truffle test but not in console

texts:
In the following code, the console.log returns an empty string, but the truffle test works fine!

const certificate = contract(Certificate);
certificate.setProvider(web3.currentProvider);
var certificateInstance =
certificate.at("0xfcdf59a5e2a43059d3d469f4aa31534d6c0d00b7");
return certificateInstance
    .ownerName() // state variable in the contract
    .then(function(_ownerName) {
      console.log(_ownerName);
      // getParam2 is the function with onlyOwner modifier
      return certificateInstance.getParam2({ from: owner });
    })
    .then(function(_value) {
      console.log(_value);
    });

Below are my truffle test code:

...
return Certificate.at(certAddress);
}).then(function(instance){
    certInstance = instance;
    return certInstance.getParam2({from: owner});
}).then(function(_value){
    assert.equal(_value, "param2value", "modifier function returns correct value"
})


texts: Web3py. Error getting events using Infura: "The method eth_newFilter does not exist/is not available"

texts:
I'm trying to get all events from contract, but get error:
"ValueError: {'code': -32601, 'message': 'The method eth_newFilter does not exist/is not available'}"

I'm using Web3py and Infura. My code:

myfilter = <myContract>.events.<MyEvent>.createFilter(fromBlock=0)

or

myFilter = web3.eth.filter({"address": <myContractAddress>})

Why is this error? How do I get events?
Help me please.


texts: MetaMask - can't get ethereum network id

texts:
I'm totally new to ethereum and at the moment just finishing my first tutorial from Dapp University.
Since the tutorial is from 2019 there is some deprecation code. I was able to find the current solutions, but I got stuck at the part where I need to get the networks id.
In the tutorial I am using the ganache as my testing blockchain and according to json the ganache network id is 5777
"networks": {
    "5777": {
      "events": {},
      "links": {},
      "address": "0xcCAE784C66CF099745F5D1E1BE7c4a76fB39f9F2",
      "transactionHash": "0x6395d9dca26bc4e3e7ef88b2e02c8c0a20f9a870e0cdf895993b40471dc47261"
    }
  },
  "schemaVersion": "3.4.0",
  "updatedAt": "2021-05-05T12:28:30.450Z",
  "networkType": "ethereum",
  "devdoc": {
    "methods": {}
  },
  "userdoc": {
    "methods": {}
  }

Now the way to get the id in the video was to use the method:
const networkId = await web3.eth.net.getId();

However that produced the error:
TypeError: Cannot read property 'net' of undefined

And also on top of that there was a deprecation notice as metamask no longer injects web3.
I found out that instead of the deprecated code I can access metamask methods using window.ethereum instead of web3.eth.
But I couldn't find the corresponding getId() method. When I tried window.ethereum.net.getId(); I got Cannot read property 'getId' of undefined error.
The closest I got was using this method I found in https://metamask.github.io/api-playground/api-documentation/
window.ethereum.request({ method: 'net_version' })
But instead of obtaining ganache id which should be 5777 I got 1.
So now I'm not sure if this is the right method and I'm simply not on ganache or this is something completely else and I just can't find the method I am looking for.


texts: Undeclared identifier when compiling with truffle compile

texts:
I have this contract and can't figure out where's the problem. Any ideas? (I'm a noob in solidity, just started a few days ago).

HelloWorld.sol file:

mapping (address => uint) balances;

function HelloWorld() {
    balances[msg.sender] = 1000;
}

function getBalance() public constant returns(uint) {
    return balances;
}

function sendCoin(address receiver, uint amount) public constant returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;

    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    return true;
}

Moon.sol file:

mapping (address => uint) balances;

function Moon () {
    balances[tx.origin] = 1000;
}

function getBalance() public constant returns(uint) {
    return balances;
}

In the Moon.sol file I missed out "mapping (address => uint) balances;".

Truffle compiler error:

$ truffle compile
Compiling .\contracts\HelloWorld.sol...
Compiling .\contracts\Moon.sol...

/C/Users/guerr/SmartContracs/firstPorject/contracts/Moon.sol:10:3: :
Undeclared identifier.
            balances[tx.origin] = 1000;
            ^------^
Compiliation failed. See above.


texts: Will there be an Ethereum Constantinople Fork coin and which exchanges would be supporting it?

texts: There are reports of nodes that still haven't upgraded their Ethereum nodes and they are on the Ethereum Constantinople fork. Would a new coin exist and which exchanges have shown support for something like this?


texts: Are tokens simply deposited to an Ethereum address?

texts: I'm just syncing Parity wallet and am wondering if I need to do something to enable the wallet to accept ERC20 tokens, such as EOS. Or do the tokens simply show up one they've been deposited to an Ethereum address.


texts: How to send a private transaction using Quorum

texts:
I'm trying to send a private transaction using  Quorum geth, but  eventually got an error :

Error: ether value is not supported for private transactions
    at web3.js:3143:20
    at web3.js:6347:15
    at web3.js:5081:36
    at <anonymous>:1:1

I notice that Quorum can't transfer balance privately, as this issuse mentioned

But  even if I specify ether value to 0, the error still remain :

> eth.sendTransaction({
    from: eth.accounts[0],
    to: "0xca843569e3427144cead5e4d5999a3d0ccf92b8e",
    privateFor:["QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc="],
    value: 0
})

Enviroment :

Geth
Version: 1.8.18-stable
Git Commit: 51e1f6354665ed7f6b098bf53ce3fd5944e14cb6
Quorum Version: 2.4.0
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1337
Go Version: go1.13.5
Operating System: linux
GOPATH=
GOROOT=/tmp2/go


texts: Transaction not showing up in Ropsten Etherscan

texts:
Around an hour back , I initiated a transaction on Ropsten network . I used Ethereum wallet for the transaction. Attaching a screenshot of the transaction below . But till now I cannot see this transaction on Ropsten network

What could be the reason for this?


texts: Storing a dynamic array of structs which contains a dynamic array of structs

texts:
I am trying to create the following objects:

Bounty[] public bounties;

struct Bounty {
    address issuer;
    uint256 fulfillmentAmount;
    uint256 balance;
    bool bountyOpen;
    Fulfillment[] fulfillments;
    mapping (bytes32 => bool) used;
}

struct Fulfillment {
    uint256 fulfillmentAmount;
    address fulfiller;
}

A brief explanation is that I want to have an array of "Bounties" which can be satisfied multiple times. Each bounty has a number of properties, one of which is an array of "Fulfillments". The fulfillments describe and store the different times the bounty was fulfilled.

When trying to create a new bounty, I use the following:

bounties.push(Bounty(msg.sender, _fulfillmentAmount, msg.value, true));

This gives me the error that I have one fewer parameters than needed to initialize the object, because I am missing the Fulfillment[] array. (I do not need the mapping to be initialized.)

When I try to initialize with the array object like so:

bounties.push(Bounty(msg.sender, _fulfillmentAmount, msg.value, true, new Fullfillment[](0)));

I get the following error:

  UnimplementedFeatureError: Copying of type struct ContractName.Fulfillment memory[] memory to storage not yet supported.

I have looked at a number of similar questions: [1] [2] [3]

They seem to imply that creating an object like this is not supported.
Instead, I could turn Fullfillment[] fulfillments into:

uint fulfillmentLength;
mapping(uint => Fullfilment) fullfillments;

Keeping track of the length myself and doing some tricks to replace push().

Is this the best practice here? Or should I look at other alternatives like having the fulfillments be an object outside of the Bounty.

This is what Bounties-Network/StandardBounties seems to do:

https://github.com/Bounties-Network/StandardBounties/blob/master/contracts/StandardBounties.sol

Looking for best practice advice here.


texts:
I want to learn how to write and use Ethereum smart contracts. I have geth installed on my computer. I have experience with SQL and write some JavaScript and HTML. Other than that I know nothing about it. I need book or an organized set of tutorials to lead me through this. Are there any tutorials out there that start from the beginning and move to the advanced?

Thanks, John


texts: How to get all transaction lists of local ethereum wallet using web3.py?

texts:
I have developed django project that have local ethereum wallet using web3.py.
I want to get transaction history of my wallet.

But I have no way.
Please help me.


texts: Is there a way to get revert message by my client?

texts:
I have a smart contract with this simple function:
function addUser( string memory _username, string memory _nome, string memory _cognome, string memory _email) public  isOwner() {
    require(bytes(_username).length > 0 , "Username vuoto");
    require(bytes(_nome).length > 0 , "Nome vuoto");
    require(bytes(_cognome).length > 0 , "Cognome vuoto");
    require(bytes(_email).length > 0 , "Email vuota");

    if(checkUsernameExisting(_username)==0)
    {
        userCount ++;
        users[userCount] = User(userCount, _username, _nome, _cognome, _email);
        emit UserAdded(userCount, _username, _nome, _cognome, _email);
    }
    else
    {
        **revert("User already exists");**
    }

}

I interact correctly with its in javascript using truffle
...
App.partecipazioneContest = await App.contracts.PartecipazioneContest.deployed()
...

try {
   ...
  await App.partecipazioneContest.addUser(username, nome, cognome, email);

} catch (error) {
  window.alert(error);
}

Is there any way to get the reason message? (in this case "User already exists").
In my catch block I get an error but I can not find the way to get the revert error message.
(emit event doesn't work).
(Update)
The error that I catch:
errorStatusError: Transaction:
0x247eeddd17eccae3376aea92587fd395d46202d78bb3aa0a9d4a0b05607de7e3 exited
with an error (status 0).
Please check that the transaction:
- satisfies all conditions set by Solidity `require` statements.
- does not trigger a Solidity `revert` statement.


texts: Synchronisation issue on Mainnet, testnet and private network

texts:
I am just unable to synchronise on any kind of network either main network , testnet and not even on private network.

I have updated my geth instance to a newer version - Geth/v1.5.9-stable-a07539fb/linux/go1.7.3.

I used the following command for the testnet as well as the mainnet - geth --fast --cache=512 console and with --testnet flag too , but kept getting the following errors -

Synchronisation failed: receipt download canceled (requested
Synchronisation failed: block body download canceled (requested)
Synchronisation failed: state data download canceled (requested)

And as a result when i use eth.blockNumber in the geth Javascript console, it returns 0.

Also i am facing error in syncing of a private testnet as given in this link Synchronisation issue on private network -

How can i solve the synchronisation issues ?

EDIT - I just noticed that the currentBlock value is increasing when i see the output of eth.syncing. So should eth.blockNumber returning 0 be an issue ?


texts: Is there an api to get list of transactions from non forked blockchain / classic Ethereum

texts:
Now that the hard fork is complete, there are two blockchains - the forked one for ETH (at 1920000) and the original is for the ETC.

The etherscan.io provide an api to get list of transactions for ETH but I do not think that they will support the non forked blockchain (ETC).


texts: Broadcast another account's signed transaction to the Ethereum Network

texts:
Is there a way to broadcast another account's transaction to the Ethereum network using Geth?

This question really won't make sense unless I describe my set-up.

1) Device A has a private key. It creates a transaction, signs it, and sends it to Device B

2) Device B is actually connected to the ethereum network, but doesn't know Device A's private key. It receives A's signed transaction and sends it to the network, no questions asked.

I'm running into a couple problems with this set-up. The first is the fact that Ethereum transactions require a nonce that must be strictly increasing with each of Device A's transactions. What happens if Device A crashes and loses its private key? How the heck would a person recover the value of their nonce in addition to their private key? Perhaps I am misinterpreting the nonce itself -- Does the nonce limit the private key's transactions, or is it increased when a node sends a transaction? In the latter case, I imagine I would need to poll Device B to obtain a nonce before signing the transaction. Is there any other data I would want to get, like the gas price?

I haven't gotten to step 2 yet, but I'm expecting this to be the real difficulty. Does geth even allow you to send another account's signed transaction? Surely there must be some core protocol beneath geth that I can access to do this for me?

Is it really impossible for something like this to be done using Ethereum's account system?


texts: What is the most efficient/optimal way to upgrade a factory contract? Let's say I have a factory contract which can generate 3 different child contracts, how can it be upgraded to be able to generate 5 different child contracts in the future instead of 3?


texts: Calling contract method internally from geth code

texts:
On developing a custom geth fork there is the need to call a specific hardcoded smart contract when ETH transfer occur. This is not an Ethereum normal behaviour but a new feature we want to implement on the fork. The calling of the contract will be done inside the very transaction that triggers the whole process, so creating a new transaction to call the contract is not an option. The atomic transaction must include the internal call of the contract (this special contract will have a hardcoded address all the time).

The main change of the code in this fork will be at https://github.com/ethereum/go-ethereum/blob/master/core/evm.go#L93

// Transfer subtracts amount from sender and adds amount to recipient using the given Db
func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
    db.SubBalance(sender, amount)
    db.AddBalance(recipient, amount)
}

to something like this:

// Transfer is performed on an ERC-20 contract
func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
    mySpecialContract.transfer(recipient, amount {from: sender})
}

So, questions are:

Is that possible to do?

Should I define the "mySpecialContract" object first? How?

How can GoLang call an specific method of a given contract?

Having the address of the contract, the method name and parameters (the whole ABI actually) is there any example code to invoke this kind of methods?

By the way, I feel like there is a function on geth code that could do that: core\vm\evm.go(43)

// run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {

Someone can confirm? Thx!


texts: What happens when two people call a transfer function at the same time?

texts:
I am doing a decentralized market of tokens ERC 721 and I have the problem that if two people give to buy the token at the same time, I do not know what would happen.

Is there any way, without spending gas, to know if there is someone in the period of purchase of that token?
Since it would be paid with FIAT money, once it receives the payment, it would call the transfer function. So I have the problem that if the two transfers are made in the same block, I do not know which of the two would be made. I have tried to set a variable that changes to HOLD while someone is in the buying process, but it would cost gas.
It could be done from the server side, a queue for the purchase, but I would like to do it from the smart contract part directly.

In this question, someone says that all requests would be made and the last one would persist. But in my case, being a transaction, the first one who does it takes the token and the second one no longer has a token to receive.


texts: Uniswap V1: Why does EthToTokenInput not refund overpaid ether?

texts:
ethToTokenInput on the Uniswap V1 contract converts all the sent ether to tokens and transfers the tokens to the recipient.

Lets assume 1 ether buys you 3.9 tokens according to getInputPrice(). If you send 1 ether with ethToTokenInput(1, ...), the contract will send you 3 tokens even though 3 tokens only cost rougly 0.8 ether.

Why does this function not refund the remaining ~0.2 ether?
Is the "overpaid" ether distributed among liquidity providers (added to the eth_reserves)?


texts:
Is there a blockchain, or a smart contract designed to store user passwords?

I am using a proprietary password manager and have hundreds of passwords stored there. I am just a bit worried that the service once goes down and I lose all my passwords (including encryption keys of crypto wallets). With a blockchain-based solution, the risk of this happening should be decreased in my opinion.


texts: Executing two contracts on one button click

texts:
I tried executing two contract when I press a button. Everything seems alright until the transaction page appears and I have 3 contract transactions, the first contract executed once and the second contract executed twice. I tried cancelling the duplicated transaction but it will tell me that the one I submitted has failed.

The only way for it to work is to let the first and second contract be confirmed then submit the duplicated one. But the outcome is that I submitted two transactions of the second contract. I attached a photo below for reference.

I'm quite new to solidity and also the web3. I don't really know where i'm doing it wrong. Please help

This is my full source code, the problem only starts at line 158 - 203


texts: How can we retrieve tokens which were transferred to contract

texts:
I was doing some testing and this thought popped up in my mind. I know, we can send ether to contract and I can also forward those ethers to another a/c. But, I am curious to know:

Is there a way by which we can get the tokens transferred to a contract Address back or can we transfer these tokens to another wallet address???


texts: How to deploy a contract to parity using truffle?

texts:
I get this when trying to deploy to parity -

  Writing artifacts to ./build/contracts

  Invalid JSON RPC response: "Provided Host header is not
  whitelisted.\n"

I am new to using truffle with parity here is my truffle.js file -

module.exports = {
  networks: {
    development: {
      host: "0.0.0.0",
      port: 8540,
      network_id: "*", // Match any network id
      gas: 4712388
    }
  }
};

What could be the cause?

Here is my parity node -

nohup parity --config node0.toml --tracing=on --fat-db=on --pruning=archive  &

[parity]
chain = "demo-spec.json"
base_path = "/home/satoshimaca/blockchain/parity0"
[network]
port = 30300
[rpc]
port = 8540
apis = ["web3", "eth", "net", "personal", "parity", "parity_set", "traces", "rpc", "parity_accounts"]
[ui]
port = 8180
[websockets]
port = 8450
[account]
password = ["node.pwds"]
[mining]
engine_signer = "0x00bd138abd70e2f00903268f3db08f2d25677c9e"
reseal_on_txs = "none"


texts: what replaces assigning array.length to 0 for clearing it

texts: I'm trying to follow the tutorial here and there's a line where an address array players has this done players.length = 0 which issues this error: member length is read-only and cannot be used to resize arrays. I get that only pop and push are allowed as well as assigning a new empty array. I was wondering how to perform that last operation in this context.


texts: Parity with Geth cli - Calling contract function with ether

texts:
I'm running parity with geth cli, invoked using the geth attach command. I have a contract already deployed using new call and stored in the object named  trading. This contract contains a function which accepts ethers and updates the contract state:

function buy (uint qty) payable {
  if ( qty <= availableQty){
    availableQty = availableQty - qty;
  }
}

Earlier, while using the geth cli with Ethereum itself, I could easily call the buy function via the command trading.buy.sendTransaction(10, {from:eth.accounts[0], value: 1000}). Now however with parity, the same command returns the following error:

TypeError: 'XMLHttpRequest' is not a function
at web3.js:4231:23
at web3.js:4245:19
at web3.js:6020:18
at web3.js:4995:36
at web3.js:4055:16
at web3.js:4141:16
at <anonymous>:1:1

Is there a workaround for this, or an alternate means of calling payable contract functions?


texts: how to send a transaction using sdk uniswap.org

texts:
i am trying to create and send a transaction to https://app.uniswap.org using SDK https://uniswap.org/docs/v2/smart-contracts/router02/
uniswap has two functions (swapExactTokensForETH and swapExactTokensForETHSupportingFeeOnTransferTokens) - tokens with and without fees. how to define a coin with or without commission? Otherwise, if sent incorrectly, the transaction will fail.


texts: Automatically set app instance in Truffle console

texts:
Is there a way to load the truffle console with the following variables without having to do manual type-ins on every test?

let app = await MyContract.deployed();
let accounts = web3.eth.getAccounts();

Excuse the naivety, starting out with Solidity/Truffle and asking the basic questions that don't seem to be answered (probably because they're not possible).


texts: Suppose I want to synchronize my chain. I download the blocks and state from a Node. What if this node is malicious? It can give me an alternative chain that I won't be able to distinguish from the real one. Some blocks of this alternative chain will be already finalized so I won't be able to rollback if I receive the real chain in the future.


texts: Increment a global variable - can EVM nodes overwrite each other?

texts:
I have the following contract:

contract Contract{
  address minter;
  uint gid;

  //...

  //constructor
  function Contract(){
    minter=msg.sender;
    gid=0;
  }
  function kill(){
    if (msg.sender == minter){
      suicide(minter);
    }
  }

  function createAgreement(string name){
      //blah, blah
      //...

      gid++;   //what happens here?!
  }

What happens if 100 users all call createAgreement(...) at the same time (i.e. on the same eth.blockNumber)? Do EVM nodes compete with each other?

I need gid to be unique for each of these 100 users!

Will gid be unique? Or do I need to do something different?


texts: When a Callcalled contract calls an other contract normally, who is msg.sender?

texts:
If I understand correctly CALLCODE substitute/replace (and not add) the ledger of the target contract with the one the calling contract, isn’t it ?

So that when contract Victor CALLCODE Alice, Alice does no longer use Alice´s ledger but Victor’s ledger, right ?

If true, when contract Alice calls contract Bob normally and when Bob checks msg.sender, who is msg.sender Alice or Victor ?


texts: Interacting with a Custom Token Contract

texts:
I seem to be having problems interacting with a custom token contract.  I am using truffle and ganache for my testing.  I am trying to interact with the custom token contract so MyContract can transfer tokens to an address on behalf of the custom token contract.  I do have the ABI as well.

custom token contract:

pragma solidity ^0.4.16;
import "./MintableToken.sol";
contract CustomToken is MintableToken {
  // Coin Properties
  string public name = "Custom Token";
  string public symbol = "Cust";
  uint256 public decimals = 18;
  function transfer(address _to, uint _value) public returns (bool) {
    return super.transfer(_to, _value);
  }
}

MyContract:

pragma solidity ^0.4.4;

import "./CustomToken.sol";

contract MyContract is CustomToken{

    function transferCustom(address _to, uint _value) public returns (bool) {
        require(_to != address(0));

        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender,_to,_value);

        return true;
    }
}

truffle test:

const accountfirst  = web3.eth.accounts[1];
const amount = 100;

let token = await CustomToken.deployed();
let myContract = await MyContract.deployed();

var ctoken = CustomToken.at(token.address);
ctoken.approve(myContract.address, amount);
let tx = await myContract.transferCustom(accountfirst, amount);

When i run this test i get transaction reverted. Any ideas? thank you in advance!


texts: How to decode token symbol from ethplorer.io to readable string?

texts:
I'm using Ethplorer API to retrieve token symbol for particular address. For this purpose I use Get token info:

/getTokenInfo/{address}

In most cases I receive readable symbol but for some tokens I get unreadable ones. So the following token address I get the following symbol:

"symbol":"\ud83c\udfcb\ufe0f"

How can I decode to readable string?


texts: How can I upgrade my smart contract or make it look better?

texts:
I just finished building a smart contract using HumanStandardToken contract.

Token Name: Test Network
Symbol: TKN
Decimals: 2
Address : 0x49ad97585681ffd73Af9e371241899de5cFF7fc3.

Etherscan is showing me the message:

  Warning: The compiled contract might be susceptible to ZeroFunctionSelector (very low-severity), DelegateCallReturnValue (low-severity), ECRecoverMalformedInput................

I have no idea what it is. The reputation is UNKNOWN.

How can I resolve this problem and upgrade the reputation?


texts: Trying to deploy a simple contract using node and getting the error: Unhandled Promise Rejection / Contract code couldn't be stored

texts:
I am doing an online course and trying to deploy using node. Can anyone help ID what I might be doing wrong. Thank you for any help! The error is below, followed by the js code.
iii@iii:~/Digital Ledger/inbox$ node deploy.js

Attempting to deploy from account 0xd268143B6FBD9BC6533F778052710C962eaAa68C
(node:18067) UnhandledPromiseRejectionWarning: Error: The contract code couldn't be stored, please check your gas limit.
    at Object.TransactionError (/home/iii/Digital Ledger/inbox/node_modules/web3-core-helpers/src/errors.js:93:21)
    at Object.ContractCodeNotStoredError (/home/iii/Digital Ledger/inbox/node_modules/web3-core-helpers/src/errors.js:102:21)
    at /home/iii/Digital Ledger/inbox/node_modules/web3-core-method/src/index.js:394:40
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:18067) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 15)
(node:18067) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

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

const provider = new HDWalletProvider('olive comic debate nominee various affair order margin fiscal zoo rocket sibling', 'https://rinkeby.infura.io/v3/0cfbe0ad9aa14310a1aab91c683d735c');

const web3 = new Web3(provider);

const deploy = async () => {
    const accounts = await web3.eth.getAccounts();

    console.log('Attempting to deploy from account', accounts[0]);

    const result = await new web3.eth.Contract(JSON.parse(interface))
      .deploy({ data: bytecode, arguments: ['Hi'] })
      .send({ gas: '1000000', from: accounts[0] });

    console.log('contract deployed to: ', result.options.address);

};
deploy();


texts: How is "by-block consensus" different from " by-chain consensus"?

texts:
I see Vlad Zamfir was able to demonstrate by-block consensus has great merit to Vitalik.  Is it better than by-chain consensus?  What are the risks associated with developing by-block consensus into future versions of Ethereum?

Source: https://blog.ethereum.org/2015/12/28/understanding-serenity-part-2-casper/


texts: What are the brackets for in SingularDTV crowdfunding contract

texts:
I can't figure out what the brackets are for in this line of code, initializing the SingularDTVFund:

SingularDTVFund constant singularDTVFund = SingularDTVFund({{SingularDTVFund}});


texts: Are events only useful for the frontend components?

texts: I'm seeing more and more ways as I learn where functions can be run on the client side. I'm looking at events. Does the Ethereum client (say, Metamask) load all the events from a contract when I open the app on a webpage? Is that what events are mostly for?


texts: Solidity: Examples of fail safe code for security

texts:
In the wiki's Security Considerations code,
the Include a Fail-Safe Mode  section says:

While making your system fully decentralised will remove any intermediary, it might be a good idea, especially for new code, to include some kind of fail-safe mechanism:
You can add a function in your smart contract that performs some self-checks like “Has any Ether leaked?”, “Is the sum of the tokens equal to the balance of the contract?” or similar things. Keep in mind that you cannot use too much gas for that, so help through off-chain computations might be needed there.
If the self-check fails, the contract automatically switches into some kind of “failsafe” mode, which, for example, disables most of the features, hands over control to a fixed and trusted third party or just converts the contract into a simple “give me back my money” contract.

What are some exemplar self-checking and fail safe functions that I could look at to see how this is done?


texts: How to interact with smart contracts using Truffle console?

texts:
This is a super basic question so I apologize in advance, but I am trying to learn how to develop and deploy smart contracts and I couldn't seem to find an up to date answer on this. How do I interact with smart contracts once I have compiled and migrated them onto the blockchain with truffle? For example, I am trying to run a HelloWorld smart contract that looks something like this

contract HelloWorld {
    string greeting;
    function HelloWorld() public {
        greeting = "Hello, World!";
    }
    function sayHello() public {
        return greeting;
    }
}

If I wanted to call the function sayHello(), how would I be able to do so?


texts: How to store 25 char string on erc20 token and cost?

texts: I’m wanting to be able to create an ERC20 token that stores a 25 character long string with it. Just wondering if this is actually possible? Also if it is possible I’m gathering from the posts I’ve read similar to it you would need to pay additional gas for it, would that cost be expensive if I was to have a lot of tokens? (Eg. > 10,000 unique tokens)


texts: Gas limit and price in send raw transaction

texts:
trying to compile a contract and then send it to the network.  The current error I'm getting is

Error: transaction underpriced

Here is my code for compiling the rawTx.  I'm on Ropsten, and the gas price is: 21000000000 and the gasLimit latest is: 4712388(from the console.logs)

const gasPrice = web3.eth.gasPrice;
console.log(gasPrice);
const gasPriceHex = web3.toHex(gasPrice);
var glimit = web3.eth.getBlock("latest").gasLimit;
console.log(glimit);
gasLimitHex = web3.toHex(glimit);

nonce =  web3.eth.getTransactionCount(account1) ;
nonceHex = web3.toHex(nonce);

var payloadData = solidityFunction.data;

var rawTx = {
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    to:contractAddress,
    from:account1,
    value: web3.toHex(web3.toWei('.01', 'ether')),
    data: payloadData
};


texts: Revert error when sending ERC20 token on Ethereum mainnet fork

texts:
I am trying to send an ERC token (USDC) on the Ethereum Mainnet fork made with ganache-cli --fork. The transfer is made from the unlocked account that has both ETH and USDC balances available to the test account generated by the Ganache. The code looks as follows:
const erc20_abi = require("./erc20_abi.js");
const usdc_addr = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
const usdc_holder_account = "0x....";
const usdc = new web3.eth.Contract(erc20_abi, usdc_addr);
usdc.methods.transfer('0x...', new BN('100000000'))
    .send({from: usdc_holder_account})
    .then(function(result){
      console.log(result);
    });

However, I get the 'revert' error from the forked EVM:
{ '0x3...': { error: 'revert', program_counter: 1704, return: '0x' },
 stack: 'c: VM Exception while processing transaction: revert\n ....}

I first thought that the USDC account was not actually unlocked but I managed to successfully send ETH from it to my test account. So, I am confused what the problem might be and cannot find a 'revert' reason.


texts: Can string be changed to equivalent bytes and bytes32 in solidity?

texts:
I was wondering if it is possible to convert a string to a bytes32 or bytes in solidity like this, I want an input in string and require an equivalent bytes32 and bytes both.

input string = "0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff"
output bytes32 = 0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff

input string = "0xd724b8592f7962a584cfedcacc2e308292f19f5245be8bdecb42354277d3a8674266a8d0b0f2fcdcdc42bc295e2bf6378da440ed7bcb022a154c8a28a825ddb301"
output bytes = 0xd724b8592f7962a584cfedcacc2e308292f19f5245be8bdecb42354277d3a8674266a8d0b0f2fcdcdc42bc295e2bf6378da440ed7bcb022a154c8a28a825ddb301
I have already looked into this link: How to convert a bytes32 to string but this is not working and returning different values than above.


texts: Deploying a contract with a "payable" constructor and including input parameters?

texts:
There is a useful Solidity contract HERE. However, there are two things at time of its deployment:

(1) The first thing is the contract balance since its constructor is payable.
(2) And the second one is the constructor's parameters value ((address **_recipient**, uint256 **duration**))

To deploy a contract I use web3.js 1.0.0-beta.34. Here is the steps I do to deploy this contract:

Web3 = require("web3")
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const bytecode = '0x1234 ....
const abi = ....

web3.eth.personal.unlockAccount('0x123...', 'password')

var thisContract = new web3.eth.Contract(abi, {
    from: '0x123...',
    gasPrice: '20000000000'
});

thisContract.deploy({ data: bytecode }).estimateGas(function(err, gas) { console.log(gas); });

thisContract.deploy({ data: bytecode }).send({
        from: '0x123...',
        gas: 5000000 ,
        gasPrice: '3000000000'
    },
    function(error, transactionHash) {
        console.log(error);
        console.log(transactionHash);
        console.log('function exec');
    }).then(function(newContractInstance) {
    console.log('Contract Instance:' + newContractInstance.options.address);
});

However, I do not know where in the above process I must determine (1) the contract balance (since its constructor is payable) and (2) the constructor's parameters value (i.e. (address _recipient, uint256 duration)) ?

Note: I guess first I have to deploy this contract using remix where I determine the constructor's parameters values and then use generated bytecode and abi by remix in the web3.js above code. However, I am not sure where can I use value: web3.toWei(1/*contract balance*/, 'ether').


texts: My etherwallet.com password is overwritten by safari and only have partial private key

texts:
I only have the Keystore File (UTC / JSON) and can proof that the ETH sent to myetherwallet came from my poloniex account.
I made a screenshot from the private key when I created the wallet, however later I found out that the complete private key is not displayed but just partially. I have like 30 from 60 characters in total fwiw.

Also the private key I copy/pasted once on my phone to get into the wallet. I have been calling around to Apple and what not to ask if its possible to get this old password back that has been overwritten by safari but everyone says this is impossible, same for the clipboard history.

Is there still hope for me?

How can I regain access to my account?

I really hope someone can help me out with this and that I made my story clear.

new information

I found the json number connected to this mew account on a screenshot, can this help me to regain access to my account?


texts: Will event be emitted on failed transaction?

texts:
require(address(0) != address)
_mint(address, 1)
emit(address, some_other_info)

If any part fails and transaction fails in general, will the event be emitted?
Can the same event be emitted multiple times? Should I keep track of it? How safe is it? Can hackers imitate events somehow?


texts:
My contract instance is created like:

var instance = web3.eth.contract(abi).at(addressA);

instance.sendTransaction is showing error in this case, what's the correct way to send ether to this contract?


texts:
i have a question:
in the web wallets(hosted wallets)when user want to make a transaction and send the information to the wallet server , can a one change the information(man in the middle attack)?


texts:
Good day all,

Can someone please point me to the right direction. I am currently running a clayminer mining in ethermine and my average hashrate is 12mHs. I have a 6 GPU rig and my rog consists of:

6 Palit GTX 1070 jetstream 8Gb
MSI Z270 M7 for motherboard
i3 7100 kaby lake
Windows 10 64 bit

I have updated all the GPU drivers. I downloaded the MSI afterburner and tried to set my mem clock to +800 and still no good. Each gpu only has around 2 MHs what ever i do.

Please help me.


texts:
I got the following errors while trying to deploy my smart contract:

sers-Air:lottery user$ node deploy.js

internal/modules/cjs/loader.js:582

    throw err;

    ^

Error: Cannot find module 'truffle-hdwallet-provider'

    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)

    at Function.Module._load (internal/modules/cjs/loader.js:506:25)

    at Module.require (internal/modules/cjs/loader.js:636:17)

    at require (internal/modules/cjs/helpers.js:20:18)

    at Object.<anonymous> (/Users/user/Documents/prod/EthereumCasts/lottery/deploy.js:1:88)

    at Module._compile (internal/modules/cjs/loader.js:688:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)

    at Module.load (internal/modules/cjs/loader.js:598:32)

    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)

    at Function.Module._load (internal/modules/cjs/loader.js:529:3)

users-Air:lottery user$

I also tried to change it to const result = await new web3.eth.Contract(JSON.parse(interface))

.deploy({ data: '0x' + bytecode })

.send({ from: accounts[0] });

as suggested in the other thread but it didn't work. My github repository:

https://github.com/damianjnc/lottery

I did npm install --save truffle-hdwallet-provider@0.0.3 but now got that error:

users-Air: lottery user$ node deploy.js

Attempting to deploy from account 0x14Ca642FA083121605fc860dB0024254D3FaCd61

(node:31456) UnhandledPromiseRejectionWarning: Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!

at /Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-method/src/index.js:375:45

at tryCatcher (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/util.js:16:23)

at Promise._settlePromiseFromHandler (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/promise.js:497:31)

at Promise._settlePromise (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/promise.js:555:18)

at Promise._settlePromise0 (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/promise.js:600:10)

at Promise._settlePromises (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/promise.js:679:18)

at Async._drainQueue (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/async.js:125:16)

at Async._drainQueues (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/async.js:135:10)

at Immediate.Async.drainQueues (/Users/user/Documents/prod/EthereumCasts/lottery/node_modules/web3-core-promievent/node_modules/bluebird/js/release/async.js:16:14)

at runCallback (timers.js:705:18)

at tryOnImmediate (timers.js:676:5)

at processImmediate (timers.js:658:5)

(node:31456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

(node:31456) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

users-Air:lottery user$


texts: Truffle Console: How to print Ether values for the accounts?

texts:
I am trying to follow a tutorial available at:
medium Just Dev
> getBalance = web3.eth.getBalance
> balanceInEth = address => web3.fromWei(getBalance(address).toString())

I got errors so I used the following command:
> getBalance = web3.eth.getBalance;"Testing"
'Testing'
truffle(development)> balanceInEth = async(address) => web3.utils.fromWei(await     web3.eth.getBalance(address))

But they are generating huge error:

Thrown: TypeError: Cannot read property 'match' of undefined
at ReadStream.onData (readline.js:1073:36)
at emitKeys.next ()
at emitKeys (internal/readline.js:424:14)
at ReadStream.EventEmitter.emit (domain.js:448:20)
at ReadStream.emit (events.js:198:13)

I was told to use following command at:
Error Truffle Console: web3.fromWei is not a function
truffle(ganache)> web3.eth.getAccounts(function(err, acc) { accounts = acc });
truffle(ganache)> const boo = async () => { return web3.utils.fromWei(await web3.eth.getBalance(accounts[0]), 'ether'); }
truffle(ganache)> boo()
'99.0015542'

The above commands are printing the account values for acc1, victim and attacker but when I am executing the transaction for victim, I am getting a huge error message:
truffle(development)> options = { from: acc1, to : victim.address,
 value: web3.utils.toWei('11', 'ether')}

{ from: [AsyncFunction: acc1], to:
'0xA3339bb424303D6F58B1260872c9C2DBF840e771',   value:
'11000000000000000000' }

truffle(development)> victim.deposit.sendTransaction(options)

Thrown: { Error: Returned  error: from not found; is required
at evalmachine.:0:16
at sigintHandlersWrap (vm.js:288:15)
at Script.runInContext (vm.js:130:14)
at runScript (/home/zulfi/.nvm/versions/node/v10.22.0/lib/node_modules/truffle/build/webpack:/packages/core/lib/console.js:227:1)

Somebody please guide me how to print account values on truffle console.
Zulfi.


texts: How can I sign a piece of data with the private key of an Ethereum address?

texts: I would like to use the key pair of one of my Ethereum accounts to sign a piece of data.  How can this be done?


texts:
Why does Ether get overloaded sometimes with 12 second blocks and a gas limit that could be changed by miners? If the network starts getting clogged, theoretically can't miners increase the gas limit?

For example, with bitcoin the 1mb block size causes congestion.


texts: Minting tokens that cover client's Tx fees and can only be used to interact with 1 smart contract

texts:
I'm working on a voting application. Is there a way to centrally mint tokens, hand them out to eligible voters/addresses, and only let users with this token vote? If so, can this token cover the transaction fees? I wouldn't want the end-user paying for the Tx fees.
In other words, I want a central authority to cover the transaction fees of the client. I can't simply hand them ether because they can use that to buy something else instead of using it to cover the expenses of running the smart contract.
If there is already a solution out there for this, can you please comment the link to it? A tutorial would also be really helpful. Thanks!


texts: The called function should be payable if you send value and the value you send should be less than your current balance. WITH NON-Payable functions

texts:
I have the following functions
function balance() public view returns(uint152) {
        return uint152(IERC20(token).balanceOf(address(this)));
    }

    function balance1() public view returns(IERC20) {
        return IERC20(token);
    }

The first one throws the error mentioned in the title, but the second one works just fine. Can you please help me understand, why does the function needs to be payable when I'm just checking the balance of a certain token. Thank you.


texts:
The ultimate disincentive system in Casper is forking the contract resulting in loss of the attacker's stake. Is this mechanism possible with any smart contract?

I'm trying to write an oracle contract that incentivizes consensus on some real-world data and want to be able to fork the contract if it comes under attack.


texts: What will happen when an ethereum node loss internet connection?

texts:
Will it reconnect to the ethereum network upon establishing internet connection again automatically and sync Data ?
Can we perform transaction and calls on the offline(no internet connection) ethereum node specifically ? suppose we have direct access to that particaular node and we can directly intereact with it.


texts: Solidity-how to transfer ether from an account to a smart contract as deposit

texts:
I just started to learn Solidity. In the SimpleAution contract, there are two functions, bid() and withdraw(), the former iniating a bid, transfering some ethers to the contract as deposit, the later refund the biders. Their codes as follow,
function bid(uint bidAmount) public payable {
    require(now <= auctionEndTime);
    require(bidAmount > highestBid);
    ///
    require(msg.value == bidAmount);

    ///this represents current contract address
    //address(this).transfer(bidAmount);
    ///address(0) is empty address
    if (highestBidder != address(0) ){
        pendingReturns[highestBidder] += highestBid;
    }

    highestBidder = msg.sender;
    ///highestBid = msg.value;
    highestBid = bidAmount;

    emit HighestBidIncreased(highestBidder, highestBid);
}
function withdraw() public returns (bool) {
    uint amount = pendingReturns[msg.sender];
    if (amount > 0){
        ///clean the returning fund first
        pendingReturns[msg.sender] = 0;

        ///then transfer fund back to msg.sender
        if (!msg.sender.send(amount)){
            /// if send back fund fail, give amount back to pending fund
            pendingReturns[msg.sender] = amount;
            return false;
        }
    }
    return true;
}

withdraw() is easy to understand, refund a bider through "msg.sender.send(amount)". However bid() doesn't have any code that indicates msg.sender transfering ethers to the contract as deposit. I tried to use "address(this).transfer(bidAmount);" to do the job, but not so sure it is right. Need help,many thanks.


texts: Is there an explorer like Etherscan for Remix JS VM sandbox blockchain

texts: I created a contract and did some transactions. I would like to explore the transactions in the sandbox blockchain in my brower (Chrome). But the tx hash is not found in the REMIX VM Debugger http://etherscan.io/remix?txhash= ... ?


texts: Someone referred me to the chaindata folder to troubleshoot a problem I am having with Ethereum-Wallet/Mist.  How can I find it?


texts: Checking if an item present in an array in Solidity

texts:
I want to check whether a specific item is included in an array or not. For example, consider the following array.
uint[] a = [1, 2, 3, 4]
Is there any way that I can get true if I have given 4, and get false if I have given 5 to check for inclusion in the array?


texts: The "+" token button is not showing in the "Tokens Tab" on my "MetaMask'.  It says :There was a problem loading your token balances."  Any and all help is appreciated.


texts: GETH accounts imported without my knowledge

texts:
I expose only port 30303, not 8545. But when I issue commands eth.accounts. I found these accounts were imported without my knowledge:

"0xe4fe1fb7e693c529f5a95dd8b1714d1acfdbd058",
"0x0a320acfe5f78d9b689f6dd1fd848ee65a790925",
"0xce3236d5e92d6c5540c51f8378297d4fad4ce6fd",
"0x433ce9234c6cad07244177ddb8fa7614d4626358",
"0x99c979f0302da89025de1e7d812e9d19a4ff9cd3"

Is my GETH hacked? Or these are my peers? My GETH is running extremely slow recently and failed to catchup with the sync


texts: testing fallback function with truffle js

texts:
SOLUTION BELOW

How do I go about testing the following fallback function:

function () public payable {
  revert();
}

being that the function does not have a function name, what do I need to do to test it? I tried using a function name that does not exist like this:

it("should not accept ETH deposits", async function() {
  let xferAmt = web3.toWei(0.5, "ether");
  await contract.dummyfunction({value: xferAmt}).should.be.rejectedWith(EVMThrow);
})

But truffle complains about the dummyfunction not being a function.

Thanks.
A.

SOLUTION

function () public {}

test:

it("should not accept ETH deposits", async function() {
  let xferAmt = 1;
  await contract.sendTransaction({value: xferAmt}).should.be.rejectedWith(EVMThrow);
});


texts: how can a contract destroy other contract (suicide accounts)?

texts:
I learnt from the yellowpaper that at the end of a contract execution, there could be a list of suicide accounts that will be removed.

my question is, why and how would one smart contract remove other accounts (smart contracts).

for example, I understand the need of self destruction. when one smart contract is finished, it destructs itself. but why do you need to destroy others and how?

Can my smart contract destroy a contract owned by another person?

also, engineering wise, how this destruction is implemented? for example, do we actually modify previous blocks' contents related to destructed accounts? or we just update the change in the tree structure?


texts: How can I debug a my Solidity smart contract with a GUI?

texts:
Is there any way to debug a Solidity smart contract with a GUI, like remix?

How can I do it for both testnets and mainnet?


texts: Can I reboot my router while geth fast syncing?

texts:
dumb question from noob here. I have started to sync with command geth --fast --cache=1024 for more than 3 days now, and I am still not finished syncing yet (still around 1 million again). Somehow I sense that my internet connection is getting slower with each day and I am wondering if I reboot my router it can help speed things up again.
So my questions are:
Is my internet get slower because of the sync process (my connection is in more than 30++ billion bytes);
if I reboot my router (not closing the console with geth process) in hoping that it can help speeding things up again (maybe it will clear the router cache, etc) do I need to redo my sync again?
Thanks for anyone who try to help, just completely confused now.


texts:
I have written a simple nested macro in LLL, but I can't get it to reduce to the simplest expression when calling the compiler with the optimization option. My macro looks like this:

(def 'mcopy (pos loc length) (codecopy (sub (mul pos 0x2) length) loc length))

Reading the LLL compiler documentation, it seems as though invocation of the above with constants should produce a reduced assembly expression with constants, like codecopy(x, b, c), and not codecopy(sub(mul(a, 0x2), c), b, c) as I see in the disassembled bytecode. I've read elsewhere that not all optimizations are guaranteed to occur, but I was wondering if there was a simple way to fix this, aside from writing my own preprocessor on the .lll source code.


texts:
I wan to implement zeppelin's destructible in my contract so destroyAndSend() after a function finishes executing, like this (pseudo-code):

pragma solidity 0.4.19;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/lifecycle/Destructible.sol';

contract SingleTx is Ownable, Destructible {

  /*
   *  Storage
   */
  mapping (uint => Transaction) public transactions;
  address[] public owners;

  struct Transaction {
      address destination;
      uint value;
      bytes data;
      bool executed;
  }

  /// @dev Allows anyone to execute a confirmed transaction.
  /// @param transactionId Transaction ID.
  function executeTransaction(uint transactionId)
      public
      ownerExists(msg.sender)
      confirmed(transactionId, msg.sender)
      notExecuted(transactionId)
  {
      if (isConfirmed(transactionId)) {
          Transaction storage txn = transactions[transactionId];
          txn.executed = true;
          if (txn.destination.call.value(txn.value)(txn.data)) {
                destroyContract();
              }
          else {
              txn.executed = false;
          }
      }
  }

  /// @dev Destroys contract after one transaction is executed.
  function destroyContract()
      private
  {
    ContractDestroyed();
    destroyAndSend(owners[0]);
  }

}

when I try to test using Truffle test, I get a revert error:

Error: VM Exception while processing transaction: revert

If I comment out destroyContract(); everything works as expected.

Any ideas?


texts: In my contracts I've been placing pragma solidity ^0.4.2; Without knowing my compiler is outdated at 0.4.16! Interestingly, all contracts still compile and are able to migrate to testrpc. Still, I would like to make sure, is it possible this could introduce unseen errors in the future?


texts: Which token standard should be use to create different tokens for different users?

texts:
I have read several differences between fungible and non fungible tokens. It cleared my few doubts though, I have few more remaining.

I have requirement to create a platform on which users can register and create their own token with passing token name, price and so. Is it possible to develop such contract to create different token for different users? And which token standard should be used in this scenario ERC721 or ERC1155


texts: What does data represent in the uniswap swap function?

texts:
The swap function in uniswap v2 is as follows:
function swap(uint amount0Out, uint amount1Out, address to, bytes
calldata data) external;

I was wondering what the 4th input to the function 'data' represents? What data needs to be sent here to create a swap?
The function is described here:
https://uniswap.org/docs/v2/smart-contracts/pair/#swap-1
And the github code is here:
https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol
Thanks in advance


texts: Can MEW (Myethereumwallet) secured by a trezor participate in token distributions?

texts: Can MEW (Myethereumwallet) secured by a trezor participate in token distributions like MEW secured by a UTC or Private Key? Can the MEW secured by a trezor call arbitrary contract methods and export private key through a smart contract?  Please help.  One of the ICOs I want to go for requires that from a wallet and I am not sure if MEW with a Trezor is safe to send the ETH from.


texts: Are there any bootnodes for the revived Ropsten testnet?

texts:
After Ropsten is revived from the attack, I tried syncing with geth --testnet removedb && geth --testnet --fast but I got inconsistent results every time.

Currently, eth.getBlock('latest').number returns ~963k where as https://ropsten.etherscan.io/ shows the latest block as ~834k. Am I connected to peers that are still running the attacked Ropsten? Are there trusted bootnodes for the new testnet?

I'm using Geth version 1.6.0-stable.

Thanks


texts: What is the algorithm to select random validators in PoS?

texts: As I know, Ethereum Casper PoS implementation randomly selects 250 validators from the validator poll for an epoch. What is the random algorithm for this selection?


texts:
I'd like to read the contract balance (amount of unspend ETH on the contract) over Geth JSON-RPC API.

E.g. the number displayed here: http://testnet.etherscan.io/address/0xc5910bcb2442e84845aa98b20ca51e8f5d2bee23

What would be a good starting point?


texts: How to refund gas to the smart contract caller? (What is the number?)

texts:
I have this function:
    function setAccount(BaseUBI _ubi, address _user, uint256 _startTime, uint _esiaID, bool _setToZero) external {
        uint256 _refund = (gasleft() + 0/*FIXME*/) * tx.gasprice;
        require(msg.sender == server, "System function"); // don't refund otherwise
        require(_refund <= balances[_user], "Not enough balance");
        balances[_user] -= _refund; // must be called before transfer() against reentrancy attack
        server.transfer(_refund); // refund gas to the server
        _ubi.setAccount{gas: balances[_user]}(_user, _startTime, _esiaID, _setToZero);
        // We may be in a wrong state now, don't change any variables here.
    }

Which number should be in place of TODO to ensure that the server will receive back at least as much gas as it spent?
Is there a library that automates this task?
If necessary, rewrite the appropriate part of the above code in assembler.


texts: Setting gasPrice not working on private network

texts:
I'm running geth with the following option:

--gasprice 21000

But if I execute the following command:

> eth.gasPrice

It gives me 20000000000.


texts: What is a summary of the token standard debate?

texts:
I've been seeing some talks about replacing ERC20 with a better standard. I think I'm slightly out of the loop, though.

What is, in summary, the limitations and/or issues with ERC20?
How will the proposed standard improve and solve those limitations and/or issues?
Is it generic enough? I.e., do we know that the new standard doesn't also have limitations and/or issues that will cause it to be replaced in a future?


texts: How to access storage areas when libraries are used?

texts:
I am testing storage areas to see exactly the efficiency aspects of this and I have trouble finding the storage on the disk for the contract/library combination.

Here is the code -

pragma solidity ^0.4.16;

import "./Set.sol";

contract d3 {
    Set.Data knownValues;

    function register(uint value) public {
        // The library functions can be called without a
        // specific instance of the library, since the
        // "instance" will be the current contract.
        require(Set.insert(knownValues, value));
    }
    function contains(uint value) view public returns (bool) {
        return Set.contains(knownValues, value);
    }
    // In this contract, we can also directly access knownValues.flags, if we want.
}

pragma solidity ^0.4.16;

library Set {
  // We define a new struct datatype that will be used to
  // hold its data in the calling contract.
  struct Data { mapping(uint => bool) flags; }

  // Note that the first parameter is of type "storage
  // reference" and thus only its storage address and not
  // its contents is passed as part of the call.  This is a
  // special feature of library functions.  It is idiomatic
  // to call the first parameter `self`, if the function can
  // be seen as a method of that object.
  function insert(Data storage self, uint value)
      public
      returns (bool)
  {
      if (self.flags[value])
          return false; // already there
      self.flags[value] = true;
      return true;
  }

  function remove(Data storage self, uint value)
      public
      returns (bool)
  {
      if (!self.flags[value])
          return false; // not there
      self.flags[value] = false;
      return true;
  }

  function contains(Data storage self, uint value)
      public
      view
      returns (bool)
  {
      return self.flags[value];
  }
}

I have tried his to get the storage -

var startSlot = web3.toBigNumber(
    web3.sha3(web3.padLeft("0", 63)+pos, { encoding: 'hex' }));
var slot = "0x" + startSlot.add(n).toString(16);
var bn = web3.toBigNumber(slot);
var output =eth.getStorageAt(con.address, bn)

With:

pos=0

I am unsure exactly how the slot positions are worked out for a mapped struct. I know the sha is taken and the added to the position.

I tried this too -

key=n;
pos=web3.padLeft("0",63)+ "0";
 var slot = web3.sha3(key + pos, {encoding:"hex"});
 var bn = web3.toBigNumber(slot);
var output= eth.getStorageAt(con.address, bn)
decout=web3.toDecimal(output);

I only get zeros back for the outputs from this js.

Has anyone any idea how to locate the storage for the code given?


texts: Trying to send ETH from Mist Wallet to Poloniex, received ETC instead

texts:
I want to send both my ETC and ETH to Poloniex.

I have a basic understanding of the DAO fork and know nothing about programming. I googled something about a replay attack and using a split contract. I also read about how Poloniex or Kraken automatically splits the currency for you. All the information is about two months old and I'm afraid it might not be applicable in the present.

So I sent 1 Eth directly to Poloniex just to be sure. When I checked Etherscan it said that my transaction was processed in the Ethereum Classic Blockchain. My ETH balance on Etherscan is unchanged but 1 ETC (plus tx fee) was missing from the ETC balance and I have 1 ETC credited to Poloniex.

What do I do? Do I send out all the ETC from Mist to Polo, since it seems I am in no danger of losing the equivalent amount of ETH? Will I be able to finally send out ETH once I have emptied the account of ETC. I assume it will not be as simple as that.

Other pertinent information:

I am using (I assume the latest) version 0.8.4 of Mist that is not completely synced at the moment. I read that it's supposed to ask me if should go on the old blockchain or the new, which it hasn't yet. I assume it has something to do with it.
The ETH and ETC are orignally of equal amount
The funds are from the pre-sale wallet, which I am only accessing now.