texts: Error "The contract code couldn't be stored, please check your gas amount"

texts:
UPDATE: I manage to figure out what's wrong is in this line

var byteCode = compiledCode.contracts[':TestStorage'].***byteCode***;

and it should be

var byteCode = compiledCode.contracts[':TestStorage'].***bytecode***;

Completely typo, but it makes me realize that this error is quite general so that could be a lot of reasons.

I have see a lot of people raised this question, but none of the answer/solution could solve my problem so ask here.

I setup truffle on my Windows OS and use Ganache as my personal development blockchain. I create a Node project, use Express setup a server handling request and deploy my contract. I have this error returned:

  The contract code couldn't be stored, please check your gas amount

My code is below:

var router = express.Router();
var logger = require('./logger');
var pool = require('./pool');
var web3 = require('./getWeb3');
const fs = require('fs');
const solc = require('solc');

router.get('/',  function(req, res, next){
    var code = fs.readFileSync('TestStorage.sol').toString();
    var compiledCode = solc.compile(code);
    var abi = JSON.parse(compiledCode.contracts[':TestStorage'].interface);
    var TSContract = web3.eth.contract(abi);
    var byteCode = compiledCode.contracts[':TestStorage'].byteCode;

    console.log("Unlocking coinbase account");
    var password = "";
    try {
        web3.personal.unlockAccount(web3.eth.coinbase, password);
    } catch(e) {
        console.log(e);
        return;
    }

    var deployedContract = TSContract.new({data: '0x' + byteCode, from: web3.eth.coinbase, gas: 6721975}, (err, res) => {
        if (err) {
            console.log('error message: ' + err);
            return;
        }

        // Log the tx, you can explore status with eth.getTransaction()
        console.log(res.transactionHash);

        // If we have an address property, the contract was deployed
        if (res.address) {
            console.log('Contract address: ' + res.address);
        }
    });
}

getWeb3.js

const Web3 = require('web3');

var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:9545'));

module.exports=web3;

I have tried below
1. adjust gas in new() and if it greater than 6721975, then error - "Error: Exceeds block gas limit" returned.
2. I manually input above steps in node command line and contact can be deployed successfully.


texts: What happens if mine testnet with etherbase set as account that already controls "real" ether?

texts:
Suppose I want to mine the testnet with something like this:

geth --testnet --etherbase '<some address where I keep "real"/mainnet ether>' --mine

What will happen to the existing mainnet ether at that address? Would I be able to split up the mainnet and testnet ether from that address at that point (if so, how)? My main concern is that the different ether will be "mixed" in some way that would essentially render all of the tokens associated with that address worthless on the mainnet (eg. if testnet UTXOs have different metadata that may confuse most wallets when they need to deal with that address now controlling those UTXOs as well as mainnet UTXOs).

New to this (and the ethereum homestead documentation seems to be not up to date as evidenced by the fact that the official docs only mention the Morden testnet rather than the newer Ropsten testnet), so if anything in my verbiage implies any misunderstanding of any concepts, I would appreciate if you would help correct me (eg. what exactly is happening under the surface). Thanks

Note, I've seen this similar post, but the answers there don't seem to really answer the poster's 'what happens' question.


texts: How can a user be informed of the reason for a revert if there is no event log available?

texts: I presume a typical case of smart contract use is purchasing tokens from a smart contract using Metamask. If the contract is at all complex (such as a tiered pricing sale with various caps) and a request to purchase tokens fails - for instance due to exceeding some cap - the user only knows that it has failed, and otherwise has no clue about what caused the failure. If they call the support staff of the company that owns the contract the support staff will likely be similarly in the dark. I totally disagree with the sentiment "fail early and hard -- without any logged event". I wholly support "fail early and hard, but leave tracks." Is this simply beyond the capability of the EVM? There is a failed transaction record present after a failure. Why can't it contain a log from the operation that failed? I must be missing some key point about the way logging "works" (or doesn't)...


texts: How can a mixed debt/equity capital structure be created for a DAO?

texts:
Suppose we have a DAO that wants to issue “debt,” which we will define as (i) a claim that must be paid and if it isn’t the the debt claimants have a right to force an event called “bankruptcy”, (ii) in the event of a “a bankruptcy” this claim must be paid before “equity.” (Note that this notion of debt is distinct from what is currently contemplated by others; most other notions of debt are implicitly secured debt collateralized by a financial asset and here we are contemplating an unsecured debt claim). Here “equity” is understood to be the token that allocated the resource being created by the DAO and with which the “management team” (eg, keepers) are compensated.

The following are several “attacks” that occur in “normal life” corporate settings that have been fixed by making them illegal, but do not appear to have a tractable solution in decentralized governance. I want to discuss how these attacks can be avoided:

1) Frauds to the Estate: suppose this DAO has a “fee” that is used to pay for costs of goods sold that cannot readily be handled by one party.
An example is a large advertising budget or fees to use to pay an external vendor. Once we allow the DAO to make decisions on spending, how do we ensure that keepers do not defraud the DAO by spending on themselves and not things that benefit the DAO? Note that token ownership is never sufficient to stop this. (If I buy a $1mm jet with company and own 1% is the company that bought me the jet, then I just got a jet for 99% off pretty much.) Moreover, the law is never sufficient to stop this (if it is truly decentralized, we cannot ensure the fraudster is in any particular legal jurisdiction nor is it clear how this case would be prosecuted).

2) Value Leakage to Equity: there are multiple ways to conduct this attack. One way is that equity holders can capitalize the company with 50% debt and thereby raise a lot of funds. then they rewrite the credit agreements of the company such that they are now allowed them to pay themselves a special dividend of all the cash they raised. Then they file for bankruptcy and the equity token and debt ends up worthless, but the equity holders got the cash from their special dividend and thereby screwed creditors.

3) Existential Effects of Distress: normal corporations have value either because it will issue or currently issues dividends, because it can be liquidated for its underlying assets or because it will be bought by another company (which will realize value in one of the two previous ways). In bankruptcy, distress will force  equity holders to get none of the value and all the value goes to the more secure of creditors. It’s difficult to see how this would work with tokens, but I can imagine a couple ways to create a similar property for a DAO. Curious to hear what others have thought of.


texts: TypeError: Cannot read property 'providers' of undefined: Truffle & Web3

texts:
Here is the necessary part of the code, from where I keep receiving the following error:
const { Web3 } = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));

TypeError: Cannot read property 'providers' of undefined
Although, the node packages for Web3 are installed. How can I solve this problem?. Thanks.


texts:
I have a Map of a List.  I am managing the data in the map and the list.   I have it working for now, but wanted to find out if there is a better way to do this.

mapping (bytes32 => Receipts[]) receiptsByPersonMap;
Receipts[] dummyReceiptsList;

Receipts newReceipt = new Receipts(_person, _cost);

dummyReceiptsList = receiptsByPersonMap[_person];

dummyReceiptsList.push(newReceipt);
receiptsByPersonMap[_person] = dummyReceiptsList;

This works for now.  it seems that the last line is irrelevant - if  receiptsList is pointing to the same storage space.  Any suggestion of a better way to do this.


texts: Ethereum transaction with multi input and multi output like bitcoin

texts: What happens to my wallet when I only 1000 accounts with 0.0001 ether and the tx-fee is about the same, I can't spend anything anymore?


texts: How to handle require/revert/assert errors properly

texts:
I'm trying to find an easy pattern to revert/rollback a write transaction.

The first idea was to log a GenericErrorEvent but then I noticed that it will never be emited if any require/revert/assert makes a "rollback".

On the truffle tests I can easily capture the errors within a try-catch, but an independent client listening for events would never be able to properly capture those same errors.

Since it's important to me that third clients can capture or listen for errors I'm just prechecking as much as possible in the function preconditions tests, log an error and just return from the public/external function if something goes wrong.

This works for simple scenarios but is very "manual" and changing the order of execution could actually introduce errors. Neither it allows to rollback from some error deeper in the stack once passed the first function precoditions.

I'm wondering whether there is a "magical" trick to log an error event and rollback to initial state with no manual coding.

The same question from another point of view:

Suppose we have next architecture:

JS client1 -> geth_node1 ... (ethereum net) ... geth_node2 <- JS Client2

JS Client1 sends a new signed transaction to its local node geth_node1. At some point the transaccion is processed by some mining node and the assert/revert/require is executed. There is a new mined transaction in the blockchain that spends a few weis from JS_client1 and JS_client1 will receive an string with the assert/revert/require error. Still, since no event is emmited JS_Client2 will have a hard time to be notified of such error.

It's it possible to (somehow) monitor at least all transactions signed by client1 and check when an assert/revert/require error was thrown?


texts: Solidity - preventing negative uint parameters/overflow

texts:
Since web3 apparently doesn't require functions with uint parameters to have positive values for those parameters, I thought I'd try it in Solidity.  I'm posting this to see if I'm overthinking it, if there is any unnecessary code, or if there's still a way it could break.  For the contract I'm working on, this would be infrequently used but important so it would be worth making sure that negative or irregular amounts would never be set.

modifier validateUintFromInt(int _value) {
    require(_value > 0); // check positive value
    require(_value <= 2**128 - 1); // assumes nothing more than uint128 is needed - not sure if this is necessary with the statement below
    require(_value == int(uint(_value))); // uint and int overflow at different points so this would provide some assurance that massive numbers would not be allowed
    _;
}

This could be used like this:

function updateValue(int _newInt) external validateUintFromInt(_newInt) {
    uint _newUint = uint(_newInt);
    globalUint = _newUint;
}


texts:
I tried to bid a name on ENS but it says

  "no accounts added to dapp"

I have metamask google extension linked to myetherwallet.

Please let me know how to add an account on dapp.

Thank you!!!

Hiro


texts: how do I create an ethereum valid key pair in nodeJS?

texts:
I need to generate a key pair that can be used to write the a besu (ethereum) private ledger.   I wrote the following code but the architect says this will probably not work with ethereum.

The examples he gave me do not compile with the latest packages, seems overly complex, or make no sense to me in that they don't do anything different from my simple code.

Here's my code:

import * as keypair from 'keypair';
import * as forge from 'node-forge';
const pair = keypair();
const publicKey = forge.pki.publicKeyFromPem(pair.public);
const privateKey = forge.pki.privateKeyFromPem(pair.private);

Not making excuses, I don't know where to begin or what to even search on.   What do I need to generate to have acceptable keys for use with ethereum?


texts: Could a proxy spigot contract have stopped the DAO fraud?

texts:
For anyone who doesn't know about the DAO exploit you can read up on it here.

It seems to me like the attack could have been stopped if payouts went through another contract that was really simple but acted like a spigot.  They would have still lost money but the spigot contract would have stopped the unstoppable flow of money out that ended up requiring a hard fork.

I feel like most contracts should be using some sort of spigot contract to mitigate bugs.

Am I right in this? Or are there other things I'm not considering?


texts: Require specific token to execute a smart contract

texts: Is it possible to only allow parties that agreed to a smart contract on the Ethereum blockchain to use a specific token for it's executing (e.g. not using Ether but token xxx)?


texts: What are the best practices for handling private keys on behalf of dApp users?

texts: I have seen many answers and theory about it but didn't find any concrete example of how it should be done.


texts: What is the function of Ether in operating an application on the Ethereum blockchain?

texts:
What is the relationship between the price of Ether and the usage of the Ethereuem blockchain?

Or is a Ether coin simply a means of holding a piece of the value of the Ethereum blockchain (like a shareholder in a publically listed company)? (I know that gas is used to operate Ethereuem blockchain applications...so then I am wondering what the point of the Ether token coin is in terms of running the applications on the Ethereum blockchain).


texts: Why are my contracts created from a Factory appearing in etherscan as normal accounts and not contract accounts?

texts:
I have a factory on rinkby testnet that creates other contracts.

These other contracts are shown as normal human accounts, and not contract accounts.

It appears that the code for the factory and the contracts it makes is all stored at the factory address. Is this why it appears this way on etherscan?

Ultimately, what I want to know is are these factory created contracts really contract accounts? or are they normal accounts?


texts: Pending/mined transaction dapp UI feedback using Metamask?

texts:
So I have deployed a smart contract and can interact with it via a web UI using web3.eth.contract(abi).at(address) and Metamask - so far so good.

However, between a transaction being submitted and it being mined I would like to display one message and once it has been mined another one.

I understand that web3.eth.getTransactionReceipt(txhash).blockNumber == "" until the tx has been mined. But how do I check this until it has in fact been mined using javascript and the injected web3 from Metamask?

EDIT: I am trying to make it work with promises but just can't wrap my head around how to implement it. This is my code that should handle a transaction receipt via a promise:

function approveFactoryContract(factory) {
  factoryAdress = $("#factory").val();
  RegistratContractInstance.approveFactoryContract(factoryAdress, false, {from: web3.eth.accounts[0]}, function(error, result){
           if(!error)
               console.log(result),
               $("#message").html("Approval request has been submitted - please wait a moment for it to be mined. You can check your transaction here");
           else
               console.error(error);
       });
}

How do I make this work?

Display text while pending: Please wait for your transaction to be mined.
Display text when resolved: Your transaction has been mined.


texts:
I'm still pretty fresh to all this code life, please help me out.
I am writing this price scanner to get the prices of pairs in Uniswap. Even though console.log(tradePrices) shows me an object with token names as keys and their /ETH pair prices as values, when I try to get the price of a token individually by its key, I get an 'undefined' error.
const tradePrices = {};
        for (let [tokenName, tokenValue] of Object.entries({dai, sushi, usdc, usdt, yfi, cover, wbtc, snx, link, comp, susd, crv, band, ampl, uni})) {
            const pair = await Fetcher.fetchPairData(tokenValue, weth);
            const route = new Route([pair], weth);
            trade = new Trade(route, new TokenAmount(weth, '100000000000000000'), TradeType.EXACT_INPUT);

tradePrices[`${tokenName.toUpperCase()}/ETH`] = trade.executionPrice.invert().toSignificant(6);
        }
         console.log(tradePrices.dai); // undefined

I would appreciate so much your input!


texts: What is difference between left and right in Gas Estimates of Remix

texts:
Gas Estimates:
Creation: 26137 + 1082400

what is difference between left one and right one?

I wonder this.
Please enlighten me.
I guess right one is about contract and left one is others like temporary memory;


texts: How to show the time when the blockchain contract called?

texts:
I want to show the time when blockchain contract called.

I am currently saving the time in the blockchain using a method like this

function userCheckIn(uint placeid) public {
    userCount++;
    checkins[userCount] = Checkin(placeid, msg.sender, new Date(now * 1000));
}

However, Date says Identifier not found or not unique.

Could you give me any advise, please?


texts:
Is that why ethereum is considered to have a lot of potential?

In other words, what does ethereum offer that other blockchain technologies can't replicate.


texts:
In this trivial example, both require and throw perform the same guard.  And according to remix using the 0.4.10 compiler, both functions, when presented with a value <= 10 throw : VM Exception: invalid opcode.

Other than maybe the readability of the code (require seems to be more intuitive), what's the benefit of using one over the other?

pragma solidity ^0.4.10;

contract Simple {
  uint public value1;
  uint public value2;

  function setOne(uint v) {
    require(v > 10);

    value1 = v;
  }

  function setTwo(uint v) {
      if(v <=  10 ) throw;

      value2 = v;
  }
}


texts: How can I instantiate a contract from a factory and, in the same call, send msg.value to it?

texts:
WHAT I WANT TO DO:  call another contract's constructor function, instantiate that contract, and subsequently send Ether to it in the same function.
WHAT HAPPENS: an instance of the other contract gets created, and Ether is transferred, but none of the functions on the newly created contract work. I get call to SmartGift.{function name} errored: Cannot read property 'length' of undefined when I try to do anything on the new contract.
PROBLEM FUNCTION:

function createSmartGift(address _recipient, uint32 _expiry, string _donorMsg) public payable returns(address){
        address newGift;
        newGift = new SmartGift(_recipient, msg.sender, _expiry, _donorMsg);
        giftExists[newGift] = true;

        uint id = gifts.push(Gift(newGift, _donorMsg,false, _expiry));
        giftToOwner[id-1] = _recipient;
        recipientGiftCount[_recipient]++;
        donorGiftCount[msg.sender]++;

        newGift.transfer(address(this).balance); // I WANT TO THIS, BUT GET ERROR

        return newGift;
    }

OTHER NOTES: I've tried both address(this).balance and msg.value. And the target contract has a payable fallback function.
Also, everything works fine if I separate out the newGift.transfer() into a separate function that I have to call separately. That's my backup plan, but I want the customer to only click once, not twice!


texts: Getting number of value transaction of a contract in the last 24 hours

texts:
I'm would like to get the number of value transactions (either tokens deposit or withdrawal) for a specific contract (I got its address) in the last 24 hours and also the total so far.

Is it possible? Say using etherscan.io or something similar?


texts: Weird exchange rate when buying DAI with Ether

texts:
I wrote code to buy DAI using ETH on Uniswap V2 as follows:
function buyCryptoOnUniswap(uint256 etherCost , address cryptoToken) public payable returns(uint256){
//address cryptoToken = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;

require(etherCost <= address(this).balance , "Insufficient funds")

    uint256 cryptoAmountPurchasable = estimateTokensThatETHCanBuy(etherCost , cryptoToken)[1];
    cryptoAmountPurchasable = cryptoAmountPurchasable.mul(11).div(10);// multiply by 1.1

    uint deadline = now + 300; // using 'now' for convenience, for mainnet pass deadline from frontend!

    usi.swapExactETHForTokens.value(etherCost)(0, getPathForETHToToken(cryptoToken), address(this), deadline);

   return cryptoAmountPurchasable;

}

 function estimateTokensThatETHCanBuy(uint ethAmount , address crypto) public view returns (uint[] memory) {
       return usi.getAmountsOut(ethAmount, getPathForETHToToken(crypto));
  }

  function getPathForETHToToken(address crypto) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = usi.WETH();
    path[1] = crypto;

    return path;
  }

The code works but I was expecting an exchange rate of about 180 -> 230 but to my dismay, 0.1 ETH only gave me 1.926 DAI and 1 ETH gave me about 19.26 DAI also.
Here is the transaction using 0.1ETH.
I am using the DAI token for kovan: 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa.
Is something wrong with my code?
Please help.
UPDATE
I wrote code to buy DAI on Kyber and I got it at the expected rate range:
See the transaction here.


texts: Why block explorer shows that I have ether but ethereum wallet show 0 balance

texts:
In testnet etherscan I can see 18.5 ether in my account:

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

But in the Ethereum Wallet, I cannot see any money, even when it wrote that blocks are up to date. I started Geth by typing geth --testnet

I looked at the latest block in testnet and it is 467662. However, in the Geth output, it displays something like number=1228242


texts:
As written in Truffle docs:

  Migrations are Javascript files that help you deploy contracts to the
  Ethereum network. These files are responsible for staging your
  deployment tasks, and they're written under the assumption that your
  deployment needs will change over time. As your project evolves,
  you'll create new migration scripts to further this evolution on the
  blockchain. A history of previously run migrations is recorded
  on-chain through a special Migrations contract, detailed below.

But what does it really mean? What are the use cases of migrations?

I'm also trying to understand the Migrations.sol file, which is given in Truffle tutorial:

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _
  }

  function Migrations() {
    owner = msg.sender;
  }

  function setCompleted(uint completed) restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}


texts: Will there be mining pools with the Proof-of-Stake?

texts: Ethereum will eventually move to Proof-of-Stake algorithm. I guess it is a very basic question, but how the mining pools are supposed to work in that case (if at all)?


texts: assertEventEmitted from new contract construction call

texts:
At present there is no way I can see or is documented to be able to easily use something like this with the truffle framework:

So using chai and writing a test to deploy a contract with something like this.

c = await MyContract.new();
// this wont work...
truffleAssert.eventEmitted(c, "ContractCreated", (ev) => {
    return ev.param === myInputParam;
});

My contract constructor will emit a ContractCreated event. I want to assert that this happened and the values are as expected. The event itself and its content is irrelevant. Its more the process of asserting events were emitted and contract construction time is important.

I would expect or want that I can do this assertion and use the assertEventEmitted function above.

Currently the only way I can see to accomplish this is so:

    let event = c.allEvents({fromBlock: 0, toBlock: 'latest'});
    event.watch(function (error, result) {
        if (!error){
            console.log("Result: ", result);
            // or some assertions similar to assertEventEmitted(...)
        }
    });

I can't find an elegant way to read the event logs emitted during contract construction using the truffle toolset.

When you send a transaction in you get the result object you can assert, upon contract creation the object returned is different and as such the logs are not available to check for event emission.

Does anyone know of a way to get those event logs from a truffle contract creation call and use the truffle-assertions.assertEventEmitted function to test with?

Thanks in Advance.


texts: How to pass parameters to Contract constructor using when using assembly?

texts:
Here I have a function which deploys a Contract straight from bytecode, but let say my contract needs some arguments in the constructor, is it possible to pass them through create opcode?

function deployCode(bytes _code) returns (address deployedAddress) {
    assembly {
        deployedAddress := create(0, add(_code, 0x20), mload(_code))
        jumpi(invalidJumpLabel, iszero(extcodesize(deployedAddress)))
    }
    return deployedAddress
}


texts: How to initialize an empty array inside a struct?

texts:
Is there a mistake in the way I initialize Bar b in the function foobar?

contract Foo {

    struct Bar {
        address owner;
        uint[] x;
    }

    Bar[] public bars;

    function foobar(address a) public {
        Bar storage b = Bar(a, new uint[]) // will that be an array in storage?
        bars.push(b)
    }

}


texts: How to set a fee for any transfer of my token

texts:
I'm planning to create my own token (Binance Smart Chaine C.) my first attempt was succesfull. But I'm trying to figure out how to avoid price dumping by whales. A Solution would be if i could adjust the selling fee like safemoon does (10%) but i haven't found the line in the code to set the fee.
I know that this question is very general, but maybe someone could help me a bit fourther.
Thanks


texts: What is a blockchain? What is the concept behind it?

texts:
I have been going through some docs, and I understand that BlockChains are mostly like the building blocks in an Ethereum network.

So, can someone give a dumbed down explanation/definition about what it is, for a starter?


texts: Gnosis Safe - Connect to site that needs to connect using MetaMask and not WalletConnect

texts:
I have a multi-sig wallet created and in use.  It requires 2 of 4 signatures and all seems to be working just fine with it.
I now need to interact with a website (https://vault.daomaker.com/#/) to connect the wallet with it, but the site only has MetaMask as an option and not WalletConnect.
Is there a way to make the two connect? Possibly using an app on the multi-sig contract, or some way to add it into a MetaMask account list?


texts: Solidity Browser and Truffle giving different bytecodes


texts: Contract to Contract Transaction with Ether

texts:
I have some trouble creating two interacting contracts.
The first contract should receive ether from a user at a function payRate() and forward the amount to another contract, which is saved at the address pool. Both functions (the payRate() and the receivePayment() function) are payable and receivePayment() is working if called from a user. Mining the contracts works fine but using the functions fails. I also tried a different versions with small fixed amounts of ether, same result.

The environment I used is Visual Studio Code with the Solidity extension as compiler and Parity (dev. chain).

    pragma solidity ^0.4.18;

    contract sendEther {

    address owner;
    address pool;
    uint amountPaid;

    function sendEther(address _pool) public {
    pool = _pool;
    owner = msg.sender;
    }

    function payRate() payable {
       require(pool != address(0));

       pool.transfer(msg.value);
       amountPaid += msg.value;

       //other ways of sending i tried:
       //TransactionPool test = TransactionPool(pool);
       //test.receivePayment().value(msg.value);

       //pool.call.value(msg.value)(bytes4(keccak256("receivePayment()")));
    }
    }

and

    pragma solidity ^0.4.18;

    contract TransactionPool {

    address owner;
    uint totalPayments;

    function TransactionPool() public {
       owner = msg.sender;
    }

    function receivePayment() public payable {
       totalPayments += msg.value;
    }

    function() payable public { //fallback function
       totalPayments += msg.value;
    }
    }

Thanks!


texts:
I have this code to send a multi-transaction of token in a short airdrop

pragma solidity ^0.4.18;
contract ERC20 {
function transfer(address _recipient, uint256 _value) public returns (bool
       success);
}

contract Airdrop {
function drop(ERC20 token, address[] recipients, uint256[] values) public {
  for (uint256 i = 0; i < recipients.length; i++) {
    token.transfer(recipients[i], values[i]);
  }
 }
}

I've deployed the contract but while it was successful, no token was received by the recipient. Do you see any errors here?


texts: Number of state entries needed before geth node is synced up with Ropsten

texts:
I am currently syncing a Geth node with the Ropsten network. Currently the download in the terminal show a neverending stream of Imported new state entries. I understand that I have to wait for all of them to sync before I can use the node in development purposes.

This leads to the question: What's the current number of state entries existing on Ropsten?


texts:
How do I import a keystore file generated in geth into Metamask?

Is there a simple way for me to convert the ciphertext into a private key, can I decrypt it with my passphrase somehow?


texts: Since the price of ETH has gone up 10x in 6 months, should I be lowering the gas price for my transactions?

texts:
The price of ETH has gone from ~8 USD/ETH to ~90 ETH/USD in 6 months, but when I view transactions on the blockchain (example), I see that most people are still using the default gas price of 2e10 wei/gas.

Shouldn't we be lowering the gas prices on our transactions to account for this price change?

I have built a Dapp where low transaction fees are an important  selling point. I intend to drop my gas price to 5e9 (a 75% reduction). Will my transactions still clear in a timely fashion?

UPDATE: I have been running transactions (as of May 5 2017) with a gas limit of 2e9 gas and they have been clearing in ~7 min.


texts: How to call a contract function using Nethereum?

texts:
I would like to call a contract function using Nethereum C#.

Here is the contract in Etherscan (https://etherscan.io/token/0x8c9b261faef3b3c2e64ab5e58e04615f8c788099#readContract)

I want to call the function 24 "getCollectibleDetails".

Here is the code that I did so far, but it isn't working.

var web3 = new Web3("https://mainnet.infura.io");
var contract = web3.Eth.GetContract(abi, contractAddress);
var function = contract.GetFunction("getCollectibleDetails");
var parameters = new object[]
{
    new
    {
        Data = 157517,
        To = "0x8c9b261faef3b3c2e64ab5e58e04615f8c788099"
    }
};

var result = function.GetData(parameters);

Anyone has faced this?

Thanks in advance for any help.


texts:
I installed open ethereum pool for mining Musicon, now pool found 3 blocks, but cant sent payments.
Getting error: Unable to process payouts: Invalid address length, expected 40 got 1 bytes


texts: Receive a token from a smart contract by sending it a 'code word'

texts:
What would be a way to assign a code word inside a contract (such as a promotional / coupon style code word) so that you could let people know "send this message/code word to this contract address and it will issue out a token".

The use case is during certain times of the week (say between 1pm and 2pm on Wednesday) I'd like to issue a code word, which friends would then send this code word to the contract, and it will issue out a token for them.

Double points for help with creating a timing regulation within the contract that's editable at a later date (eg I can set this week's code word to be valid between X and Y time on Wednesday).

Thank you.


texts: Performing a C-like pointer increment in Solidity

texts:
I have a memory or calldata struct with an attribute of type byte[]. I want to have a memory variable with that data, except for the first n Bytes.

In C, you'd just write

typename variablename = structname.fieldname + n;

and be done. How can this be done in Solidity?

More specifically, I have a struct describing the Ethereum header:

  struct Header {
    bytes32 parentHash;
    bytes32 uncleHash;
    address coinbase;
    bytes32 root;
    bytes32 txHash;
    bytes32 receiptHash;
    byte[] bloom;
    int128 difficulty;
    int128 number;
    uint64 gasLimit;
    uint64 gasUsed;
    uint64 time;
    byte[] extra;
    bytes32 mixDigest;
    uint64 nonce;
  }

I want to verify the signatures of blocks of a proof of authority (clique consensus) chain. This signature is part of the extra field. However, there's also some other data in there which is why I need to be able to skip a variable number of bytes (the length of the extra field minus 65) and store it in a variable before using this code to extract the signature's elements:

function splitSignature(bytes memory sig)
    internal
    pure
    returns (uint8 v, bytes32 r, bytes32 s)
{
    require(sig.length == 65);

    assembly {
        // first 32 bytes, after the length prefix.
        r := mload(add(sig, 32))
        // second 32 bytes.
        s := mload(add(sig, 64))
        // final byte (first byte of the next 32 bytes).
        v := byte(0, mload(add(sig, 96)))
    }

    return (v, r, s);
}

(https://solidity.readthedocs.io/en/v0.5.12/solidity-by-example.html)

So I need to derive the last 65 Byte of the extra field to derive v, r, and s.


texts: Truffle interaction with my smart contract getting Vm exception

texts:
pragma solidity ^0.4.23;

contract Hotelbooking {

  event Transfer(
        address indexed _from,
        address indexed _to,
        uint256 _value
    );

 mapping(address => uint256) public balanceOf;

  //mapping (uint256 => data) accounts ;

  function transfer(address _to, uint256 _value) public returns (bool success) {
          require(balanceOf[msg.sender] >= _value);

          balanceOf[msg.sender] -= _value;

          balanceOf[_to] += _value;

          Transfer(msg.sender, _to, _value);
            return true;

      }
    }

My trascation code i want intract with mty truffle

  Hotelbooking.deployed().then(function(i){app = i;})

  app.transfer(web3.eth.accounts[1],10,{from : web3.eth.accounts[0] })

i am getting the following error

  Error: VM Exception while processing transaction: revert
      at XMLHttpRequest._onHttpResponseEnd (/usr/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
      at XMLHttpRequest._setReadyState (/usr/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
      at XMLHttpRequestEventTarget.dispatchEvent (/usr/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
      at XMLHttpRequest.request.onreadystatechange (/usr/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
      at /usr/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
      at /usr/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
      at Object.InvalidResponse (/usr/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)

plese help me


texts: Is Ownable.sol transferOwnership() an expensive function to run, or am I running it wrong?

texts:
I have a simple ERC20 token, and I would like to transfer the ownership of this contract onto a new address using the Ownable.sol transferOwnership() function
When I run this contract, it seems that this function call is going to cost me approximately 1.5 ETH (!!!) if I use a competitive Gas Price (215 GWEI). That seems very expensive considering its my understanding that all that is happening is one variable is being updated on the blockchain.
Am I running something wrong? Here is the etherscan information, I have tried to run it with a very low gas fee but it still seems to cost 0.15ETH (it will probably never be added to a block at this price)
https://etherscan.io/tx/0xb9c184899d8d19e53464509aabd3383508a2320ea67613d3f327a393d8961999
Here is my code:
const Web3 = require('web3');
const TestToken= artifacts.require('TestToken.sol');
const web3 = new Web3('https://ropsten.infura.io/v3/<MYKEY>');

module.exports = async function (deployer, network, accounts) {
  const ADMIN_ADDRESS = "...";
  const NEW_ADMIN = "...";

  const TEST_TOKEN= await TestToken.at("...");
  console.log('TEST governance token address: ' + TEST_TOKEN.address);

  const TEST_OWNER = await TEST_TOKEN.owner();

  console.log('The owner of the TEST governance token is: ' + TEST_OWNER);
  console.log('Transferring Ownership Now');

  let result = await TEST_TOKEN.transferOwnership(NEW_ADMIN);
  const NEW_TEST_OWNER = await TEST_TOKEN.owner();

  console.log('The new owner of the TEST governance token is: ' + NEW_TEST_OWNER);


texts: What is the execution order of Inherited constructors in solidity?

texts:
I'm reading the section on inherited constructors on the documentation here.

The example given confuses me than understanding the concept, and it doesn't explain the most important part, the execution order.

To summarize the documentation, it says in the following example:

pragma solidity ^0.4.0;

contract Base {
  uint x;
  function Base(uint _x) { x = _x; }
}

contract Derived1 is Base(7) {
  function Derived1(uint _y) {
  }
}

contract Derived2 is Base{
  function Derived2(uint _y) Base(_y * _y) {
  }
}

Derived1 inherits Base(7) constructor, and Derived2 uses a modifier-like syntax of Base(_y * _y).

But what it DOESN'T explain is how they are actually executed. Let's take an example

contract Base {
  public uint x;
  function Base(uint _x) { x = _x; }
}

contract Derived1 is Base(7) {
  function Derived1(uint _y) {
    x = _y;
  }
}

contract Derived2 is Base {
  function Derived2(uint _y) Base(_y * _y) {
    x = _y;
  }
}

does the x = _y in each inheritance get executed BEFORE the base constructor? or after?

Normally in any object oriented oriented programming you use notations like super() to explicitly state how the parent constructor will be executed.

In case of objective-c

- (void) init {
  [super init];
  // do something
}

and

- (void) init {
  // do something
  [super init];
}

make a huge difference since the execution order is different. And the //do something part may even utilize the result from [super init].

So how does this thing work in Solidity? If you can, please share the source for the explanation as well. I can't find this on the documentation so I don't know where else I can find this.


texts: Custom token sent to wallet , does not show in wallet

texts: I am using the rinkeby test network and i created a custom token using the basic code stub given on the ethereum.org site. So I transferred to another account which is also on the rinkeby network. But the balance is not reflected. Can anybody help ?


texts:
how to put struct "s1" values in another variable.

pragma solidity ^0.5.1;

contract MyContract{
    struct student{
        int RollNo;
        string Name;
    }

    student public s1=student({RollNo:1, Name:"Test Bunny"});

    int public disint; string public disname;
    disint=s1.RollNo;
    disname=s1.Name;
}


texts: My geth node is taking ages to sync, can I still send ether?

texts:
It looks like I have to sync my blockchain at least until the block when my account was funded. Because as of right now the balance for my address is still zero.

I'm runnig geth version 1.4.4-stable-8ea3c88e.


texts:
We knows the private key right?

If we hold the private key we should be able to send ETH from the public  address and then the money got sent to our account.

I  want to buy video coin. The minimum purchase is 10 ETH

I don't want to fail.

I just want to make sure everything is up up

Anyone did it?

The issue for those who want to refresh their memory: The way ICO works is you send money from an ethereum address and you got money to the same address. I believe this works only on EC20 coins. I don't know if videocash is an EC20 coin or not.

You cannot use your exchange wallet, in general, to ICO. That's because your exchange wallet is custodian wallet.

However, if you control the private key of the public key you should be fine.

And I am under the impression that etherdelta is fine. I do not need myetherwallet. I just need etherdelta.


texts: Implementing Fractional Reserve Bandwidth Concept in EVM on Serenity

texts:
I recently came across this piece by Bytemaster of Bitshares: "How to build a Decentralized Application without Fees".

It's actually a very interesting piece that details how one might run a blockchain system without fees yet still retain something of a market equilibrium while also avoiding the problem of Sybil attacks that blockchains essentially solve. Would it be at all possible to implement something like this in Serenity? How do you think one might go about it? Let me know.


texts: connecting geth to web3.go 1.0 via websockets or HTTP

texts: Is there anyThing similar to web3.js written in go that allows me to communicate with the geth client ?


texts: Does the central pool server run the EVM code and just send out block headers, or does every miner run every contract?


texts: How do I deploy a contract when my blockchain isn't syncing?

texts:
I would like to deploy a smart contract using truffle but I got problems while syncing the etherum blockchain. There are always blocks left and the syncing process is never finished. I don't want to talk about the syncing problem since there are a lot of open issues on github and questions on this platform and it seems the problem can't be fixed.

My questions what other possibilities do I have to deploy a smart contract? I saw there are some online tools but I'm not sure if I want to past my private key to any of these sites.


texts: In bitcoin, when a transaction is under-priced and stuck unconfirmed on the blockchain, it is possible to bump it by setting up a CPFP transaction. Is there a similar way to achieve this in Ethereum? Say, transaction #1 has gas price set to 5Gwei and nobody is picking it up. Can I set up a transaction #2 whose code is something like "execute transaction #1 first" and price it at 10Gwei? How could this be achieved?


texts: How to download or access ('web3/lib/web3/event.js');

texts:
The following test script requires('web3/lib/web3/event.js');

const SolidityEvent = require('web3/lib/web3/event.js');

function decodeLogs (logs, contract, address) {
 return logs.map(log => {
const event = new SolidityEvent(null, contract.events[log.topics[0]],   address);
return event.decode(log);
});
}

module.exports = {
 decodeLogs,
};

Does anyone know where I can find the library or is the library installed with the web3 download ???

Thanks in advance !!


texts: Switched from the Ethereum Wallet's test network to main network and need to remove the previous data

texts:
I was on the Ethereum Wallet's test network and finally worked out all the code, but now that I have switched over to the main network I've had to download a lot of the preexisting blocks and has my Mac's storage nearly full. Is there a way I can clear out the previous data from the test network to free up space? Also, I thought about uninstalling and then installing it again, but I've already sent some ether to the "my account" in the wallet, would I lose that account or can I have it recovered?
Thanks for any and all help!


texts: How is address comparison done in Vyper?

texts:
In solidity, you can do this:
address_1 < address_2

But the same code is not possible in vyper. How can I compare which address is larger than the other in vyper?


texts: Error sending ether to a a smart contract deployed in ropsten with web3 with python

texts:
I am trying to send ether to a smart contract deployed on ropsten via infura, but I am having some problems in txn.
The error is "Error in Txn: Reverted".

The sender account has enought ether to afford the transaction so I dont understand what is failing.
def default_reward():

    amount_in_ether=2
    amount_in_wei = wb3.toWei(amount_in_ether,'ether')

    acct = wb3.eth.account.privateKeyToAccount(config.ADMIN_KEY)

    txn_dict = {
            'to': config.audacoin_contract_address,
            'value': amount_in_wei,
            'gas': 4465030,
            'gasPrice': wb3.toWei('21', 'gwei'),
            'from': acct.address,
            'nonce': wb3.eth.getTransactionCount(acct.address),

    }

    signed_txn = acct.signTransaction(txn_dict)

    txn_hash = wb3.eth.sendRawTransaction(signed_txn.rawTransaction)

    txReceipt = wb3.eth.waitForTransactionReceipt(txn_hash)

    return "Sended"

This is the method I use and it executes normally, I mean, without any errors.
I supouse that I commit an error declaring txn_dict but I dont know which.
Thanks very much for your help!
PS: I connect to ropsten via Infura.


texts:
With solidity 5.0+ , the delegatecall function can return a boolean and a bytes representing return value.  I want to understand how does one convert the returned bytes to various datatypes. ex

If the call is:

bool s, bytes b = delegatecall(....)

How can bytes b be converted to native types like (assuming i as the caller know the return value type):

bytes32
uint256
user defined struct

Thanks!


texts: How do i make an ERC-Token Private or have a Ring signature like monero?

texts:
I'm currently building an erc token on the Ethereum blockchain. My goal is to make a token that has some sort of functionality that makes it private like Monero's Ring Signature.

Is there any way to make the token transactions private or incredibly difficult to track? If so do you guys have any examples of this?

Thanks!


texts:
I have geth running on an AWS EC2 instance. Here is how I started it:

geth --rpc --rpcaddr "127.0.0.1" --rpcport "8545"  --rpc --rpccorsdomain "*"

from that same instance I can use python's request.post to issue a RPC request to http://localhost:8545. It works perfectly.

Now I'm trying to do the same request from my local computer by requesting to http://xx.xxx.xxx.xx:8545 but Im getting the error bellow:

HTTPConnectionPool(host='xx.xxx.xxx.xx', port=8545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000028F39163438>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))

I have added rules on AWS security group to allow all inboud from all IPs.
what could I be missing?

Thanks


texts: Solidity IDEs with background compilation for OSX

texts:
Are there yet any Solidity IDEs or editors that

Run OSX
Allow editing a folder of local Solidity source code files with includes or library support
Highlight compiler error as you type them

Please correct me if I am wrong: the browser based IDE works for a simple contract, but breaks down when you need to include multiple contracts that you keep in a version control.


texts: contract instance has a null transactionHash

texts:
I have migrated the contract via truffle, code like this, very simple
and it returns the contract account address

[root@localhost c2]# truffle migrate
Compiling ./contracts/Ballot.sol...
Writing artifacts to ./build/contracts
Running migration: 1_initial_migration.js
  Replacing Ballot...
  Ballot: 0x2eb2128b3150bd4b95e96540b7e2d2151bcfb2cc
Saving successful migration to network...
Saving artifacts...

then I created the contract instance like this

myBallot = eth.contract(abi).at(addr)

abi and addr are vars, and they are certainly right, then

myBallot
{
  abi: [{
      constant: false,
      inputs: [{...}],
      name: "vote",
      outputs: [],
      payable: false,
      type: "function"
    }
    …………
  ],
  address: "0x071d808a15df658c0b39b71d127f4df05bb66abb",
  transactionHash: null,
  allEvents: function(),
  chairperson: function(),
  giveRightToVote: function(),
  proposals: function(),
  vote: function(),
  voteCast: function(),
  voters: function(),
  winnerName: function(),
  winningProposalIndex: function()
}

the transactionHash is null

and then I call the function myBallot.giveRightToVote(eth.accounts[0]);  and continue minned, the voters is still empty

 myBallot.voters()
[false, 0, 0]


texts: How do I add my Dapp to https://www.stateofthedapps.com/?

texts: If I create a Dapp or start development on an Ethereum Dapp, what's the easiest way to get my Dapp listed on https://www.stateofthedapps.com/?


texts: Can I found order ID of Shapeshift transaction that has been made on Parity?

texts: I want to solve some problem with transaction on Parity that is related to Shapeshift. Is it possible to found shapeshift's order ID from a few hours ago. Is it maybe stored in the Parity's local files?


texts: Web3 CDN error: regeneratorRuntime is not defined

texts:
When I include the web3 js CDN to my html file, I receive this error

web3.min.js:1 Uncaught ReferenceError: regeneratorRuntime is not defined
    at Object.<anonymous> (web3.min.js:1)

Here is the CDN I am using

https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js

How do I use this CDN correctly?


texts: How to change contract interactions to kovan?

texts:
I am using newest web3 v1.2.4
const Contract = require('web3-eth-contract');
Contract.setProvider(INFURA_KOVAN_HTTPS);
const contract = new Contract(CONTRACT_ABI, CONTRACT_ADDR);

I have that code and it is requesting mainnet network, so I can't interact with my contract.


texts: Whether scatter can be used to replace web3?

texts: Whether I can use scatter instead of web3 metamask? In this way I do not need to add the metamask add on on my browser? And I can run the dapp on mobile for scatter because metamask does not support mobile?


texts: How to maintain a whitelist of addresses and assign a badge/title to the first 20 users?

texts:
I would need to keep a list of addresses (whitelist) and assign a badge/title for to the first 20 users, then another badge/title to the next 100, etc.

e.g.

First 20 users/addresses = Early Adopter
Next 100 users/addresses = Explorer
Future: next n users/addresses different badge/title

Any help, please?
Thanks.


texts: Ethereum Contract access on Private Node

texts:
I have set up a private network with one node on Linux virtual machine and one is my local windows pc.
I have done the peer adding. and I could see peer is added when I do a admin.peers on both the node.
lets call two machines as machine A and machine B.
I have created a contract which will store a number on machine A,
here is the contract code (copied from internet) and deployment steps:

1) storeSrc

contract SimpleStorage {
    uint storedData;
    function set(uint x) {
        storedData = x;
    }
    function get() constant returns (uint retVal) {
        return storedData;
    }
}

2) storeCompiled

web3.eth.compile.solidity(storeSrc)

3) storeContract

web3.eth.contract(storeCompiled.SimpleStorage.info.abiDefinition);

4) store

storeContract.new({
    from:web3.eth.accounts[0],
    data: storeCompiled.SimpleStorage.code,
    gas: 300000},
    function(e, contract){
        if(!e) {
            if(!contract.address) {
                console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");
            } else {
                console.log("Contract mined! Address: " + contract.address);
                console.log(contract);
            }
        }
    }
})

With following steps I could easily deploy the contract on machine A and was able to execute its as well.

Now since I have machine B as an added peer ideally I should be able to access this contract with its address. But in order to access the contract function I have to do following steps:

1) storeSrc

contract SimpleStorage {
    uint storedData;
    function set(uint x) { storedData = x; }
    function get() constant returns (uint retVal) { return storedData; }
}

2) storeCompiled

web3.eth.compile.solidity(storeSrc)

3)storeContract

web3.eth.contract(storeCompiled.SimpleStorage.info.abiDefinition);

4)store

storeContract.at("contract address")

So here are my questions:

Can I deploy this on a machine A without doing steps 1, 2, and 3?

Is there any way to avoid steps 1, 2, and 3 and directly access the contract using its address?


texts: Can a contract fetch the global block gas limit?

texts:
The OPCODE GASLIMIT gets the block's gas limit. Could in-line assembly,

    uint gasLimit;

    assembly {
        gasLimit := gaslimit
    }

fetch the gas limit ?

contract B {

function getGasLimit() returns (uint) {
    uint gasLimit;

    assembly {
        gasLimit := gaslimit
    }
    return gasLimit;

}

}

Using https://ethereum.github.io/browser-solidity/, with a gaslimit set to 3000000, getGasLimit() returns 6000000.

Why does it return twice the gas limit ?


texts:
Using Solidity, how can I transfer ERC20 tokens from the current address to another?

Is it done using call or send?  Are the balances kept in the token contract or in the address that the tokens belong to?


texts: How is it possible to retrieve ERC-20 tokens sent to a testnet?

texts: I'm wondering if it possible to retrieve ERC-20 tokens sent to a testnet wallet. In my case, the testnet private key actually opens an other Ethereum wallet completely different from what the testnet says. Thus the tokens sent are actually in a mainnet wallet whos private key is unknown.


texts: Error encountered during contract execution [Reverted] Problem with Contract

texts:
I've sent the transaction - https://ropsten.etherscan.io/tx/0xbecb36319d806edc3617abcbeb1f95e7215cb205dc180088f225c1addd82086f to the contract address and it got reverted.

Could someone explain me why?

Contract code:

pragma solidity ^0.6.8;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/math/SafeMath.sol";

contract Waterfall {
    using SafeMath for uint;

struct User {
    address payable addr;
    uint amount;
}

address payable public owner;
User[] public users;
uint public totalUsers = 0;
uint public feePercentage = 10;
uint public payoutPercentage = 10;

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

function join() external payable {
    require(msg.value >= 1 ether, "Investment must be at least 1 ether");
    users.push(User(msg.sender, msg.value));
    totalUsers += 1;

    uint fee = msg.value.mul(feePercentage).div(100);
    owner.transfer(fee);

    uint position = 0;
    while(position < totalUsers) {
        uint payout = users[position].amount.mul(payoutPercentage).div(100);
        if(payout > address(this).balance){
            break;
        }
        users[position].addr.transfer(payout);
        position += 1;
    }
}

}


texts: Extremely high gas Limit for ethereum function execution

texts:
I am trying to call a function from my smart contract.
The function i am trying to call is convertRTKIntoRTKLX
(Full code :- swapContract)
Although, the necessary code for this question is only this much:-
function convertRTKIntoRTKLX(address to, uint256 amount, uint256 X) public returns (bool) {
    require (
        (X >= 2 && X <= 5),
        "Invalid value of X. X can only be 2, 3, 4, 5"
    );

    require (
        amount > 0,
        "Cannot convert 0"
    );

    ERC20 AMMOToken = ERC20(_Token_AMMO);
    ERC20 RTKToken = ERC20(_Token_RTKL[0]);
    ERC20 RTKLXToken = ERC20(_Token_RTKL[X-1]);

    require (
        RTKLXToken.balanceOf(address(this)) >= amount,
        "Insufficeint RTKLX Token balance in the contract for the given value of X"
    );

    require (
        RTKToken.allowance(msg.sender, address(this)) >= amount,
        "Allowance Lower than required for RTKToken"
    );

    require (
        AMMOToken.allowance(msg.sender, address(this)) >= ((X-1)*amount),
        "Allowance Lower than required for bulletToken"
    );

    if(AMMOToken.transferFrom(msg.sender, address(this), ((X-1)*amount))) {
        if(RTKToken.transferFrom(msg.sender, address(this), amount)) {
            if(RTKLXToken.transfer(to, amount)) {
                _RTKLX_ExtCirculation[X-1] += amount;
                return true;
            } else {
                return false;
            }
        } else {
            AMMOToken.transfer(msg.sender, (X-1)*amount);
            return false;
        }
    } else {
        return false;
    }
}

Now i call this function with X = 2, and some valid address. Consider these 2 cases --
a) amount =  10 x (10^18)         <---  mentioned in this format for easier understanding
b) amount = 150 x (10^18)
Now, for case a, the gas limit is fine and comes less than 200,000
But for case b, the gas limit comes around 11,874,898
(NOTE :- Before executing this function, i have approved 1000 x (10^18) RTK and AMMO token.)
Can anyone tell me why is gas limit going so high ?
When i test it on remix, the gas limit only comes around 175,000


texts: Solidity inserting data that maps addresses to arrays of bytes32 error

texts:
My contract is as follows:

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

    function try(){}

    function fill_map(bytes32[10] _attributes) public  {
            Map[msg.sender].push(_attributes);
    }

    function get_map(address id) view public returns (bytes32[10]){
      return Map[id];
    }

}

The error I get is:

Member “push” not found or not visible after argument-dependent lookup in bytes32[10] storage reference Map[msg.sender].push(_attributes)

I also tried inserting the data with a loop as follows:

    for(uint i=0;i<10;i++)
    {
        Map[msg.sender].push(_attributes[i]);
    }

Also results in the same error.


texts: Ethereum uses the algorithm Hashimoto to mine for ether, other altcoins such as Expanse also use the same algo. Like bitcoin and namecoin, can ethereum and expanse be merge mined? (and how can it be implemented?)


texts: switching signer off when using parity as development network

texts:
I successfully created a private network with some accounts with lots of ETH following the instructions on parity's github

but when I try to create a transaction the signer wants me to validate each transaction. This is not usable in development.

I tried to use the --unlock account option and provided the --password file. Parity starts up but transactions simply hang after that.

How can I switch off the signer?


texts:
I have an enum with certain predefined data.
If at a later date, I have to add or push in more choices , can I edit the enum using some function ?
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }

If I need to add a choice, GoBack , can I do that ?
Thanks


texts: What are the best practices when setting up / interacting with a hot wallet on an application server?

texts:
Let's say I have a small application running on a server that interacts with the Ethereum blockchain to occasionally send ETH to random addresses at random times. This application also has other functionality like talking to external APIs. It's not a webapp though and has no web interface. In fact, the only way of configuring / accessing the server is SSH access.

Presumably, on the server you're going to be running either geth or parity locally in order to send transactions. These transactions need to be able to be sent without any user input (entirely automated).

What are the best practices here for working with parity or geth? Are there specific args that can be used to lock them down, yet still be able to send transactions?
Should the local accounts be always unlocked? Should the private key encryption passphrase be stored as a file on system, environment variable, other?
Is using cloud server providers not recommended (vs. running on your own hardware)?


texts: dapp based on ethereum for identity of a person

texts:
I have started taking interest in smart contracts and got to understand solidity and erc20 tokens a bit. Still I am not able to understand how can I design a dapp based on ethereum which can be used for identity of a person.

What should represent the identity (map address with identity proof)?
What would be role of transaction in this case?

I am not able to get a larger picture.

Any flowchart, architecture diagram etc would be very helpful.


texts: Create2 and new contract deploy at used address

texts:
Given that it seems possible, using somehow CREATE2, to deploy a new smart contract at a certain address where a different smart contract existed before to be killed...

(see @smarx answer here Can you selfdestruct a contract more than once?)

is it the case? How can I do it in practice?


texts:
I would like to run light nodes using geth, but I dont what version of geth is stable to that kind of node or even a sync mode fast node.

thanks a lot.


texts: Where does Metamask mobile for Android store wallet seed or private keys?

texts:
I'm curious where Metamask mobile app on Android (Samsung phone) stores the wallet seed phrases and/or private keys as a vault file in the phone.
I can find it on Windows but I don't know where to start with mobile. Thanks for the help.


texts: Remix: Potentially should be constant but is not.

texts:
I am trying to execute a contract provided as a tutorial for Remix at the following link:
https://gangachris.com/posts/a-look-into-remix-ide/
The contract is:

 pragma solidity ^0.4.20;

contract Cars{
   struct Car{
      bytes32 make;
      unint year;
   }

   mapping(address => Car[]) public carOwners;

   function registerCar(bytes32 _make, uint r) public {
      carOwners[msg.sender].push(Car({ make: _make,
                                       year: yr}));
   }
   function changeOwnership(address toOwner, uint index) public returns (bool){
      if(carOwners[msg.sender].length == 0) {
         return false;
      }
      if(carOwners[msg.sender].length > index + 1) {
         return false;
      }
      carOwners[toOwner].push(carOwners[msg.sender][index]);
    }
    function getCarMake(address owner, uint index) public view returns (bytes32 carMake) {
       if(carOwners[owner].length == 0) {
          return;
       }
       if(carOwners[owner].length > index + 1){
          return;
       }
       carMake = carOwners[owner][index].make;
     }
}

I found by search that it’s a Remix problem and not associated with Solidity. Some body please guide me.

Zulfi.


texts:
Is it possible to set a minimum price that a token can trade at? If as an example the floor was set at $1USD / and someone tries to sell the token at a lower price $0.75USD, the order will be rejected.
Thanks very much for your help in advance.


texts: Require in modifier: Undeclared identifier

texts:
curious why the require statement throws up Undeclared identifier in this solidity code:

pragma solidity ^0.4.8;

contract Escrow {
    ....
    modifier onlyafter(uint _time) {
      require(now >= _time);
      _;
}

I rewrote it as:

   modifier onlyafter(uint _time) {
      if(now >= _time){
       throw;}
      _;
}

which compiled fine.


texts:
I cloned go-ethereum, and used go mod vender.
When make, it's failed! and the error info is:
# github.com/karalabe/usb
vendor/github.com/karalabe/usb/hid_enabled.go:22:10: fatal error: ./hidapi/hidapi/hidapi.h: No such file or directory
   22 | #include "./hidapi/hidapi/hidapi.h"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.


texts:
I'm trying to run a Node on a private blockchain using the following command:

geth --datadir data/privateBlockchain/ -networkid 1234567 -port 30306 -nodiscover -rpc -rpcapi “db,personal,eth,net,web3,debug” -rpccorsdomain ”*” --rpcaddr ”localhost” -rpcport 8545

I got it from this tutorial:

https://medium.com/coinmonks/ethereum-land-marketplace-dapp-tutorial-part-1-create-and-deploy-a-smart-contract-351bc0d62be2

but when I ran it the following message is shown on the screen:

Fatal: Error starting protocol stack: listen tcp: lookup ”localhost”: no such host

I've also tried with 127.0.0.1 instead of localhost.

What can I do to fix this problem?


texts: Cannot vote on private chain. using dao tutorial

texts:
I'm trying to do a little extra with the ethereum dao tutorial on a private chain with several nodes having different etherbases.

What I did is as follows,

I created the contract, sent it some ether.
Added some members (around 8). I can see the members and member count fine.
I created a proposal.
Finally selected the VoteOn method but get Data cant be executed. message.

There is a votes array in Proposal but something doesnt sit well with this line p.votes[p.numberOfVotes]= Vote({inSupport: supportsProposal, voter: msg.sender, justification: justificationText});

EDIT: My goal is to see the votes and justifications. Without the above line, all works well.

Here is a part of the contract

event Voted(uint proposalID, bool position, address voter, string justification);
...
struct Proposal {
    address recipient;
    uint amount;
    string description;
    uint votingDeadline;
    bool executed;
    bool proposalPassed;
    bool proposalCanRun;
    uint numberOfVotes;
    int remainingVotesToPass;
    int currentResult;
    bytes32 proposalHash;
    Vote[] votes;
    mapping (address => bool) voted;
}

struct Vote {
    bool inSupport;
    address voter;
    string justification;
}
...
function voteOn(
    uint proposalNumber,
    bool supportsProposal,
    string justificationText
)
    onlyMembers
    returns (uint voteID)
{

    Proposal p = proposals[proposalNumber];         // Get the proposal
    if (p.voted[msg.sender] == true) throw;         // If has already voted, cancel
    p.voted[msg.sender] = true;                     // Set this voter as having voted
    p.numberOfVotes++;                              // Increase the number of votes
    if (supportsProposal) {                         // If they support the proposal
        p.currentResult++;                          // Increase score
    } else {                                        // If they don't
        p.currentResult--;                          // Decrease the score
    }

    ...

    p.votes[p.numberOfVotes]= Vote({inSupport: supportsProposal, voter: msg.sender, justification: justificationText});   //form vote obj from given data and add vote to vote group

    ...

    // Create a log of this event
    Voted(proposalNumber,  supportsProposal, msg.sender, justificationText);
}
...


texts: How can we address the security issues related to the executing of malicious codes?

texts: Assume a malicious code exists in a contract (either written intentionally or not). Is there any mechanism to prevent such codes from being executed? Is it even possible to do the monitoring?


texts: metamask and web3: Invalid number of arguments to Solidity function

texts:
my function has only one input string description :

function createProposal(string description) {
        Proposal memory p;
        p.description = description;
        proposals.push(p);
    }

and according to ABI I shoud only pass one argument to the function when I call it in web3:

 {
      "constant":false,
      "inputs":[
         {
            "name":"description",
            "type":"string"
         }
      ],
      "name":"createProposal",
      "outputs":[

      ],
      "payable":false,
      "type":"function"
   }

But when I call it using web3 I get this error:

Error: Invalid number of arguments to Solidity function
    at Object.InvalidNumberOfSolidityArgs (inpage.js:1)
    at u.validateArgs (inpage.js:1)
    at u.toPayload (inpage.js:1)
    at u.call (inpage.js:1)
    at b.$scope.createProposal (controller.js:44)
    at fn (eval at compile (angular.min.js:1), <anonymous>:4:162)
    at e (angular.min.js:288)
    at b.$eval (angular.min.js:151)
    at b.$apply (angular.min.js:151)
    at HTMLButtonElement.<anonymous> (angular.min.js:288)
    at HTMLButtonElement.dispatch (jquery.min.js:2)
    at HTMLButtonElement.v.handle (jquery.min.js:2)

Here is the code I wrote:

$scope.contract.createProposal.call({description: $scope.createproposal},
            (err, response) => {console.log(response)})

How can I fix this?


texts: Ledger Nano S backup phrase + Mnemonic code converter test

texts:
So, I just tried testing my backup phrase offline on this page:

https://iancoleman.github.io/bip39/

I typed in my 24 word backup phrase in the BIP39 mnemonic field and set the coin box to Ethereum.

Should the first generated address (m/44'/60'/0'/0/0) match my first public ledger address? Because they don't.

My Ledger is still working so I still have access to my Ether but I want to make sure my 24 word phrase is correct.


texts: When Eth Classic was forked off, did the people who held Ether suddenly hold an identical sum in two currencies?

texts:
I'm having a hard time understanding forks. What happened to the transactions in the blockchain before block 1'920'000? Are they present in both resulting blockchains, i.e. everybody then had two wallets filled with an identical amount of each currency?

If not, how was it solved instead?
If yes, did the resulting two tokens together have the value of one previous token, or did everybody suddenly get double rich?


texts: SyntaxError: no visibility specified. Remix

texts:
Going through some tutorials on ethreum, and got stuck here. The code seems ok for me. I tried to add the public/private  as the error says, then i got another error like:

parsererror function variable struct or modifier declaration expected

Who could help me out ?

pragma solidity ^0.5.0;

contract MyFirstContract{
    string private name;
    uint private age;

    function setName(string newName){
        name = newName;
    }

   function getName()returns (string){
        return name;
    }

    function setAge(uint newAge){
        age = newAge;
    }

    function getAge()returns (uint){
        return age;
    }
}

EDIT:
WHo could siply explain why this code doesn't display the name ? the function getName should've returned "jack"-string, but its blank. Also i'm using Java Script Environment


texts:
I'm learning Solidity. According to the docs, variables are permanently stored in contract storage. From my understanding (I may be wrong), the details are on the blockchain. My question is, how do I look at this? I was looking at EtherScan, however, I couldn't find anything. I'm learning this by writing contracts in Remix. While I know those contracts are on TestNet, I'm not sure which one (Ropsten, Kovan, or Rinkeby). I'm also not sure where the contract address is in Remix. I've successfully created my contract. But, I don't see an address anywhere.

I'm I simply overlooking something or am I way off in my understanding? Any help is appreciated.


texts: How do I get multiple signers for the Kovan testnet?

texts:
I am using hardhat + ethers + infura for my contract development and testing, and all has been fine so far. On my local computer, when I run
const [deployer, d2] = await ethers.getSigners();

in my javascript environment, I get two signers with a distinct address and with some power of ten of ETH stored on these addresses.
I am now moving to the Kovan testnet, because my contracts appeal to the Chainlink price feed. I use Infura to connect to the net. However, when I run
const [deployer, d2] = await ethers.getSigners();

console.log("deployer.address:", deployer.address);
console.log("deployer.balance:", (await deployer.getBalance()).toString());
console.log("d2.type", typeof d2);

I get
deployer.address: 0xE1**************************************
deployer.balance: 5******************
d2.type undefined

(Numerical values are partially hidden for privacy.)
How can I get multiple signers on the Kovan testnet? This is obviously necessary for proper testing for more complex contracts with multiple individuals involved. Thanks a lot!


texts: Unable to deploy contract on public chain

texts:
I was trying to deploy a contract to public ethereum network using Mist. I was able to send transaction successfully but my transaction is get no confirmations. It has been around 45 minutes and my transaction is still on 0 out of 12 confirmations. What could be the possible reason?

Note:

I have sufficient ethers in my account (more than 1)
I have tested the contracted on private testnet.
My ethereum node is not synced to blockchain (still 142882 blocks to go)
I have let Mist decide the fee for transaction.

Edit :
On Private-test Network:

Estimated fee consumption=0.02485106 ether (1242553 gas)
Provided max fee= 0.02685106 ether (1342553 gas)
Gas used: 1243385

On Public net:

Estimated fee: 1275193 gas
Provided Max fee: 1375193 gas
Gas used: 1375193

Also when I tried to track whether my transaction ran out of Gas using ether.camp, it could not find my transaction, same was with Etherscan.How even can I track my transaction?

Edit 2:
Mist stopped syncing at block 2283415, it is unable to download more peers from past 17 hours. I guess this may be a possible reason of why my transaction is not yet mined.


texts: Is every token on ethereum tradable on EtherDelta?

texts: Is every token on ethereum tradable on EtherDelta given that there is atleast 1 buyer and atleast 1 seller interested?


texts: How do you verify a contract on etherscan that is deployed by another contract?

texts:
How do you properly verify a contract on etherscan that is deployed by another contact?

I deployed a contract that deploys other contracts onto the blockchain.

The original contract is verified , however when that contract deploys contract onto the blockchain, I am unable to verify the contract.

Can anyone help with this?


texts:
Trying to use my eth_config.toml file in ethereum docker container, but it throws this error for some config flags, one of them:

Fatal: /root/ethereum/data/eth_config.toml, line 10: field 'EthashCachesOnDisk' is not defined in eth.Config, see https://godoc.org/github.com/ethereum/go-ethereum/eth#Config for available fields

it is not allowing me to use these flags too:

EthashCacheDir = "ethash"
EthashCachesInMem = 2
EthashDatasetDir = "/root/.ethash"
EthashDatasetsInMem = 1
EthashDatasetsOnDisk = 2
DiscoveryV5Addr = ":30304"

Is there some changes with new release?


texts: Error: Your homepage is not available when Trusted Signer is disabled

texts:
Just launched parity (using v.1.4.4 at the moment) as always, and when I try to access its UI (via http://localhost:8080/ ), I get this error:

404 Not Found
Your homepage is not available when Trusted Signer is disabled.

You can still access dapps by writing a correct address, though. Re-enable Signer to get your homepage back.

How can I reenable the signer? I've already tried parity signer new-token in the command line, and it gives me a new token, but I cannot do anything with that token in the 404 page, so I'm lost.


texts:
Im using truffle and openzeppelin for issuing my ERC20 token.
I already can add and buying the token, but still cannot transfer the token to another.

when i console.log the contract, it show me:

and i created front end for transfer

but i little bit confuse how to connected it to the contract to be able to transfering token to receiver address.

for now i just created function transfer like this:

transferToken() {
    let web3 = store.getState().web3.web3Instance
    const receiver = this.state.receipt_add
    const token_value = this.state.token_amount

    const token = contract(IYoToken)
      token.setProvider(web3.currentProvider)

    token.deployed().then(inst => {
        inst.transfer({
            to: receiver,
            amount: token_value
        })
    })
}

but its not working, and the error message is:


texts: Read transaction logs of another Smart Contract

texts:
I have to track user activity in DEX smart contract and do some validation/operation based on that information.
DEX itself does not API to retrieve that info, but emit events, so is there any way to read transaction logs from the smart contract?
UPDATE 1
DEX smart contract in TRON blockchain:
https://tronscan.org/#/contract/TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE/code
UPDATE 2
Here the Smart Contract itself with the events I am interested:
pragma solidity ^0.5.8;

interface IJustswapExchange {
  event TokenPurchase(address indexed buyer, uint256 indexed trx_sold, uint256 indexed tokens_bought);
  event TrxPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed trx_bought);
  event AddLiquidity(address indexed provider, uint256 indexed trx_amount, uint256 indexed token_amount);
  event RemoveLiquidity(address indexed provider, uint256 indexed trx_amount, uint256 indexed token_amount);

 /**
   Smart contract code goes here ...
 **/
}

P.S. If possible I will need events filtered by the first argument.
UPDATE 3
Ethereum equivalent contract with events:
https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code
contract Uni {
    event Transfer(address indexed from, address indexed to, uint256 amount);
}


texts: Can you use Ganache to test create wallet using web3py?

texts: I am using the web3.py library using the web3.eth.account.create () to create my own wallets, my question is if there is any way to use the Ganache services as Provider to be able to perform tests when they are created wallets and make transactions between them


texts:
Is there a difference in gas cost between storing data within a contract itself vs calling an external contract to store the data?
I'm guessing that you must pay an extra 20,000 transaction cost to send the data to another contract?


texts: How can I fetch current pair prices through uniswap-v2 API?

texts:
I need to quote online prices of different token pairs through uniswap-v2 API. As the below picture shows, I tend to pass token pair (maybe with base token desired amount) to the API and get all price related values as result.

I found Fetcher.fetchPairData method in uniswap documentions, but it does not return the correct values. Am I using the correct method or I have to use another method for this purpose?


texts: How to steal eth using delegatecall and selfdestruct

texts:
This documentation says

  Even if a contract’s code does not contain a call to selfdestruct, it can still perform that operation using delegatecall or callcode.

This worries me.

I've created some pseudo code to give a gist of a possible exploit.  The code below creates an "exception: invalid opcode", but you'll be able to follow my logic.  Assuming this style of attack works, what can be done to guard against it?

pragma solidity ^0.4.2;
contract Steal{
      function delegatecall_selfdestruct(address _target) external returns (bool _ans) {
          _ans = _target.delegatecall(bytes4(sha3("selfdestruct(address)")), this);
      }
}

contract Mark {
  function Deposit() payable {
  }
}

The idea is to send some testnet ETH to the contract Mark then use the Steal contract to call Mark and make it selfdestruct and give the ETH to the Steal Contract.


texts: Mist Wallet Stuck on "Connected to Node"

texts: It got about 80% of the way through the blockchain download, then it just stopped and went to "finding peers" So I closed the wallet, restarted the PC, and now it just gets stuck on "connected to node". I have since moved the lightchaindata folder out, and am currently re-downloading. I imagine the same thing will happen again. What can I do?


texts:
I have a struct that has an array of addresses. When the address array is empty and I try to get index 0 I would expect it to return address(0), but instead it reverts. Any way around this?

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  // THIS REVERTS
  address a = map.addresses[0];
}

EDIT:

I updated my struct to contain an exists mapping, but am wondering if there is another way. This works:

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
  mapping(address => bool) exists;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  if (map.exists[key] == false) {
    map.indices[key] = map.addresses.length;
    map.addresses.push(key);
    map.exists[key] = true;
  }
}


texts:
Does ethereum work when there is only TCP available?

Can one use ethereum as a client over Tor?

It does not work for me. Using Whonix. So running the traffic over Tor is not an issue. Blockchain download never starts.


texts: Quorum private transactions - Inconsistent state

texts:
We are using Quorum and sending private transactions
Participant A  - Sending 3000 Private transactions to  ( Participant B and Participant c)
However, all 3000 transactions are committed successfully at Participant A. In case of Participant B and Participant C, only few transactions had gone through. Hence , the state is inconsistent across parties.
Participant A – 3000 – OK
Participant B – 487 – Inconsistent state ( EVM reverted is the error message)
Participant C – 487 – Inconsistent state ( EVM reverted is the error message)
We checked Participant B Node’s eth.syncing status and blocks syncing is fine. Also, txpool.status – both pending and queued returns 0.


texts:
I have this example contract.

contract Example{
    function foo(){
        revert("hello world!!!");
    }
}

When execute the foo function, this revert the tx, how get the revert message?

PD.: i use truffle to test contracts

now truffle support revert message


texts:
how can we get all the past events of the contract ?
I am trying like this :

on web3.js ( "web3": "^1.0.0-beta.34"):

// Add the web3 node module
var Web3 = require('web3');

// Show web3 where it needs to look for the Ethereum node.
web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/_ws'));

// Define the contract ABI
var abi =

// Define the contract ABI and Address
var contract = new web3.eth.Contract(abi, '0x5a3c9A1725BB82690ee0959c89abE96fD1b527ee');

// Fun console text, you can ignore this.
console.log('-----------------------------------');
console.log('Matching Smart Contract Events');
console.log('-----------------------------------');

const filter = { fromBlock: 0, toBlock: 'latest'}; // filter for your address
const events = contract.allEvents(filter); // get all events
console.log(events)

// contract.Transfer({}, { fromBlock: 0, toBlock: 'latest' }).get((error, eventResult) => {
//   if (error)
//     console.log('Error in myEvent event handler: ' + error);
//   else
//     console.log('myEvent: ' + JSON.stringify(eventResult.args));
// });

// contract.allEvents(fromBlock: 0, toBlock: 'latest', (e, res) => console.log(res))

on web3.py (web3==4.3.0) :

import requests
from web3 import Web3,WebsocketProvider

def main():
 web3 = Web3(WebsocketProvider("wss://mainnet.infura.io/_ws"))
 print (web3, "web3")
 contract_address = "0x5a3c9A1725BB82690ee0959c89abE96fD1b527ee"
 contract_abi =
 contract = web3.eth.contract(address=contract_address, abi=contract_abi)
 print (contract, "contract")

 transferEvent = contract.eventFilter('Transfer', {'fromBlock': 0,'toBlock': 'latest'});
 print (transferEvent, "transferEvent")

 eventlist = transferEvent.get_all_entries()
 print(eventlist, "eventlist")

 # transferEvent = contract.eventFilter('Transfer', fromBlock = 0)
 # transferEvent = contract.events.Transfer.createFilter(fromBlock = 0)
 # print (transferEvent.get_all_entries())

if __name__ == "__main__":
 print ("Script has started...")
 main()
 print ("Script has ended...")


texts:
I am trying to make geth work with ropsten but I am not sure why its refusing to load my ropsten funds.

I have a ropsten account which I have imported to geth via its private key:

geth --testnet account import "C:\Wallet\Ropsten.txt"

The account was created in MetaMask and currently has 5.783 ropsten ether.

Now when I start geth in RPC mode with --testnet

 geth --rpcapi eth,web3,personal --testnet --rpc

Then when I try to check my balances using web3.js, I always get my balance as 0:

 web3.personal.unlockAccount(web3.eth.accounts[0],"<password>", 15000);
 console.log(web3.eth.getBalance(web3.eth.accounts[0]).toNumber());

This always gives me 0;

I also tried specifying the ropsten bootnode manually:

geth --rpcapi eth,web3,personal --testnet --fast --bootnodes "enode://20c9ad97c081d63397d7b685a412227a
40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,eno
de://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677
ce455ba1acd9d@13.84.180.240:30303" --rpc

but still it is not loading my balance which leads me to believe that its not connected to ropsten or I am doing something wrong.

How can I make geth work with ropsten?


texts: Problem with Bonding Curve Contract from Relevant

texts:
I’m trying to get the relevant bonding curve contract to work.

The only thing I changed is that I added an older compiler version in truffle config.

compilers: {
  solc: {
    version: "^0.4.25",
  }
},

Otherwise I got problems with the breaking changes of the new compiler version.

When I try to run the tests now, I get this error message:

==== JS stack trace =========================================

    0: ExitFrame [pc: 0000007F84250361]
Security context: 0x01658c29d9f1 <JSObject>
    1: /* anonymous */ [000001A020368951] [C:\Users\moritz\code\ethereum\urlin-test4\bonding-curve\node_modules\babylon\lib\index.js:~4415] [pc=0000007F8452AB2D](this=0x03fdca333061 <Parser map = 00000248CBED00E1>)
    2: /* anonymous */ [000001A020367ED9] [C:\Users\moritz\code\ethereum\urlin-test4\bonding-curve\node_modules\babylon\lib\index.js:~3606] [pc...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF65D76AB9A v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4810
 2: 00007FF65D710C86 uv_loop_fork+80486
 3: 00007FF65D711BB0 uv_loop_fork+84368
 4: 00007FF65DB8E99E v8::internal::FatalProcessOutOfMemory+798
 5: 00007FF65DB8E8D7 v8::internal::FatalProcessOutOfMemory+599
 6: 00007FF65DE67B54 v8::internal::Heap::RootIsImmortalImmovable+14788
 7: 00007FF65DE5D794 v8::internal::Heap::CollectGarbage+7556
 8: 00007FF65DE5BE68 v8::internal::Heap::CollectGarbage+1112
 9: 00007FF65DE657D7 v8::internal::Heap::RootIsImmortalImmovable+5703
10: 00007FF65DE65856 v8::internal::Heap::RootIsImmortalImmovable+5830
11: 00007FF65DA26341 v8::internal::Factory::NewFillerObject+49
12: 00007FF65E18110A v8::internal::StoreBuffer::StoreBufferOverflow+26826
13: 0000007F84250361
npm ERR! Test failed.  See above for more details.

Does anybody know how I could get this to work? Or can point me to another working curve boding contract?

Thanks a lot for your help!


texts: How does a miner mine blocks without any transactions on a private network?

texts:
If I start a node with a random network id and a custom data directory, I can create an account and start mining.

What I expected after starting the miner is that it won't be able to mine any blocks since there are no other nodes who are submitting transactions.

But, when I started the miner, it started to mine blocks continuously.

So, what does these blocks contain? How can a block be mined without any transactions?


texts: Cross chain call contract on ethereum from private network

texts:
Im looking for a way to call a contract that is deployed on the ethereum main network using Go (or JS/anything).
From what i can see the foolproof way is to do so over json RPC but i would love to hear of gracefull solutions if
anyone has them.


texts: Saving the actual data vs. hash of the data - which one is better?

texts:
I am new to etheruem, I would like to create a smart contract for keeping document data.

From 2 designs below, can I know the pro and con of each one, please?

put the array of raw JSON data to the blockchain

items = [
{
   field1: value1,
   field2: value2,
   ...
   fieldN: valueN
},
...
]

put only hash of JSON data to the blockchain

items = ["hash of object1", "hash of object2", ...]

What are the pro and con both designs above in term of fee (when insert or update), query speed?

and if my system has up to 100 million documents. Can the etheruem blockchain hold all of my data?

Thanks


texts: with Web3.js, display sendTransaction data field from function call

texts:
From js, I typically call a function with something like this:

theFunction=someAbi.at(0x1234...);
theFunction.someMethod(param1, param2, param3,
    {"from": 0x111222..., "to": 0x1234..., "value":web3.toWei(2, 'ether')});

I would like to also display for the users how they would achieve the same manually, using the geth console, something like

web3.eth.sendTransaction({'from':0x111222..., 'to':0x1234,
    'value':web3.toWei(2, 'ether'), 'data': 0xXXXXXXX})

So, how do I get the 0xXXXXXXXX part from my original theFunction.someMethod(...) call?  I know it can be calculated, but web3 can obviously do so already, so I don't want to reinvent the wheel.


texts: How to call a deployed smart contract methods from android

texts: I deployed a smart contract into my private network using truffle framework. After deployed the contract I implemented a client interface using android from android I want to call the methods of deployed contract. is it possible to call the smart contract methods using truffle? or it is possible with web3j only? with web3j can I again deploy the smart contract with solc? anybody, please give me a clarity


texts: How to speed up ethreum transaction after initiating

texts:
Is there any possibility to speed up transaction after creating transaction receipt.
My project need to similar functionality we have with metamask is there a way we can accomplish this using any javascript libraries like web3 etherjs  ?


texts: How time difference can be calculated by block.number and how it is different from block.timestamp?

texts:
I have been looking into the code recently done by some developers, they are using block.number + numbers to calculate the time difference. For example if I want to lock fund for some 6 months or 180 days developers are using block.number + (some calculated numbers 1296000 blocks) to calculate number of funds to be unlocked.

I would like to know how this calculation works with time period. And why not to use block.timestamp instead? Is block.number reliable?

Here is the code snippet. It is basically vault that hold the tokens for 180 days.

contract Vault is SafeMath {

    // flag to determine if address is for a real contract or not
    bool public isVault = false;

    Token token;
    address multisig;
    uint256 unlockedAtBlockNumber;
    // 1296000 blocks = 6 months * 30 days / month * 24 hours / day * 60 minutes / hour * 60 seconds / minute / 12 seconds per block
    //uint256 public constant numBlocksLocked = 1296000;
    // smaller lock for testing
    uint256 public constant numBlocksLocked = 12;

    /// @notice Constructor function sets the Lunyr Multisig address and
    /// total number of locked tokens to transfer
    function Vault(address _Multisig) internal {
        if (_Multisig == 0x0) throw;
        token = Token(msg.sender);
        multisig = _Multisig;
        isVault = true;
        unlockedAtBlockNumber = safeAdd(block.number, numBlocksLocked); // 180 days of blocks later
    }

    /// @notice Transfer locked tokens to multisig wallet
    function unlock() external {
        // Wait your turn!
        if (block.number < unlockedAtBlockNumber) throw;
        // Will fail if allocation (and therefore toTransfer) is 0.
        if (!token.transfer(multisig, token.balanceOf(this))) throw;
        // Otherwise ether are trapped here, we could disallow payable instead...
        if (!multisig.send(this.balance)) throw;
    }

    // disallow payment after unlock block
    function () payable {
        if (block.number >= unlockedAtBlockNumber) throw;
    }

}


texts: How to recover presale wallet password from mnemonics

texts:
I have the following stored in my secure password manager from the presale:

A 40-character hexadecimal address
A 64-character hexadecimal private key
A list of 24 mnemonic words
Something I called "ethereum purchase password", a 16-character string with numbers, letters and punctuation characters.
A json file containing my wallet

I'm trying to import this json file into ethereum wallet, and it asks for a password. When I use my "ethereum purchase password," it says the password is wrong. Not sure what the problem is, but I assume I should be able to recover my password from the mnemonic words. How do I do this?


texts: What is the merit of creating new smart contract languages like Solidity instead of using other languages?

texts: What is the pros and cons of creating new languages like Solidity for smart contracts instead of using other computer languages like Golang or Python?


texts: solidity - check bignumber returned from solidity

texts:
I am using truffle, but that shouldn't make any difference here...
When using contract's transfer mehtod, I want to pass a parameter - 1000000000000000000000000, but since this is too big, it results in an error. That's why I pass web3.utils.toBN('1000000000000000000000000')
After that, I should check if one of the address in solidity holds this amount of tokens.
So I have this:
let balance = await instance.balanceOf(address);
This returns a bigNumber.
Way 1: To get an actual number so that I can test if it worked, I tried this: balance.toNumber() which didn't work.
Way 2: Then, I tried  assert.equal(balance, web3.utils.toBN('1000000000000000000000000'));, but now, it shows an error -       AssertionError: expected <BN: d3c21bcecceda1000000> to equal <BN: d3c21bcecceda1000000> even though they still seem equal.
My question would be what way do you choose to work with such cases ? Way 1 or Way 2? and if so, how do I fix my issue then ? Thanks..


texts: How to listen to contract events using ethers.js?

texts:
I need to listen to the specific contract events and do some task once the event is emitted. I didn't find proper docs on ethers.js documentation.
Can anybody tell me how can I keep listening to my contract events using ethers.js?


texts: How can we obtain the state value of a variable from previous block number using web3

texts:
I have a private chain and I am running own archiving node. The node connected with --fast cache=1024 option.

For example I have a set function on my smart contract.

contract smartContract {
    uint  value;
    function set(uint input) returns (bool success) {
         value = input;
    }
    function getValue() public view
     returns (uint)
    {
        return value;
    }

}

This function is called at block number 100 and 200.

smartContract.set(10) //deployed at block number 100
smartContract.set(20) //deployed at block number 200

At this point. if our blockchain is sync, as we know, when we call smartContract.get() it returns 20.

Here mentions that smart contact can only see the current state.

  A contract can only see the current state when it executes, not
  previous states. This restriction allows validating nodes to work only
  with the current state, rather than needing to store and be able to
  access all the previous states.

Here we can get previous blocks data. Since we can obtain previous block data, we could obtain the previous states.

[Q] Could web3 retrieve state of a value from previous block numbers instead of returning the its latest state value?

If we provide the block number such as 100, smartContract.get() at 100; somehow can web3 return value's value at block number 100 instead at latest?


texts: Cannot get very simple delegatecall to work

texts:
I have this super simple code:
pragma solidity 0.5.13;

contract test1{

    uint256 public number;
    address public sender;

    function setNumber(uint256 _number) public {
        number = _number;
        sender = msg.sender;
    }
}

contract test2{

    bool public success;

    function sendNumber(address _contractaddress) public {

        (bool _success, ) = _contractaddress.delegatecall(abi.encodeWithSignature("setNumber(uint256)",69));
        success = _success;
    }
}

I'm deploying both contracts, then calling sendNumber of the second contract and passing the address of the first contract. I then call number() and sender() on the first contract, but both are unset.
Is there some dumb syntax error I am making here? success is returning true on the call.


texts:
data = web3.utils.sha3('balanceOf(address1)').slice(0,10) + randomstring.generate({ length:24, charset:'0'}) + address1.substring(2);

web3.eth.call({to : config.ContractAddress, data : data}).then((result) =>{
                   console.log("bbbbbbbbb", result);}).catch((e) =>{
                     console.log("eeeeeeeeeee" , e);
                   });


texts: How can I exclude msg.sender from a list

texts:
For the sake of humanity, could anyone help please?

A splitValue is send by msg.sender - the sender is part of the beneficiaryList - but excluded from the list at moment of sending.
How would that look like in code?

I have a start:

uint splitValue = uint(msg.value/beneficiaryList.length);
     for (uint index = 0; index < beneficiaryList.length; index++) {
     beneficiaryList [index].transfer(SplitValue);

     if(participants[msg.sender] != 0){
     beneficiaryList [index] != (msg.sender); }

Not sure if the last two lines are correct.


texts: Can contract code query the block chain?

texts:
Is it possible to have a contract whose methods iterate through the block chain? in that they can read block/transaction related data and make transactions based on them?

Or monitor the block chain for new blocks and perform future transactions (act like event handlers but for the block chain as a whole)?