texts: Why can't I deposit an ERC20 token from my wallet to my deployed contract?

texts:
Hello all I've recently starting diving into solidity development and I'm having trouble with ERC20 token interactions.

What I want to accomplish is sending ERC20 tokens to a smart contract that I created.

pragma solidity ^0.5.0;

contract ERC20 {
    function totalSupply() public view returns (uint supply);
    function balanceOf(address _owner) public view returns (uint balance);
    function transfer(address _to, uint _value) public returns (bool success);
    function transferFrom(address _from, address _to, uint _value) public returns (bool success);
    function approve(address _spender, uint _value) public returns (bool success);
    function allowance(address _owner, address _spender) public view returns (uint remaining);
    function decimals() public view returns(uint digits);
    event Approval(address indexed _owner, address indexed _spender, uint _value);
}

contract MySmartContract {
    function approveDeposit(address tokenAddress) public {
        ERC20 token = ERC20(tokenAddress);
        token.approve(address(this), token.balanceOf(msg.sender));
    }

    function depositToken(address tokenAddress) public {
        ERC20 token = ERC20(tokenAddress);
        uint tokenAmount = token.balanceOf(msg.sender);
        token.transferFrom(msg.sender, address(this), tokenAmount);
    }
}

In my wallet I have BAT tokens. After calling the approveDeposit function with the BAT token address, I try calling depositToken but it returns an error.

What am I doing wrong?


texts: Ethereum account model - SPV proofs possible?

texts:
Ethereum does use an account-model and not like Bitcoin an UTXO model. Is it possible to do SPV-proofs in Ethereum and if so, can you please explain how to do it?

Correct me if I'm wong.

The state of an account is not stored on the blockchain in Ethereum, it is computed and stored in a local database on the node.

So in order to compute the state of an account you have to execute all smart contracts which this account has triggered and not only that. These smart contract may depend on an other account's state and so on and so forth. It seems pretty impossible to me to have an SPV-proof on Ethereum.


texts: How transaction fees will be affected after implementation of Casper protocol?


texts:
How can I parse JSON in solidity?

The idea is to have a function or similar which is able to parse JSON inside a Solidity contract.

With a simple JSON object (only key value strings, like {'A': 'a', 'B': 'b'}) the solution should be able to transform it to a mapping(string => string).


texts: What is the scalability limit for POA Ethereum (number of nodes)?

texts:
Tried to find any benchmarks what is the maximum number of nodes for Ethereum PoA network.
When does a network latency become crucial? Looking for any sources / empirical benchmarks.


texts: Let say I want to be sure that some action is executed every 24 hours. Is there a way to guarantee this if my contract have necessary ethers to pay for this calls?


texts: Uniswap: how is price impact being calculated?

texts:
i know that price impact implies that the difference between market price and estimated price due to trade size.
say i have a pair: cat token and dog token with
pooled cat : 0.999992
pooled dog : 1.99998
from here i assume that market price for cat is 1.99998/0.999992 = 1.99999 dog
so next, in uniswap swap interface i key in 1 cat, then its estimate dog show me 0.998497
the way i calculate price impact is (1.99999 - 0.998497)/1.99999 * 100 = 50.0749%, but uniswap show me 49.78%
someone please tell me how price impact is being calculated? thanks


texts: How are solidity integer overflows handled?

texts:
uint8 x = 255;

x += 10;

Is x going to be 0 or 9?


texts: How exactly to calculate the Ethereum Mixhash?

texts:
Sorry I have tried to study the yellow paper, but it sounds quite tough to me.. I know the mixhash is a formation of nonce, but I want to know what exactly "forms" the mixhash(e.g. header + nonce ?) and what's the algorithm and calculation?

Thanks!


texts: dynamic value (amountEth) doesnt work in very basic web3 UI webpage

texts:
I am a newbie and try to learn to code web3 interfaces to call basic smart contract funtions.
For now I made a button - when clicked it send 1 ETH to a specific (static) address. This worked fine... Now I try to do the same but this time I want an input field to let the ETH be dynamic... I did not find any template for a "Presale-Website" or a "Payment Website with dynamic value input" ... So I tried to hardcode it. But whatever I try, either it doesnt work AT ALL or the button works but will always try to send 0 ETH, no matter what input-value i type into the input-field...
Any help (a link to a working template, any hint, any tutorial etc.) is welcome...
Here is my code:
    <!DOCTYPE html>

    <input onclick="fill_amount" id="amount" type="number" placeholder="eth">
       <button class="pay-button">Pay</button>


texts: Do I need to specify nonce in token transfer code?

texts: I am using ethers.js to transfer erc20 token. How do I put nonce in transfer? Nonce can be any number?


texts: Solidity. Truffle. Call contract function in migration file

texts:
Tell me, how through truffle, after the deployment of the contract, call one of its functions? I mean, during migration, how can I call the function of the contract?

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

    module.exports = function(deployer) {
        var ownable;
        var ownableAddress;

        deployer.then(async () => {
            ownable = await deployer.deploy(Ownable);

            ownableAddress = ownable.address;
            await ownableAddress.addContractAdresses(address);
        });
};

Here is the function call

await ownableAddress.addContractAdresses(contract.address);

But I get an error

TypeError: ownableAddress.addContractAdresses is not a function

Here is the contract itself and its function

pragma solidity ^0.5.0;

contract Ownable {

    mapping (address => bool) public authorizedContractAdresses;

    function addContractAdresses(address _address)
        public
    {
        authorizedContractAdresses[_address] = true;
    }
}


texts: How to deposit to WETH in Solidity 0.6 and above?

texts:
Solidity 0.6.0 introduced a breaking change in how ETH transfers are performed. The following doesn't work anymore:
weth.deposit.value(amount)();

What is the latest syntax for depositing ETH into the WETH contract?


texts: How to edit starting parameters of the genesis block in mix?

texts:
When I click the "import" button it seems to want to import stuff from a file. But what structure etc should the file have?

Cannot find any documentation on this. Any pointers gratefully received.


texts: Ethereum development environment for Mac OSX El Capitan

texts:
What is the recommended development environment setup for developing Dapps on OSX El Capitan for a beginner?
What tools i need to get started with DAPP development?


texts: Contract method not returning the value while using ethjsonrpc and pyethapp

texts:
for some reason, i had to use python version of Ethereum implementation i.e PyEthApp. I am able to setup the local network and able mine the transactions.
 I was exeperimenting with contracts for my application. Here is the sample contract i was using for my learning

pragma solidity ^0.4.4;
contract Example {
    // Device Registry
    mapping (uint => string) public _registry;
    uint nIndex= 0;
    function set_s(string new_s) {
        _registry[nIndex] = new_s;
        nIndex = nIndex + 1;
    }
    function get_s(uint number) returns (string) {
        return _registry[number];
    }
}

when i test this contract in remix, it is working fine... in the python shell, i have imported ethjsonrpc and checking the API methods

for storing data in to array,

 >>> tx = c.call_with_transaction(c.eth_coinbase(), contract_addr, 'set_s(string)', ['Dinesh'])

transaction submitted to miner, and after sometime it is mined successfully..

but i got struck with retrieving the data from mu contract array '_registry'.. i have tried to use call method directly,

>>> results = c.call(contract_addr, 'get_s(uint256)', [0], ['string'])

but it was giving

  "AssertionError: Not enough data for head"

when i checked and googled it, people were saying transaction has to be mined. So i changed my command to

>>> tx = c.call_with_transaction(c.eth_coinbase(), contract_addr, 'get_s(uint256)', [0])

here also transaction submitted to miner, and it is mined eventually... But i could n't see the return value anywhere..

anyone got it worked?  please let me know, if there is a workaround to call get methods with some return value


texts:
Ethereum Wiki:

  Every unique set of key/value pairs maps uniquely to a root hash, and
  it is not possible to spoof membership of a key/value pair in a trie
  (unless an attacker has ~2^128 computing power)

I did not understand the statement shown above, where:

[Q] Why an attacker needs ~2^128 computing power to spoof membership of a key/value pair in a trie?

Thank you for your valuable time and help.


texts: Script to show independencies and inheritances

texts: I have my projects in Solidity with contracts in different files, folders. I would like to write a Python/Javascript script to tell me how the files are dependent on each other (i.e. A requires B, then B requires C and D, etc.). I also want to do it for class inheritance. What is the best way to do it? Do I just have to parse the code as text file and look for import or is there a better way? Thanks in advance.


texts: Anyone here familiar with the Ethereum block chain developers program/certification?

texts: I read about the block chain developers course with the goal of creating about 6000ish certified Ethereum developers.  I am trying to find out if anyone has actually done the course? I am a Java and RoR developer and would like to branch out in to crypto currency. Thanks


texts: Transactions on my private ethereum blockchain don't work. The balances of the accounts stay the same

texts: I have 2 accounts with initial balance, 100000 and 120000. I tried 2 transactions. The 1st was a 20000 ether transaction from the 2nd account to the 1st. And a 1000 ether transaction from the 2nd account to the 1st. Both of them didn't make a difference to the balance.


texts: Transaction Timing Implications for Reentry Attacks

texts:
This is the classic reentry attack:

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    (bool success, ) = msg.sender.call.value(amountToWithdraw)("");
    require(success);
    userBalances[msg.sender] = 0;
}

I don't understand how this works. It seems one transaction is not completed before the other. I know that in the Dao attack a contract using a fallback function on call.value() rigged the system to stall before adjusting the state variable userBalances[msg.sender], but if this is merely due to the extra time created via this fallback function, it suggests an improbable but possible problem.

Say I have 10 tokens in contractBalance, and users can put them into their contract balance.

function takeAllTokens(uint x) public {
    require(x < contractBalance);
    uint amountToTake = contractBalance;
    uint y = x + 1; // just to give it a couple pico seconds
    contractBalance -= x;
    userBalances[msg.sender] = contractBalance;
}

If transactions are not processed completely in sequence, two people arriving simultaneously asking for 10 tokens would each end up getting 10 tokens, more than is in the contractBalance in this example.

Is this only impossible because in this latter case, the time needed to go from one line to the next is so short, that while possible, its probability is considered impossible?


texts: Is there an "in" keyword in Solidity similar to Python?

texts:
I understand that "in" is a reserved keyword in the Solidity language (for now) but can it be used like the "in" keyword is used in the Python language? That is can it be used to find a specific value from a range of value like from a list?

To be clear, the usage I am talking about (in Python) has been explained here. I want to know if there is a similar keyword in Solidity >0.6.0 ?

I would like to put forward a basic example :

If I create a list of some arbitrary numbers and want to find if the number 5 is present in that array, is there some simple keyword like "in" such that I write "5 in list" and get a boolean result as true/false.

Even if it is not there can you please guide me to the simple most way to do something like above?


texts: Contract not showing the name and symbol

texts: I deployed a contract on ropsten but it was not showing the name and the symbol. I have the feeling that there is something wrong at the deployment and I think it has to do with the parameters. As you can see in the picture.... is it the way I should write them or is it wrong  ? Thank you very much


texts: How to call a function and to read return values from an external deployed contract address?

texts:
I am trying to call a function from deployed contract address using the below format

DeployedContractAddress.call(bytes4(keccak256("get(address)")),0xfffff);

But when trying to call the get(_address) using deployed contract address(without abi encoded), it should return an array. But here, it returns Boolean values true or false.

 function get(address _address) public returns (uint256[]){
 for(uint i=0;i<n;i++){
     arr[address].push(i);
 }
 return (arr);
}

Is there any simple way to get an array values without using ABI encoded?


texts: I have a full Ethereum Wallet, so I funded it with bitcoin and I saw the transaction in the etherscan website. But my balance (after 1 day) is still 0. what can I do? There are only 105 blocks left and the transacion block was already syncronized.


texts: Approve() and transferFrom() functions seems to be giving errors

texts:
I am trying to develop a smart contract very similar to:
https://github.com/tapmydata/tap-protocol/blob/main/contracts/VestingVault.sol
So , I deployed ERC20 token and passed the contract address to constructor of VestingVault.
Next , I passed VestingVault contract address to approve() of ERC20 as spender and amount equal to totalsupply.
After that, I try to run addTokenGrant(), but it throws. I suspect problem is in  require(token.transferFrom(owner(), address(this), _amount));
Can somebody please help me out , thanks in advance


texts: If Ethereum switch to POS,how do/should I prepare the mining machine?

texts:
Sir,
   We are developing a application using Ethereum. For now,we use test environment.But in the future,We will  build up a private chain for formal environment. If Ethereum switch to POS from POW,how do I build the mining machine? I am afraid that if I prepare mining machines now,these machine will be useless when Ethereum switch to POS.

How do I plan the infrastructure?
   Thanks!
             Barkely


texts: How network hashrate is being calculated?

texts:
Hashrate
The number of attempts that miner makes per second is known as the hash rate or hash power.
Network's hashrate
It is the most important data point in blockchain tech. ... Essentially, the hashrate describes how much computing power (called hashing power in blockchain speak) is being thrown at the network, by nodes all across the world.

consider there are 10 nodes in the network with each has hashing power of 60h/s

then how the Network's hashrate is being calculated?

If 2 nodes out of 10 goes down, is that effects the Network's hashrate ?


texts: How to add values to array within a struct in Solidity?

texts:
First of all, sorry for my English as a Google Translate

I wanted to add values to the list inside the struct, but with the code below the following error appears: UnimplementedFeatureError: Copying of type struct Ballot.Play memory [] memory to storage not yet supported.

pragma solidity ^0.6.7;
contract Ballot {

    struct Play {
        uint cod_music;
        uint qtd;
    }

    struct Listener{
        address user;
        Play[] listened;
    }

    Listener[] listeners;
    Play[] tests;

    function listenMusic(uint cod) public {
        tests.push(Play({
            cod_music: cod,
            qtd: 1
        }));

        listeners.push(Listener({
            user: msg.sender,
            listened: tests
        }));
    }
}

Any suggestion?


texts: If crypto art is stored off-chain, how does the collector have any control over their NFT's contents if the server where it is saved shuts down?

texts:
CryptoKitties essentially sells crypto art NFTs to collectors on the Ethereum blockchain. However, the pictures of the cryptokitties are stored on the company's server, since the NFT merely represents ownership of the image. The artist/creator of the NFT always retains a perpetual obligation and right to store the image, whether it be on the NFT platform where they minted the NFT in the first place, whereas the collector does not have any whatsoever.
If the company's website or the company itself were to go down, then that cryptokitty would disappear. In other words, despite the collector owning the image via the NFT, they have no control over the actual online existence of the image. Even if they saved a copy of the image somewhere, the NFT can't be rewritten to redirect the link to the image, embedded in the NFT itself, to the collector's own copy since, upon its minting, the NFT's link permanently points directly to the cryptokitties server forever.
Now, think of this, people are known to dump $1,000,000's into these NFTs and other similar NFT collectibles. Do they not realize just how little control they have over their so-called "possession"? The fact that the image is stored off-chain on a server that the collector doesn't own or control, doesn't this jeopardize and undermine the whole idea of "ownership"?


texts: What does the keyword `var` do in solidity?

texts: I see it in some contract examples, but it doesn't look like it has the exact same purpose as regular JavaScript. Can it be used to initialize variables in a specific scope without declaring a type?


texts: How to convert an Ethereum address to an ASCII string in solidity

texts:
I've seen another question answered with a solution to this here : Convert address to string but it results in an error so I'm re-asking. The error is:
"TypeError: Operator < not compatible with types bytes1 and int_const 10"
For context, I'm trying to build a function to dynamically construct a URI which includes the address of the contract where the function lives.


texts: Is there Mist version without Coinbase support?

texts:
I wanted to update Ethereum Wallet, but in the changelog I read that they made some kind of deal with Coinbase (that the Ethereum Foundation has no money from, apparently) and added direct support for that one exchange. I do not want to be a part of that, so I ask: Is there an up-to-date version of the Ethereum Wallet that does not this built in (an official fork, perhaps)?

And there are two downloads on the download page: Ethereum Wallet and Mist. I suppose they both have this support, so what is the difference between them? I have searched, but they are mostly mentioned as if they were the same.


texts: How to watch log for all instances of a specific type of contract?

texts:
Attaching a watcher for every instance of a contract is not a good idea in terms of memory and CPU. So is there a way to watch for events from all instances of a contract i.e., by registering a single watcher for all instances of the contract.

Note that I don't want to provide the address of the contract instances because that will force whole DB lookup.

I  need to display the changes on the contract in real-time on the client and also update the DB in real-time.


texts: How to distinct between value types in transfer

texts:
How does one distinct between sending different value types?
E.g. between a transfer of ETH and a transfer of ERC20 token.
Extending the question, is it strictly necessary for an external contract such as an escrow, to be approved, to transfer any ERC20 on behalf of one of the contracts?

Is it possible to do:

contract A) sends ETH -> Escrow <- contract B) sends ERC20
Escrow swaps between the two without approval?


texts: This method only supports 0x/prefixed hex


texts: Deploying smart contract programatically from web3 / nodejs

texts:
I'm building a Dapp where, whenever a user creates an account, it automatically creates an Ethereum address for the user (I'm exposing the personal module over RPC for now, but it's just for playing purposes). I now want to automatically deploy a contract when a user creates an account, ideally to make that user the only address capable of interacting with that contract.

Following some tutorials (this), I installed solc and changed my code to

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const solc = require('solc');
var fs = require('fs');
const input = fs.readFileSync('contracts/helloWorld.sol');
const output = solc.compile(input.toString(), 1);
const bytecode = output.contracts['helloWorld'].bytecode;
const abi = JSON.parse(output.contracts[':helloWorld'].interface);

This however, throws an error TypeError: Cannot read property ':helloWorld' of undefined. After some investigation, I realised the output is returning { errors: [ ':1:1: Error: Expected import directive or contract definition.\npragma solidity ^0.4.11;\n^\n' ] }

Finally, even after seeing this answer, I still can't figure out why. I paste my contract code on Remix IDE and it does not throw any error.

My contract code (the test one I'm using now) is

pragma solidity ^0.4.11;

contract helloWorld {
    /* Constructor */
    address owner;

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

    function remove() {
        if (msg.sender == owner) {
            // Suicide and send funds to owner
            selfdestruct(owner);
        }
    }

    function greet() constant returns (bytes32, address) {
        if (msg.sender == owner) {
            bytes32 hello = "hello";
            return (hello, msg.sender);
        }
    }

}

Any help would be much appreciated, been stuck for a while :)


texts: Geth windows console - get Transaction and balance problem

texts:
I have setup a geth client in windows.  By using below command I am able to run geth.

geth --rinkeby --verbosity "0" console

I created an account then pasted my public key on twitter to get funded by Faucet of Rinkeby, it was success, I can see my balance on Rinkeby web ui.

But when I send query about my balance from geth win cli, it is still 0. getTransactionCount() is also 0.

when I do eth.syncing this is the output:

{
  currentBlock: 791043,
  highestBlock: 1772520,
  knownStates: 1607660,
  pulledStates: 1599109,
  startingBlock: 35346
}

According to Rinkeby web ui my transaction  is in 1772468 th block

So why I can't see my balance, what does currentBlock mean in syncing function? Does that means my node hasn't synced with the blocks between current and highest block and behaves according to state at current block?

Confused.

Thanks


texts: Ethereum Address genration gives new address and new private key everytime in Android

texts:
I am using 'org.ethereum:geth:1.6.5' dependency.
I am trying to follow github code of
https://github.com/ethmobile/ethdroid .I found it gives every time new private and address.
I want to have same private key and address when user add same phrase or seed in any device.It should create same wallet based on same phrase (or passowrd).

I tried to create ECKey by adding same SecureRandom object and Provider object everytime.Yet it gives new private key.
Is there any way to fullfil this requirements?

My code is:

           String TAG = "MainActivity >";
    SecureRandom secureRandom = new SecureRandom();
    TextView tv;
    Provider provider =  SpongyCastleProvider.getInstance();
    MainActivity activity = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
 String stringToConvert = "strategy";
            byte[] theByteArray = stringToConvert.getBytes();

 secureRandom =  SecureRandom.getInstance("SHA1PRNG").setSeed(theByteArray);

  tv = (TextView)findViewById(R.id.tv);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getAddress();
                 //   Account();
                }
            });

}

    private void getAddress(){

        try {

            ECKey eck = new ECKey(provider , secureRandom);
            //new ECKey(Security.getProvider("EC"), new SecureRandom());
            Log.i(TAG , "Private key: " + Hex.toHexString(eck.getPrivKeyBytes()));
            Log.i(TAG , "Public key: " + Hex.toHexString(eck.getPubKey()));
            Log.i(TAG , "Address: " + ("0x" + Hex.toHexString(ECKey.computeAddress(eck.getPubKey()))));

            tv.setText(("0x" + Hex.toHexString(ECKey.computeAddress(eck.getPubKey()))));

        } catch (Exception e) {
            Log.e(TAG + "Exception = ", e.toString());
            e.printStackTrace();
        }

    }


texts: How to check Balance of a specific account (MetaCoin)

texts:
I'm fairly new to programing and solidity, still on the learning curve of things here.... So right now I'm trying to check for the balance in Wei of the account I submit into the text field (Account). How do I achieve this functionality?

My html code for this in index.html is;

Check

Account:<input type="text" id="acctAddress" placeholder="e.g., 0x93e66d9baea28c17d9fc393b53e3fbdd76899dae"></input>

<button id="check" onclick="checkBalance()">Check Balance</button>

You have  META

The Metacoin Solidity in MetaCoin.sol function is;

function checkBalance(address _account) returns (uint balance) {
        return balances[_account];
    }

The JavaScript function in app.js is

function checkBalance() {

    var acctAddress = document.getElementById("acctAddress").value;
    var check_element = document.getElementById("acctBalance");

    setStatus("Retreving Balance... (please wait)");

    web3.eth.getBalance(acctadd)

      acctAddress = acctadd;

    }

};


texts: How to detect a consensus is BFT or not?

texts:
Can we divide consensus algorithms into BFT (Byzantine Fault
Tolerant) and non-BFT ?
If so, How to detect a consensus is BFT or non-BFT ?
Is there any non-BFT consensus algorithm example ?


texts: How to call function from SmartContract?

texts:
I have a smart contract deployed having the following function.

function getTime() public view returns (uint){
       return now;
   }

However, when I try to call the function like this. ("einstance" being the instance of the contract):

tme=einstance.functions.getTime()
tme

I receive:

<Function getTime() bound to ()>

How can I retrieve the time from this?


texts:
Hi im new on the blockchain, so i have a specific question :
I did a withdraw from EtherDelta and they send me an "internal transaction", so i cant see the new balance on my wallet..
Someone can explain me where are my ether ?
Why they cant do normal transaction ?
Thanks for the answer

Tx : https://etherscan.io/tx/0xce5d12239074fc77229f869cc558fe542a29714f15e535eb13d3b70efecf9d19


texts: Why does a contract method that only returns a value doesn't use a constant and cost gas?

texts:
I've set up a Truffle sample project, which contains the following contract with the last method added for demonstration purposes (see logs below):

pragma solidity ^0.4.4;

import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
  mapping (address => uint) balances;

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

  function MetaCoin() {
    balances[tx.origin] = 10000;
  }

  function sendCoin(address receiver, uint amount) returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    Transfer(msg.sender, receiver, amount);
    return true;
  }

  function getBalanceInEth(address addr) returns(uint){
    return ConvertLib.convert(getBalance(addr),2);
  }

  function getBalance(address addr) returns(uint) {
    return balances[addr];
  }

  function getBalanceWithConstant(address addr) constant returns(uint) {
    return balances[addr];
  }
}

The getBalance() function only return a value and doesn't alter the state of the network. Why was there no constant used for this function in the Truffle sample code? From what I can tell looking at the logs, in its current form, it needs mining and costs gas when being called.

Update

Here's the log.

First I call the function with the constant, which just returns the value:

Home:truffle migu$ truffle console
truffle(development)> var meta;
undefined
truffle(development)> MetaCoin.deployed().then(function(instance) { meta = instance;})
undefined
truffle(development)> address = '0xf27c14a83851210c6e26502433fd8193733ace90'
'0xf27c14a83851210c6e26502433fd8193733ace90'
truffle(development)> var tx = meta.getBalanceWithConstant(address);
undefined
truffle(development)> tx
{ [String: '10000'] s: 1, e: 4, c: [ 10000 ] }

Also, the testrpc logs don't show any mining:

eth_call

Then I call the function without a constant:

truffle(development)> var tx1 = meta.getBalance(address);
undefined
truffle(development)> tx1
{ tx: '0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be',
  receipt:
   { transactionHash: '0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be',
     transactionIndex: 0,
     blockHash: '0xe12fce4f8e2b3dd8fc0ca840ab5a63e60a8c94e22ab6c5b157fc654ddf4c2f48',
     blockNumber: 6,
     gasUsed: 23146,
     cumulativeGasUsed: 23146,
     contractAddress: null,
     logs: [] },
  logs: [] }

And the testrpc logs show mining activities:

eth_sendTransaction

  Transaction: 0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be
  Gas usage: 0x5a6a
  Block Number: 0x06
  Block Time: Sun Mar 12 2017 08:07:27 GMT+1100 (AEDT)

eth_getTransactionReceipt


texts: Web3 | TransferFrom() transactions always Failed

texts:
I'm trying to send Custom ERC20 Token to Owner Wallet Address using transferFrom() function using Web3.js

However all the Transactions are failed. Which is the same problem occur on Remix IDE.
Some answers on stackOverflow here says that the approve() is needed to call first before the transferFrom() function. so, I tried on Remix frist but I got the same problem. And then tried with using Web3.js like below.

const myContract = new web3.eth.Contract(abi);
const amount = sendAmount;
let address = myAddress;
myContract.options.address = contractAddress;
myContract.options.from = TokenOwner;
let options = myContract.options;
let data1 = myContract.methods.approve(address, amount).encodeABI();
let data2 = myContract.methods.transferFrom(address, TokenOwner, amount).encodeABI();

const ethAccount = fromPrivateKey(toBuffer("0x..."));
const fromPrivateKeyBuffer = ethAccount.getPrivateKey();

web3.eth.getTransactionCount(TokenOwner, (err, count) => {
  if (err) return;

  const txData = {
    chainId: 0x03,
    gasPrice: web3.utils.toHex(42000000000),
    gasLimit: web3.utils.toHex(90000),
    to: contractAddress,
    from: TokenOwner,
    value: 0x0,
    nonce: web3.utils.toHex(count),
    data: data1
  };
  const tx = new ethTx(txData);
  tx.sign(fromPrivateKeyBuffer);
  const serializedTx = tx.serialize().toString("hex");
  if (!serializedTx) {
    return;
  } else {
    web3.eth.sendSignedTransaction(`0x${serializedTx}`, (err, MuiTXHash) => {
      console.log("err : ", err, "Data1-MuiTXHash : ", MuiTXHash);
      // START DATA2
      web3.eth.getTransactionCount(TokenOwner, (err, count) => {
        if (err) return;

        const txData2 = {
          chainId: 0x03,
          gasPrice: web3.utils.toHex(42000000000),
          gasLimit: web3.utils.toHex(90000),
          to: contarctAddress,
          from: TokenOwner,
          value: 0x0,
          nonce: web3.utils.toHex(count + 1),
          data: data2
        };
        const tx2 = new ethTx(txData2);
        tx2.sign(fromPrivateKeyBuffer);
        const serializedTx2 = tx2.serialize().toString("hex");
        if (!serializedTx2) {
          return;
        } else {
          web3.eth.sendSignedTransaction(`0x${serializedTx2}`, (err, MuiTXHash2) => {
            console.log("err : ", err, "Data2-MuiTXHash : ", MuiTXHash2);
          });
        }
      });
      // END DATA2
    });
  }
});

};

I got the two Transaction Hash return data and the TransferFrom() transaction is failed again.
What is the problem?
How can I make it success? I have to withdraw the custom ERC20 token from specific address to owner. so I have to use transferFrom() transaction.
Please let me know how to do. Thanks.


texts:
I have the following contract:

pragma solidity ^0.4.18;

contract ReferralProgram {
    // referrer => array of referrals
    mapping (address=>address[]) private referrals;

    function becomeReferral(address referrer) public {
        require(referrer != 0x0);
        referrals[referrer].push(msg.sender);
    }

    function getReferrals() public view returns (address[]) {
        return referrals[msg.sender];
    }
}

I call method becomeReferral multiple times from different accounts and specifying the same referrer address (function parameter).

Then I call getReferrals from referrer address and it returns empty array. It is possible use dynamic arrays in mappings? Documentation says:

  _ValueType can actually be any type, including mappings.

What am I doing wrong? Thanks.

P.S Testing in remix browser


texts:
Consider the following contracts

contract Victim{
//...

  function donate() public payable
  {
    credit[msg.sender] += msg.value;
  }

  function withdraw(uint amount) public {

    if (credit[msg.sender] >= amount)
    {
      (bool success, ) = msg.sender.call.value(amount)("");
      require(success);
      credit[msg.sender] -= amount;
    }
  }
//...
}

contract Attack{
  Victim victim;
//...
  function () payable {
     victim.withdraw.value(0)(balance);
  }
}
//...

My question: how do we initiate attack as an end-user?

Scenario 1. First call occurs from an EOA (say Bob), for example using a Javascript library like this attack.withdraw(1). Here, Bob calls the withdraw function and so msg.sender is Bob's EOA address (assuming Bob signs the transaction with his private key). Inside the withdraw function we transfer funds to Bob msg.sender.call.value(amount)("");. But how is Attack's fallback function called in this case if msg.sender is not a contract address?

Scenario 2. We call victim.withdraw.value(0)(balance) from inside Attack contract. This time around msg.sender is the contract's address. Inside the withdraw function there is a check if (credit[msg.sender] >= amount). So, does the Attack contract have to have nonzero balance inside the Victim contract? I cannot transfer ethers to the contract's address from truffle console: 'Error: Returned error: sender account not recognized'.


texts: Where to find the documents matching the dao proposals hash?

texts: In each proposals of the DAO there is a hash that I guess is here for us to check the proposal document matches the submission. But where to find these documents? Any official link where links to each proposal are listed? How can we vote if we can't read the original paper? Thanks.


texts: Is there a way to count empty accounts using geth ? I just want to be able to track current DDOS cleanup process.


texts: Is there a block property that is determined after the block is published?

texts: I wanted to know if is there a block property in ethereum that (is not determined) no one knows (even the miner of that block) before publishing it to the network?


texts: Is Data Stored on Ethereum encrypted or only RLP encoded? If data is not encrypted, is there some way to secure and encrypt it using AES encryption algorithm in cipher block chaining (CBC) or XTS mode with a 128-bit or 256-bit key?


texts: What is the exact issuance model for ETH?

texts:
How is the number of ETH per block determined? My initial impression was that ETH blocks produce 5 ETH per 15 seconds but I cannot find any exact numbers or methodology regarding the emission schedule.

This blog post from 2014 says 18,000,000 ETH will be produced per year, given there are 31,557,600 seconds in a year, that leaves us at 1.7532 ETH per second. Given ETH blocks are 15 seconds, that equates to 8.5616 ETH per block.

However, according to bitinfocharts.com, the reward per ETH block is a bit more complicated.

It seems that the total reward per block is split up in the following way:

Static reward (currently 3 ETH)
Transaction fees
Uncle inclusion
Uncle rewards

In which of these 4 points are new coins generated and how is that generation determined?

Why is the static reward 3 ETH (totaling ~6.3 million new ETH per year) when the original blog post and most information I'm finding on ETH claims 18 million new ETH generated per year? Is there a block halving event or some similar schedule for reducing the static reward?


texts: Basic example of interaction between 2 contracts?

texts: What is a basic example of one contract invoking a method in another (non-calling) contract? Would the address of the contract having that method always need to be hardcoded?


texts: How do I add a wallet to web3-react without using an injected browser extension?

texts: So essentially I am not using the Metamask browser extension for my usecase and instead, I'm initializing a wallet using web3.eth.accounts.wallet.add(private-key) to add the wallet. I'm also using infura to connect to the kovan test network. The codebase I'm adding to is using web3-react to manage state, but currently it discovers your wallet only if you add it through connecting it with the Metamask browser extension or any other wallet extension/login. How do I add my programmatically added wallet to my we3-react manager?


texts: Smart Contract validate the transaction sent.

texts: I was wondering how smart contract can validate the sender address.  That means the transaction is coming from the valid Ethereum address. Do we have to have any validation logic inside the contract. I know that the one who deployed the contract can be set as the owner but then how Dapp signs the transactions and smart contracts verify that it has come from the proper source.


texts:
Where I can I find a description of how geth maps Blocks, Transactions, Accounts, etc. onto a LevelDB database? I can dump the 300+ million db blocks (keys) in my local geth database but I have no idea how to parse them beyond that.

Thank you,
Michael Herman

p.s. That is, something that maps Ethereum block architecture into LevelUp constructs/API calls.


texts:
Usually, Parity logs looks like:

2016-12-04 20:56:28  Syncing #2346672 6eb0…3382      2 blk/s   25 tx/s   0 Mgas/s   13529+    0 Qed   #2360201    0/ 8/25 peers     10 MiB db    6 MiB chain   50 MiB queue    2 MiB sync
2016-12-04 20:56:33  Syncing #2346682 732e…9811      1 blk/s   18 tx/s   0 Mgas/s   13518+    0 Qed   #2360201    0/ 8/25 peers     10 MiB db    5 MiB chain   50 MiB queue    2 MiB sync
2016-12-04 20:56:38  Syncing #2346703 743c…36b1      4 blk/s   12 tx/s   0 Mgas/s   13498+    0 Qed   #2360201    0/ 8/25 peers     10 MiB db    5 MiB chain   50 MiB queue    2 MiB sync
2016-12-04 20:56:48  Syncing #2346802 baa1…2f6b      9 blk/s   30 tx/s   0 Mgas/s   13399+    0 Qed   #2360201    0/ 8/25 peers      9 MiB db    6 MiB chain   50 MiB queue    2 MiB sync

Easy to guess, that

2016-12-04 20:56:28 - timestamp

Syncing #2346802 - syncing block #...

6eb0…3382 - probably block's hash

9 blk/s - download speed, blocks per second

12 tx/s - download speed, transactions per second

Can you explain, what other columns mean?


texts: how to customize my own commands in geth console?

texts:
How to customize my own commands in geth console?

We know that in geth console, we can type eth.accounts and other commands.
I found that there is a  JavaScript parser/interpreter named Otto which does this, But how to add a new command such as eth.mycommand in geth console?

Thank you very much.


texts: How to get access to the storage array through the solidity assembler?

texts:
If the array is located in memory, then all the elements are in sequence, for example:

    uint256 arrLength = arr.length;
    assembly{
        let offset := sload(arrLength)
        res:= mload(add(arrLength,0x20)) //first element
    }

But I don’t understand how in the arrays located in the storage? the keys of the elements are generated?
How to get a pointer to an array located in storage?
How to get the value of an element knowing its index?


texts:
In Solidity, what's the difference between funtion type and funtion?
And what can they be used for and how respectively?
Thanks!


texts: What is the relationship between Gwei and gas?

texts: I know that a Gwei means 1000000000 wei, but when we send a transaction with 21000 gas, is that mean we send 21000 Gwei? please explain Gwei for me


texts:
I added the following two lines of code to my function:

uint gas_remaining = msg.gas;
//irrelevant code....
refund = refund + ((gas_remaining - msg.gas) * tx.gasprice);

For some reason this is causing the following error:

transact to browser/ballot.sol:Lottery.buyT errored: VM error: revert.
revert  The transaction has been reverted to the initial state.

Am I doing something wrong?


texts:
In a smart contract, if we make a member variable public:

Question 1: Can a malicious party write a transaction/contract and change the value/state of the public variable in the contract?

Question 2: Would the problem be solved by only turning public to private?

For instance, if in a contract we have:

address private owner;

and in the contract constructor we have:

 owner= msg.sender;

then we have a getter function like:

get_owner() returns (address){
  return ownner;

}

then nobody can change owner, but if have

address public owner;

someone may change it later on?

But if we have a getter function as above, MyEtherWallet (to interact with a contract on testrpc) does not read/return owner, unless we turn public owner to a private one.

Question 3: Why MyEtherWallet does not return a value, for the getter functions that we write?


texts:
On the homepage of eterhmine it says that one of their features is "Customizable minimum payment threshold (Standard: 1 Ether, Minimum: 0.05 Ether, Maximum: 10 Ether)" and yet everything else I'm reading about says it pays out after 1 ether.

I am new to mining and want to make sure I am doing this correctly (I'm showing ~50 MH/s so I think it's working alright, but I won't be happy until I see a non-zero ether amount in my balance!).

(1) Is there a way to change the minimum payout so that I can go from zero to non-zero on a shorter timeline?

(2) Is there any other way to see results sooner? Even if there is not a smaller payout, is there a way to see that I am X% of the way to my next ether or anything like that?

For what it's worth, I'm using Genoils miner and have followed their directions but tweaked it slightly for Ubuntu.


texts:
I will try to explain my idea.

Our server receive data to save from different servers, we call it S1, S2 and S3.

Our server uses a node script with web3.js to call function over a contract. Actually we're paying all the transactions from our wallet.

I'd like to be able to receive eth from our clients, saving into contract balance, having a balance x single address.

This is doable.

But then i'd like that our server will spend the clients's eth, not our eth, to call contract functions.

So the ultimate goal is that user will pay for what server does.

My problem is that users are not interacting with our server with a browser, so we have no metamask to pay costs.

Is there a way to addebitate to third party the fees?

We could do calls for our clients,  we anticipate costs, then call a contract function that only we can call to move a certain amount of eth from user's personal balance to our.

I imagine I can't simply move eth from other's wallet to our. So I thinked to create something like a balance per user inside contract, accept anticipated payments, and move gas from user's balance into contract balance.

I am totally sure it will be hacked in some way. I am not entirely happy.

Edit

My user should be able to send ETH to contract. This amount is sent to contract, not to contract owner
When contract receive eth from an user, the contract does something like

balance[msg.sender] += msg.value
A part the initial payment, user will NO be able to interact directly to the contract in any way.

EDIT 2 : Probably I've found a practical example

Imagine like we act as a bank.

You, the user, transfer money to your bank account. The bank, our contract, actually knows the total amount of money owned by you.

But if your bank account has enough money, the bank pays your bills.

You sent initially money into your bank account, but is the bank that spends your money without your intervention.

So sending eth to my contract, users allow me to spend what they sent.


texts: Right way/pattern for setting address of 'creator' contract on 'created' contract

texts:
ContractA   creates  multiple instances of  ContractB.
In my contract I would like to set the address of ContractA on ContractB instances but as that address (of A) is not available at the time of (B) creation, what would be the suggested pattern.

One way to do it is by making it a 2-step process #1  create the instances of ContractB in constructor #2 make a call to set the address of the contract A on instances of Contract B ... any thoughts on other ways of doing it?

// Code for illustration only
contract ContractA{
  address[] instancesOfB;

  function ContractA(){
     // create the instances of ContractB and push to instancesOfB
     ...
  }

 function updateB(){
   // loop through the array
   for(uint8 i=0; i < instancesOfB; i++) {
      instancesOfB[i].setAddressOfA(address(this));
   }
 }
}


texts: How to approach implementing a new sync mode in Geth?

texts: Has anyone ever tried implementing your own sync mode in Geth? What's the recommended flow of code change in order to implement your own sync mode?


texts: Which wallets support a multi signature transaction?

texts:
I have an address with some coins and I want to set it up as a multi-signature wallet using 2 of 3. Which wallets support this feature and is there a good tutorial for this? I want to to split control of my funds with me and 2 other friends.

When I make a transaction, do their wallets also get alerted that I made a transaction so they can approve it? Or it doesnt work like that?


texts: How to unlock account from another node in same blockchain network?

texts: I have deployed DAPP on two node private ethereum blockchain network. According to this question it is not possible to access all accounts across multiple nodes. My question is consider a scenario where a particular ethereum node crashes due to some reason. In that case all account information which is stored on that node will lost. If private keys of accounts are stored safely outside the node then can user will unlock account using his/her private key from other node?


texts: Stack to deep workaround for object " instantiation "

texts:
I'm have an object with around 25 fields in it.

int idOfObjectTracker;
mapping (uint => object)listofobjects;

struct object {
string _1;
string _2;
   ...
string _25;
}

i'm trying to " modifiy all the propreties at once.

function newObject(string _1,string _2,...){
   object o = listofobjects[idOfObjectTracker++]
   o._1 = _1;
     ....
   o._25 = _25;
}

Obviously this doesn't work and i can't seem to find a workaround since i don't want my client to provide the id so splitting creation in multiple function wouldn't work either since the id would be messed up.

How do you normally proceed in this situation ?


texts: Why does this transaction (truffle metacoin example) not require gas?

texts:
In the truffle metacoin example why does this line not require {gas: xxxx}? Is it that this transaction doesn't need gas or that truffle sets some sort of default gas?

return meta.sendCoin(receiver, amount, {from: account});


texts: I'd like to monitor the transfers of a certain ERC-20 token but so far I didn't find a way. I'm currently using web3.py. Any suggestion? Thanks


texts: How to send an ETH address from a webpage to a smart contract?

texts:
What's the best way to get an ETH address from a website form submission (php) passed to a smart contract in order that the smart contract can send some new minted Tokens to the ETH address collected in the php form?

The user submitting the ETH address on the website does not have any ETH so we will have to pay for the Gas for any transactions.

The user's ETH address submitted on the php form is different to the msg.sender address (us).

Have been considering using PHP with: https://github.com/digitaldonkey/ethereum-php

But is there an easier approach? Thank you


texts: Can I avoid out of gas errors using testrpc

texts:
I am writing a proof of concept using truffle and testrpc and I have to spend hours optimizing the code to avoid out of gas errors. Is there a way to bypass this error or have a very high value. I have tried setting high limit on testrpc

  testrpc -l 4500000000000

Tried specifying high gas in truffle.js

networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
      ,gas: 500000000
    }
  }

But still, encounter out of gas when running my tests.

Transaction: 0x0981ab4c4ebdcb851e138d7a18344d256489ef01259f6b714edefdfe23ab824c
  Contract created: 0xccb7c4bd42c1e8e809d9f4573a2c2e0590b27b78
  Gas usage: 500000000
  Block Number: 23
  Block Time: Tue Jan 16 2018 08:35:30 GMT-0800 (PST)
  Runtime Error: out of gas

If I comment out 5 lines of the code triggering events (for validation failures), it runs without any issues with the default 6.7M gas. Here are my events, I have switched to bytes32 from string.

// Used for error handling.
  event AnyException(bytes32 m);
  event AnyException(bytes32 m1, bytes32 m2);
  event AnyException(bytes32 m1, bytes32 m2, bytes32 m3);

Here is a successful transaction after commenting 5 lines generating events using default gas in truffle.js.

Transaction: 0xb9f0f703c7f7e1ae5d51fc8170c00d2f12de146c6c2d5b48a47bd2a1e2a14203
  Contract created: 0x87d84cf9d012a181658ce76fa03ab1a7bc0ad538
  Gas usage: 6227032
  Block Number: 28
  Block Time: Tue Jan 16 2018 08:51:03 GMT-0800 (PST)

How can gas usage jump so high with 5 lines of event logs?


texts: How to invoke an Ethereum function from a web server?

texts:
I have a hardware device that detects events I would like to save in the Ethereum blockchain.

So my idea is that the hardware device will call an API function in my web application (C#, node, PHP, etc.), and the web application will call using web3.js a function in my Ethereum smart contract. Everything should be done automatically without human intervention.

My solidity program is this one:

pragma solidity ^0.4.11;

contract Logs {

  struct Log {
    string user;
    uint deviceId;
    uint time;
  }

  Log[] logsList;

  function writeLog(string _user, uint _deviceId) external {
    logsList.push(Log(_user, _deviceId, now));
  }
}

I tested using testrpc and Metamask and works fine.

But I'm wondering:

How to call the writeLog function from the backend of my web application? I'm assuming that the contract has ether enough to pay for the gas.
How can I be sure that the call is done only by my backend? I don't want a malicious user to call directly the function and consume all the ether of the contract


texts: How to find out the rate of ETH in USD in the contract?

texts:
I have a function which can rate ETH in USD. How can I find out the rate of ETH in USD in automatic mode?

Can this be done in Solidty?
Or do I have to use a third-party language, for example, Javascript?

function setExchangeRate(uint value) onlyOwned {
    require(value > 0);

    ExchangeRateChanged(exchangeRate, value);
    exchangeRate = value;
  }


texts: What happens in CALL when gas is set to 0?

texts:
Reading the documentation on the CALL opcode :

"call contract at address a with input mem[in..(in+insize)) providing g gas and v wei and output area mem[out..(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success"

Where CALL is

call(g, a, v, in, insize, out, outsize)

If I test a contract which uses the transfer function and then check what happens in assembly, I see that the stack does indeed represent the right address a at the first position of the stack and the right value v at the second position of the stack. However, the 0th postion of the stack is set to 0. This would mean 0 gas is sent with this call. In transfer, 2300 gas has to be sent, but this apparently does not happen.

How does this work?

EDIT Contract code

pragma solidity ^0.4.24;
contract Transfer{
function test() public payable {msg.sender.transfer(msg.value);}
}


texts: Reduce gas costs with longer block confirmation times (like in Bitcoin)

texts:
In Bitcoin, fees tend to decrease as you target longer block confirmation times. For example, a standard transaction with 1 input and 2 outputs has a fee of  approx. $3.06 for confirmation within 6 blocks. If I target confirmation within 40 blocks the fee drops to $0.95 cents - a significant savings. If I target confirmation within 1440 blocks the fee drops further to approx. $0.48 cents.
For Ethereum I was only able to find fee estimates for 3 levels of speed - low, average high. Low speed targets confirmation within (approx.) the next 15 min, average targets confirmation within 2 min 39 sec and high targets confirmation within the next 30 seconds. The cost of each target is $1.97, $2.57 and $4.08 respectively (at the time of writing).
My question is this: Is it possible to target longer confrimation times (such as 60 min, 400 min and 24 hrs) to reduce fees even further (like we can do with Bitcoin)? If so, how can I get estimates for targeting confirmation within N blocks/minutes for Ethereum?


texts: How can I reduce the gas price for the fallback function?

texts:
Below is my fallback function for ethereum. It currently require 91000 gaslimit which is way more than 21000. Metamask always starts the transaction with 21000 gas stipend due to which transaction fails always. Is there anyway Metamask calculates the actual gas needed because I cannot tell each user individually to send 91000 gas along they will believe in gas whatever Metamask will suggest OR if we can reduce the gas price from 91000 to 21000 somehow.

function deposit() external payable {
    makeDeposit(msg.sender, msg.value);
}

function makeDeposit(address sender, uint256 amount) internal {
    require(balances[sender] == 0);
    require(amount > 0);
    balances[sender] = balances[sender].add(amount.mul(1000));                      // mint new tokens
    _totalSupply = _totalSupply.add(amount.mul(1000));                              // track the supply
    emit Transfer(address(0), sender, amount.mul(1000));                            // notify of the transfer event
    depositor[sender].time = now;
    depositor[sender].amount = amount;
    emit Deposited(sender, amount);
}


texts: In webpack App.js cannot locate css file and web3 library

texts:
I am following an online tutorial which uses truffle webpack for designing the dapp.
Inside, I have written some code for index.html and app.js which are stored in app and app/javascripts folders respectively.
When I run the local server using 'npm run dev' and inspect the HTML page in chrome I get an error which says HTML cannot find the stylesheet declared. To further test I also observed that 'app.js' could not import web3 as well.

Please suggest how can I import the CSS file and related web3 directory in app.js. For reference, I have added screenshots of HTML error and my folder structure.


texts:
This is my code

pragma solidity ^0.4.19;

contract FirstContract
{
    address creator;
    uint256 priceOfATransaction = msg.value;
    uint256 totalAmount;
    address buyer;

    function FirstContract() public
    {
        creator = msg.sender;
    }

    function perSaleDetails() public
    {
        totalAmount += priceOfATransaction;
        //=========Detail of an order==========//
        priceOfATransaction = 0;
    }

    function sellerMoneey() public returns(bool)
    {
        if(msg.sender == creator){
            if(!creator.send(totalAmount)) {
                return false;
            }
        }
    }
}

REMIX WARNING:-

  Gas requirement of function FirstContract.sellerMoneey() high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)

What do I need to modify


texts: how to add my custom token to 0x protocol in testnet/mainnet

texts:
I am new to the 0x protocol. Is it possible to add custom token using 0x Portal DApp?. Share any example or document.

I have deployed my own exchange medium. it is running in http://localhost:3001

I don't know how to add my custom token in that exchange medium


texts:
I see that there is a default gas price, but does everyone use it? Do people get away with paying much less for gas? Are there any websites that track how long transactions take at different gas prices?

Ethstats shows gas price as 1/20th of the default. Does anyone know how accurate this is as a minimum?


texts: Buying ERC20 tokens on Development stage

texts: How can we simulate buying ERC20 tokens from a contract deployed on Ropsten for Development and Testing purposes without involving real Ethers?


texts: How to get the return value of a contract from a contract call?

texts:
If a contract does returns something, (whether a string or return true/return false) how to get it’s return value ?
I mean where does the return value is stored ? Is necessary to use RETURNDATACOPY or does the value is on the stack in the case of return true/return false ? If it’s on the stack, how to know if the contract exited because of a problem in execution (like revert or out of gas) or because execution was successful at returning false ?

Of course, I’m talking while knowing the site or the type of return value so that using RETURNDATASIZE isn’t required. I don’t want a Solidity or Vyper answer, but to know how things works at the bare low‐level.


texts:
How can I use constructor in the following solidity codes.

    pragma solidity 0.4.24;

    contract owned {
        address public owner;

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

        modifier onlyOwner {
            require(msg.sender == owner);
            _;
        }

        function transferOwnership(address newOwner) onlyOwner public {
            owner = newOwner;
        }
    }
*****************************************************************

    contract TokenERC20 {
        string public name;
        string public symbol;
        uint8 public decimals = 18;
        uint256 public totalSupply;

    function TokenERC20(
            uint256 initialSupply,
            string tokenName,
            string tokenSymbol
        ) public {
            totalSupply = initialSupply * 10 ** uint256(decimals);
            balanceOf[msg.sender] = totalSupply;
            name = tokenName;
            symbol = tokenSymbol;
        }
    ****************************************************************

    contract MyAdvancedToken is TokenERC20, owned{

    function MyAdvancedToken(
            uint256 initialSupply,
            string tokenName,
            string tokenSymbol
        ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
    _____________________________________________________________

Is the following coding a right way to use constructor for the codes mentioned above?

    pragma solidity 0.4.24;

    contract owned {
        address public owner;
        address public newowner;

        event OwnershipTransferred(address indexed _from, address indexed _to);

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

        modifier onlyOwner {
            require(msg.sender == owner);
            _;
        }

        function transferOwnership(address _newowner) public onlyowner {
            newowner = _newowner;
        }
        function acceptOwnership() public {
            require(msg.sender == newowner);
            emit OwnershipTransferred(owner, newowner);
            owner = newowner;
            newowner = address(0);   //Why address 0x0 is used here??
        }
    }

    ********************************************************

    contract TokenERC20 {

        string public name;
        string public symbol;
        uint8 public decimals = 18;
        uint256 public totalSupply;

    constructor() public {

        totalSupply = 750 * 10 ** uint256(decimals);
        balanceOf[msg.sender] = totalSupply;
        name = "MyAdvancedToken";
        symbol = "MAT";

    *************************************************************

    contract MyAdvancedToken is TokenERC20, owned {

    constructor()
        TokenERC20 public {}

    ______________________________________________________________

I deeply appreciate your help.


texts: What happens if you modify the blockchain database out of band?

texts: I understand that the data in a blockchain is stored in a database. E.g., this post states that Ethereum uses LevelDb or RocksDb. I expect that normally the only access to this database is through smart contracts, but is there anything preventing someone from modifying the underlying database out of band e.g., using the APIs that come with the database? What would happen in that case? Wouldn't the changes propagate to other copies of the database? And wouldn't that amount to a hack? How is the blockchain secured from such hacks?


texts: raw_tx_demo.js of "Mastering Ethereum" : TypeError: ethTx is not a constructor

texts:
I ran raw_tx_demo.js, an example code on page 119 of "Mastering Ethereum" by Antonopoulos and Wood, but got an error message below:

$ node raw_tx_demo.js
/Users/gemcutter/raw_tx_demo.js:22
tx = new ethTx(txData);
     ^

TypeError: ethTx is not a constructor
    at Object.<anonymous> (/Users/gemcutter/raw_tx_demo.js:22:6)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

The original source code is in the link below:
https://github.com/ethereumbook/ethereumbook/blob/develop/code/web3js/raw_tx/raw_tx_demo.js

I simply copied, pasted it and executed the node command.
Could anyone let me know why this happens and how to fix this?


texts: I was told that contracts can not trade on etherdelta because they can not sign transactions, could someone clarify?


texts: SyntaxError when setting instance of deployed contract to token variable

texts:
I'm following this tutorial: https://www.youtube.com/watch?v=044h0ZI-fDI
At 22:45, the following command is run: DappToken.deployed().then(function(i){token=i;})
In the video, after this command is run, undefined shows up.
However, this is what happens to me:

My Node Version: 12.18.1
My Truffle Version: 5.1.43
I'm using Git Bash.

I also understand the tutorial was performed on older versions of Solidity, but I made the necessary changes.
Both contracts were migrated successfully (as you can see in the image).
But for some reason, the command in question doesn't work... Help?


texts: How an IERC can do transferFrom without ERC20?

texts:
I'm trying to understand the following code:
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract Recipient {
    IERC20 private _token;

    event DoneStuff(address from, address to, uint256 amount);

    constructor (address token) public {
        _token = IERC20(token);
    }

    function doStuff() external {
        address from = msg.sender;
        address to = address(this);
        uint256 amount = 1e18;

        _token.transferFrom(from, to, amount);
        emit DoneStuff(from, to, amount);
    }
}

Here, the contract imports the IERC20 which is just an interface. I'm trying to understand why the contract can execute this _token.transferFrom(from, to, amount); without having the actual transferFrom function? Because the contract just imports the interface and does not have the transferFrom function implemented.
Could you help me clear my mind?


texts: Contract won't deploy (Truffle, React + Redux Box)

texts:
I am trying to develop a smart contract that would allow for multisig actions.

So if I, for example, want to add admin to AdminStorage I will need consent of a number of admins.
It's exactly like Multisig wallet transaction confirmation, but with external contract method calls.

So I have contract AdminStorage (in contracts/storage/AdminStorage.sol). It's just a simple address storage - nothing to write home about.

But on top of that I have Multisin (in contracts/multisig) and MultisigAddAdmin (that extends Multisig). The purpose of these is to add all this multisig properties to admin addition.

There are no restrictions to the caller of AdminStorage.add yet, but it's just a test run. Soon this method will only be callable from MultisigAddAdmin.

The thing is: MultisigAddAdmin just won't deploy.
There are no errors (like "Check your gas limit" when you try to deploy and abstract contract) - nothing. Truffle runs migrations just fine and it even prints deployed address, but then I go to Truffle console and MultisigAddAdmin.isDeployed() is false. And I can't access the deployed instance from web3.js (in React app) either.

Steps to reproduce:

(You will need NodeJS 7, LATEST Truffle and testrpc)

Clone https://github.com/IsThisThePayneResidence/personal-solidity-contracts
npm install
truffle compile --all
run testrpc (to install just type npm install ethereumjs-testrpc)
truffle deploy
truffle console
(In Truffle console) MultisigAddAdmin.isDeployed()

Please, help!


texts: How to make a Solidity function require ERC20 payment

texts:
I find lots of examples for making a contract function payable with Ether and requiring specific Ether amounts. But how do I achieve the same with an ERC20 token instead of Ether?

Example: Say I have the following simple contract.

contract SaveMyNumber {

    uint storedNumber;

    function set(uint x) public {
        storedNumber = x;
    }
}

How can I make it require payment of 20 MyERC20Token to allow saving a number?

Bonus question:

Can extensions to ERC20 (like ERC827) help do this better?


texts:
A light node connect to a light  node or a full node?

when i run geth --syncmode "light",the data is just about 40M,these data is what?just header of blocks?


texts:
So I'm following a library containing the file named "ProtcolConstansts.php", there's one line confusing me
/** @var int Maximum length of transaction memo */
public const MAX_TX_MEMO_LEN = 32; // 32 bytes

What is Memo in Transaction?


texts: How does new block propagation, step by step, work in Ethereum?

texts:
I'm trying to understand how nodes propagate new valid blocks in Ethereum.

Here's my attempt at a step by step how description of the process:

1. Miner constructs a new block and starts iterating the nonce to try to match the difficulty target
2. Miner finds a nonce that meets the difficulty target
3. Miner sends the new winning block to (say) 6 peers
4. These peers validate the block
5. If the block is valid, these peers update their copy of the state and pass the block on to (say) another 6 peers. If the block is not valid, the peers ignore the block
6. This process is repeated until the new block propagates to the entire network

Is the above process roughly correct? If not, what about this process is incorrect?

Thank you!


texts: I want to make multi-node , not private network

texts:
I know how to make multi-node in private network,

but I have a question how to make a multi-node with other machines.

this picture shows independent two nodes, and you can see blank on admin.peers

my first geth

  geth --networkid 8484 --datadir test_data --port "30303" --rpc --rpcaddr 0.0.0.0 --rpcport "8545" --rpccorsdomain "*" --nodiscover  --rpcapi "db,eth,net,web3,personal,admin,miner,debug,txpool" console

my second geth

  geth --networkid 8484 --datadir test_data2 --port "30304" --rpc --rpcaddr 0.0.0.0 --rpcport "8546" --rpccorsdomain "*" --nodiscover  --rpcapi "db,eth,net,web3,personal,admin,miner,debug,txpool" console

I had a successful result on private Network, but nothing on different node
maybe, nobody has no idea but very Thank you for any answers!


texts: Ledger Wallet Node JS api signTransaction_async - implementation issue

texts:
I tried to implement the Ledger node js api (https://www.npmjs.com/package/ledgerco) in my application. The first part with getAddress_async works, but I’m stuck with the signTransaction_async. I started with the examples on the NPM site:

eth.signTransaction_async("44'/60'/0'/0", "e8018504e3b292008252089428ee52a8f3d6e5d15f8b131996950d7f296c7952872bd72a2487400080").then(function(result) {
        console.log(result);
}).fail(function(ex) {console.log(ex);});

I replaced the original derivation path "44'/60'/0'/0'/0" to "44'/60'/0'/0" and replaced the raw transaction string to my customized version (the second string with ‘()’ is for readability) :

e8068504e3b2920082520894BB9bc244D798123fDe783fCc1C72d3Bb8C18941387038d7ea4c6800080 ->

(e8) (06) 85 (04e3b29200) 82 (5208) 94 (BB9bc244D798123fDe783fCc1C72d3Bb8C189413) 87 (038d7ea4c68000) 80

Nonce: 06,
GasPrice: 4e3b29200,
Gas: 5208 (0.000441 ETH = 21000),
To address: 0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413 (example address),
Value: 038D7EA4C68000 ( 0.001 ETH),
What is the first ‘e8’?

I can run my NodeJS app successfully and get this result:

{ v: '1c',
  r: '767fd4a3083a003f2d056edd19b53aaf1a82331ef6b0bafa7e815b0c05e1e696',
  s: '3973be6e55cade0d56148e1f46faf9781c97369d376647209d2e95551f7a995f' }

Based on this output I can create this signed transaction string:

0xf86b068504e3b2920082520894BB9bc244D798123fDe783fCc1C72d3Bb8C18941387038d7ea4c680008025a0767fd4a3083a003f2d056edd19b53aaf1a82331ef6b0bafa7e815b0c05e1e696a03973be6e55cade0d56148e1f46faf9781c97369d376647209d2e95551f7a995f

What is this first part: 0xf86b,  The rest of the string I can create, based on the input above. The last part is to push it to the Ethereum blockchain, for that I use:

https://etherscan.io/pushTx

Error! Unable to broadcast Tx : {"jsonrpc":"2.0","error":{"code":-32010,"message":"Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 1441000000000000 and got: 0."},"id":1}

I have enough funds on my wallet and when I sign a transaction with my Ledger in combination with MyEtherWallet or my private Ethereum node, I can create a signed transaction and push it successful to the Ethereum blockchain.

Can someone help me to debug this issue with the raw transaction and explain the parts I mentioned above.


texts: How to send Ether programatically everyday? (Centralized)

texts:
I am new in the Ethereum programming. I am not trying to create a smart contract. I am trying to write a script on a centralized platform (Nodejs or Python or Php server or even Windows task scheduler) that automatically and daily sends the same previously determined percentage of Ethers. For example, I can program it to send 10% of Ethers to wallet A, 35% to wallet B and 55% to wallet C.

I looked at https://github.com/ethereum/go-ethereum/wiki/Sending-ether but it still requires a user to input passphrase and it assumes a lot a previous steps that are not mentioned in page. Can someone explain a step by step approach for this goal?


texts: Copying Private chain data to another private chain

texts:
I have two independent private chains running with unique genesis file each. If we use same accounts in both the chains is there a way to copy the state or data of chain 1 to chain 2.
Regards,
Manoj


texts: Transaction working in remix but not errored from dapp

texts:
I have a master contract which deploys instances of other contracts.

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract DataEntityContract {

    DataEntity DE;

    constructor(string memory _name,string[] memory _relatedEntities, string memory _date, string memory _fileName, string memory _annotations) public
    {
        DE = DataEntity(_name, 'URN', _fileName, new string[](0), _relatedEntities, 'references', _annotations, msg.sender, _date);
    }

    struct DataEntity {
        //Event notifications;
        string dataEntityName;
        string rawFileURN;
        string fileName;
        string[] nameChangeHistory;
        string[] sources;
        string references;
        string annotations;
        address createdUpdateBy;
        string when;
    }

    function editDE() public {
        DE.annotations = "edited";
    }

    function getAnnotations() public view returns(string memory) {
        return (DE.annotations);
    }

}

contract FlattenedDEC
{
    address owner;
    string public name;
    mapping (string => address) dataEntities;
    string[] public dataEntityNames;
    uint count = 0;
    uint public DataEntitiesCount = 0;
    mapping(uint => Lineage) public lineageInfo;
    mapping(uint => DE) public DataEntities;

    event DataEntityEdited(
        string name,
        string comments,
        address editedBy
    );

    constructor() public
    {
        name = "DataEntityCatalogue Master Contract";
        owner = msg.sender;
    }

    function createNewDataEntity(string memory _name, string[] memory _dataEntities, string memory _date, string memory _fileName, string memory _annotations) public returns(address _new){
        DataEntityContract instance = new DataEntityContract(_name,_dataEntities, _date, _fileName, _annotations);
        return address(instance);
    }

    function editDE(string memory _name) public{
        DataEntityContract de = DataEntityContract(dataEntities[_name]);
        de.editDE();
        emit DataEntityEdited(_name, "edited", msg.sender);
    }

Now, when I try to call the editDE method in FlattenedDEC or even in DataEntityContract from my dapp I am gettting a jsonrpc error but when I call the same from remix everything works fine.

Here is my react js code:

async editDataEntity(name){
    const web3 = window.web3;
    const networkId = await web3.eth.net.getId();
    const networkData = await FlattenedDEC.networks[networkId];
    const contract = web3.eth.Contract(FlattenedDEC.abi, networkData.address);
    contract.methods.editDE().send({from: this.state.account})
    .on('error',(error) => {
      console.log("error: ", error);
    })
    .on('transactionHash', () => {
      console.log("edited");
    });
  }

This is the error i get:

MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload
{"id":6402969023659,"jsonrpc":"2.0","params":
["0xf9010e8203dc85746a528800836170d494ca9a565e46004c9e5f9b2ac2b4ca83d61814c20180b
8a4108770750000000000000060000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000064544495
445440000000000000000000000000000000000000000000000000000822d45a0186aa938713cc78d
fe0089d896b0890ffa693ad77fe521d4d3e5e454d2fbe600a045413f6b3d94d1df175ba42e7790e99
9fe3a97a44c91451632abb02789e10612"],
"method":"eth_sendRawTransaction"}


texts: Is naked addition and subtraction safe in transfer and transferFrom?

texts:
I'm implementing my own ERC20 token and trying to figure out best practices by looking at existing implementations. I found that DAI has addition and subtraction functions that appear to prevent integer overflow in the transfer and transferFrom methods.
function add(uint x, uint y) internal pure returns (uint z) {
    require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
    require((z = x - y) <= x);
}

Whereas the Consensys reference implementation just subtracts and adds balances without performing any such check.
    balances[_to] += _value;
    balances[_from] -= _value;

My intuition is that my token doesn't need these methods, as it has a fixed supply far less than MAX_UINT256. Am I missing an attack vector? Is there a more authoritative source to copy?


texts: Metamask not connecting with my account in ganache

texts: I'm developing a project with truffle pet shop . when i connect my project to metamask using the private keys of a account , im not able to receive my account address on my code and though i connected my account to metamask my Account id shows null


texts: Web3.js enabled mobile browsers and wallets

texts: What mobile browsers or wallets there exist with proper web3.js support?


texts: Request “eth_sign” result promise never end

texts:
I have to sign a random string with my metamask. So created a js code like that:
await window.ethereum.request({
        method: "eth_sign",
        params: ["my address","My string"],
        id: "1"
    }).then(result => {
        console.log(result)
    }).catch(error => {
        alert(error.message);
    })

But i never got a response after i clicked "sign" on metamask window.
The promise is always in "pending" status.

Is it a bug or i'm doing somethings wrong ?
Thanks you !
EDIT:


texts:
In ETH system, is it possible to hide the sender address of transactions by 3th party, "zk-SNARK" or others? And if yes, any suggestions?
Thanks.


texts:
A function recives bytes as input:

function foo (bytes data)

How do I parse that into individual byte32 chunks?

function foo (bytes data) returns (bytes32[])

My goal is to understand how to handle the Token function:

receiveApproval(address from, uint256 tokens, address token, bytes data)


texts: Is it possible to insert some custom data in the DATA field of an Ethereum Transaction?

texts:
i am working on trying to get some data encoded/inserted into an ethereum transaction.

Let me describe my environment first, i am using Web3py, Ganache and Remix IDE. I am able to successfully communicate between the three as i can write python code in Jupyter Notebook which successfully interacts with the contract deployed on Remix. And i can see each and every transaction in Ganache.

Now, my task is to store some data on the Ethereum Blockchain ( not necessarily the mainnet, if it can be done on a local RPC or even a test net, it will be enough. )

I am trying to send the following Raw transaction

tx = {
    'nonce': nonce,
    'to': address,
    'value': web3.toWei(1, 'ether'),
    'gas': 2000000,
    'gasPrice': web3.toWei('10', 'wei'),
}

to my smart-contract, using

web3.eth.sendRawTransaction

however, i get the following error in web3py ( this is a huge error, but this is the part that seems pertinent, i will post whole error if you need me to. )

'message': 'VM Exception while processing transaction: revert', 'code': -32000

Then is tried to use this command

web3.eth.sendTransaction({
    'nonce': nonce,
    'to': address_of_contract,
    'value': web3.toWei(1, 'ether'),
    'gas': 2000000,
    'data' : '7b224e616d65223a202',
    'gasPrice': web3.toWei('10', 'wei'),
})

Whether i include the data field or exclude it in this command, it gives the same error;

'message': 'VM Exception while processing transaction: revert', 'code': -32000

Please help me out.

I just want to find a way to send data(some hexadecimal string or hex bytes) in a transaction.

Let me know what possibilities exist for any such functionality in Ethereum.

Thank You.

EDIT : Contract Code as requested by @iamdefinitelyhuman

pragma solidity ^0.4.17;

contract Inbox {
    string public message;
    string[] hex_storage;
    address owner;

     event printHex(string x);

    function Inbox(string initialMessage) public payable {
        owner = msg.sender;
        message = initialMessage;
    }

    modifier isOwner {
        require(msg.sender == owner);
        _;
    }

    function setMessage(string newMessage) public
    {
        message = newMessage;
    }
        function getMessage() public view returns (string)
        {
            return message;
        }

    function storeMember(string hex_data) public
    {
        hex_storage.push(hex_data);
    }

    function showMember() public
    {
        for (uint i=0; i<hex_storage.length; i++)
        {
            printHex(hex_storage[i]);
        }
    }

    function cleanOutBalance() isOwner public
    {
        uint bal = address(this).balance;
        address(owner).transfer(bal);
    }

    function displayBalance() public view returns (uint)
    {
        uint bal = address(this).balance;
        return bal;
    }

}

So i know the Contract code is not perfect, but most functions perform rudmentary stuff ( get, set, pushing data into array )

i would like to target the storeMember function with my transaction. But, from what i have learned on Solidity, is that when you invoke a smart contract function from a front-end, the transaction contains some data of the targeted function in it's data field, hence it is impossible to alter that field if i am calling a Smart Contract function from the front-end. ( please correct me if i am wrong with this concept )

Therefore, i am trying to send a custom transaction (not a raw transaction), without invoking any function, to the contract. In the hopes that it may allow me to modify the Data field without any restrictions. ( I have also tried raw transactions, but they show the same error as listed above )

Please let me know if i can take any additional steps or precautions to allow me to encode data in the Data field of the transaction.


texts:
I'm trying to use webpack in a truffle project.
I follow this guide https://github.com/ConsenSys/truffle/wiki/Using-Truffle-and-Webpack-(beta).

At point 8 in my app.js I add this line:

var TestRPC = require("ethereumjs-testrpc");
  if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
 web3 = new Web3(new web3.setProvider(TestRPC.provider()));
}

Unfortunately when i require ethereumjs-testrpc the Chrome console output: Uncaught Error: Cannot find module "fs".

I try to add in my webpack config:
node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }

with no success.

Tks for help.


texts: Is there a programmatic way of querying the blockchain for the list of deployed contracts?

texts: Do you have any suggestions on how I could query the blockchain via web3 or something so that I can get a list of deployed contracts?


texts: I want to understand whether Smart Contracts & Ethereum can be used to achieve the functionality of our current VB6 ERP application where we have concurrent users creating new transactions, editing/deleting existing transactions and have reports to view saved transactions. Can Smart Contracts/Ethereum be a platform of choice for such applications


texts:
I was able to sync a complete GETH fast node but the server crashed and the node did not work. So, now I am downloading again. But I have worries that the samething can happen again. My question is:

How do I backup my Ethereum full node? Should I use rsync to copy all the chaindata to a separate location so that if the server crashes I can use the backup chaindata again?


texts: Using Infura, how do I know the deployed contract address

texts:
I'm doing this with web3.js and infura.

Is there a way I can know the contract address?

const myContract = new web3.eth.Contract(myContractAbi);

let deploy = myContract.deploy({
  data: '0x' + myContractByteCode
  arguments: [ ]
});

// get the number of transactions sent so far so we can create a fresh nonce
web3.eth.getTransactionCount(fromAddress).then(txCount => {
  const rawTransaction = {
    nonce: web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(500000),
    gasPrice: web3.utils.toHex(gasPrice * 1e9), // gasPrice Gwei
    from: fromAddress,
    value: '0x00',
    data: deploy.encodeABI()
  };

  const privateKeyHex = new Buffer(privateKey, 'hex')
  const tx = new Tx(rawTransaction);
  tx.sign(privateKeyHex);
  const serializedTx = tx.serialize().toString('hex');

  web3.eth.sendSignedTransaction('0x' + serializedTx, (err, result) => {
    if (!err) {
      console.log(result);
    }
  });
});

console.log(result); returns TXID


texts: Check if a variable exists in external contract

texts:
kinda new to the development side of Ethereum. Been searching around for days but can't seem to find an answer for my specific case. I'm trying this challenge here.

The problem is that I can't seem to access the variable in the Stamp contract using  address(stamp).id() when trying to check if the var Id exists as I get "TypeError: Member 'id' not found or not visible after argument-dependent lookup in address."

Referencing the validator file, I can't create new contracts via the 'new' keyword to check that Id() exists as the validator is the one creating the contract at the particular address. As such, I need some way of accessing the variable of the external contract without using low level calls. This is why I haven't found answers on similar threads because in this instance, I can't modify the original Stamp or NotStamp contract.

Any pointers greatly appreciated. My attempt below. Thanks

pragma solidity ^0.5.0;

interface IStampCollector {
  function isCollected(address stamp) external returns (bool);
  function collectStamp(address stamp) external;
}

contract Stamp {   bytes32 public id;   uint public rarity;
    constructor(bytes32 _id, uint _rarity) public {
      id = _id;
      rarity = _rarity;   }
    }

contract NotStamp {   bytes32 public notId;   uint public notRarity;
    constructor(bytes32 _id, uint _rarity) public {
      notId = _id;
      notRarity = _rarity;   }
    }

contract StampCollector is IStampCollector, Stamp, NotStamp {

    bool public genuine;

    function isCollected(address stamp) public returns (bool) {
      require(address(stamp).id());
      genuine = true;
       }

      function collectStamp(address stamp) public {
       }
     }


texts: Contract refund gets "Error: invalid address"

texts:
Here is a contract I deployed on my private network:

pragma solidity ^0.4.13;

contract test {
    string stat;
    address owner;

    event statChanged(string _stat);

    function test() {
        stat = "INIT";
        owner = msg.sender;
    }

    function() payable {
        stat = "PAID";
    }

    function getStat() constant returns (string) {
        return stat;
    }

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

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

    function send2Owner() {
        owner.transfer(this.balance);
    }

    function update(string _stat) {
        stat = _stat;
        statChanged(_stat);
    }
}

I send ETH to the contract:

eth.sendTransaction({from: owner, to: contract, value: 1100000, gas: 200000, gasPrice: 1})

By running the contract .getBalance() I can see that the correct amount of ETH has arrived at the contract address, .getOwner() I can also see a good owner address too. Finally, I run .send2Owner to send the ETH back to owner:

var testContract = web3.eth.contract(...).at("...");
testContract.send2Owner();

Now I get this error:

Error: invalid address
    at web3.js:3879:15
    at web3.js:3705:20
    at web3.js:4948:28
    at map (<native code>)
    at web3.js:4947:12
    at web3.js:4973:18
    at web3.js:4998:23
    at web3.js:4061:16
    at apply (<native code>)
    at web3.js:4147:16

Why am I getting this error?


texts: Need to make a sha256 hash from two addresses

texts:
In solidity, what is the best way to combine two addresses? I cannot find a consistent pattern for doing this with the address type.

Would the recommended pattern be to convert address to string, concatenate and generate a hash?

Here's the pattern I'm attempting to achieve.

sha3(address1 + address2)


texts: Before a transferFrom, is it better to check the allowance first?

texts: transferFrom already checks the allowance, so does it make sense?


texts: How to determine wether Ether was mined or received?

texts: Is there a way to distinguish or calculate the total amount of ether which any account has received from mining and from the transfers (I mean the amount of ether transferred from other accounts)?


texts: Is there an implementation of the minimal viable plasma concept as proposed by Vitalik Buterin

texts:
Vitalik Buterin has proposed a minimal viable plasma concept at

https://ethresear.ch/t/minimal-viable-plasma/426

[Q]: is there a running implementation of this concept available?


texts:
I am working on oracles. I saw this link -
https://kndrck.co/posts/ethereum_oracles_a_simple_guide/

The code works, I tested it. But what is the issue to me, is the code actually secure? Can someone interrupt the message from the client.js to the smart contract and change the value?

There is not any TLS and no other way to confirm the correctness of the data.

This is the key js -

var OracleContract = require('./build/contracts/CMCOracle.json')
var contract = require('truffle-contract')

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


texts: Optimizing hashrate for AMD radeon RX580

texts:
hi all i am new to mining , i bought 7 of the AMD radeon RX580 GPU 8 GB, to mine ethereum , i watched some tutorials on youtube about  how to optimize BIOS for the GPU .
I followed the tutoria and i pushed the HashRate/s from 19 MH/s to 21.461 MH/s
i was expecting to push it to 30 MH/s as the reviews are saying .

i am using nanopool.org with asia server since i am in kuwait .

the miner i am using is Claymore

what i want to know is:  why the hash rate dose not went to 30 MH/s for each even i did  the right steps for BIOS optimization.
dose it depend on the pool?
or i have to do more things

TECHPOWER-z : used it to save bios for recovery and for changing .

PolarisBIOSEdetor : to change the bios memory files after copying the data for 1.750 to 1.2000. and save it .

ATI-FLASH : to load the files that we changed in the previous step .

the tutorial i followed : https://www.youtube.com/watch?v=JKM60VVIfRg .


texts: How to send Metacoins to other accounts with truffle console and testrpc local blockchain?

texts: Playing around with the default project provided by truffle. I compiled the contracts with truffle compile.Then deployed with truffle migrate and after that switched to the console via truffle console.Any idea what the command line is for sending  for instance 10 Metacoins from default account [0] to account [1]? I set the contract object as a variable with var meta = MetaCoin.deployed(). After that I tried meta.sendCoin({from:accounts[0], to:accounts[1], value: 10}) but it seems to be wrong. However I can send Ether with that command using web3.eth.sendTransaction({from:accounts[0], to:accounts[1], value: 10})


texts: How do I transfer funds to another account from a lightwallet.dat file

texts:
I have a lightwallet.dat file which I exported from ujomusic.com. It's in a different format to that used by geth. I don't expect geth will import it so can I create an account with the same number as that account, and using the private key somehow, transfer the funds to another account? This is so that I can get at the Ether in the account.

Can I retrieve the plaintext private key? If so, how do I do that?

The file looks like this:

{
    "encSeed":
{         "encStr":"U2FsdGVkX186DSL2uPp1vZO......","iv":"1cb31568e......","salt":"3a0d...."},
    "encHdRootPriv":    {"encStr":"U2FsdGVkX19FA0tZsR......","iv":"da5e226....","salt":"45034...."},
"hdIndex":1,
"encPrivKeys":{
"92f2f6b0cc1.......:{"key":"U2FsdGVkX183.....","iv":"5ec1968....","salt":"371302....."}},
"addresses":["0x92f2f6b......"],"keyHash":"f1af35a6222......",
"salt":{"words":[-918769374,1616628770,1822257817,983741528],"sigBytes":16}}


texts: I want to get about 150000 ropsten ether for testing. Is there any way to get it? I've seen some faucet websites but they have limitations.


texts:
When i try to send a lot of transaction, every block looks like only use half of its gas limit.
How can i make block to use all its gas limit until it can't handle more transaction?


texts: "TypeError" for a simple program causing failure to compile, "Type address is not implicitly convertible to expected type address payable."

texts:
This is my first contract (working from Lynda course). Even when I use the supplied code I still age this error for the following code with I try to compile:

TypeError: Type address is not implicitly convertible to expected type address payable.
    receiver = _receiver;
               ^-------^

Compilation failed. See above.

pragma solidity ^0.5.16;

contract ApprovalContract {

  address public sender;
  address payable public receiver;
  address constant public approver = 0xd268143B6FBD9BC6533F778052710C962eaAa68C;

  function ApprovalContracts() public {
    // tbd
  }

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

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

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

}


texts: For higher priority would it be a good idea to send a transaction with highest gasPrice?

texts:
I am little bit lost related to gas refund issue. On the following answer: https://ethereum.stackexchange.com/a/11017/4575
it has been mentioned that:

  However, if things do get crowded and miners do not include your
  transaction right away you can increase the gas price. This is
  analogous to a "higher priority" in other systems:
  https://stackoverflow.com/questions/33802037/in-ethereum-what-is-gas-how-is-it-used-and-what-is-the-difference-between-st.

Therefore to get a higher priority for a transaction to be mined, would it be a good idea to send a transaction with highest gasPrice (for example: myContract.hello(var, {from: web3.eth.accounts[0], gas: 99570000 , gasPrice: 50000000000 }); ), since as I understand unused gas will be automatically and immediately refunded. if the gasUsed for hello() method is 1000000, will I get refund for 50000000000 - 1000000 ? or all the gas I send via transaction will be spent?

Please note that I updated my question based on @Badr Bellaj's guidance.

Thank you for your valuable time and help.


texts: What is the easier way (no libraries, no 100KB of JavaScript) to read value from the blockchain?

texts:
I'm working on an open-source project.

I'm hesitant to include web3.js with all the code.

I just want to read a single value from the Ethereum blockchain.

That is why my requirement is to avoid 100KB libraries.


texts:
I'm not sure what changed, but with the original contract, I could not change the values of the variables.  Originally, I had tested storing values using the setSample() function a second time... then retrieving them resulted in the second storage being ignored (the variables were the same as the first time I stored them).  Now, when I store different variables under the same index (stackID) and retrieve them, it seems that I can overwrite them.  Maybe I'm missing some basic fundamental like [for example], maybe immutability doesn't apply to uints, but only addresses.  My goal here is to make sure that the values can't be overwritten, per the index (stackID) when stored via the EVM.

Below is the contract.  Also appreciate any suggestions if there's anything else I'm doing wrong, not related to this issue.

pragma solidity ^0.4.24;

contract StackSample {

    struct Sample {
        uint48 tm;
        uint56 tdn;
        uint56 ash;
        uint56 ndf;
        uint56 adf;
        uint56 cp;
        uint48 nitr;
        uint64 rfv;
        uint64 rfq;
        uint48 nel;
        uint40 grower;
    }

    mapping(uint56 => Sample) public samples;

    address public owner;

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

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    function setSample(uint56 _stackID, uint48 _tm, uint56 _tdn, uint56 _ash, uint56 _ndf, uint56 _adf, uint56 _cp, uint48 _nitr, uint64 _rfv, uint64 _rfq, uint48 _nel, uint40 _grower) onlyOwner public {

        Sample storage sample = samples[_stackID];

        sample.tm = _tm;
        sample.tdn = _tdn;
        sample.ash = _ash;
        sample.ndf = _ndf;
        sample.adf = _adf;
        sample.cp = _cp;
        sample.nitr = _nitr;
        sample.rfv = _rfv;
        sample.rfq = _rfq;
        sample.nel = _nel;
        sample.grower = _grower;
    }

    function getSample(uint56 _stackID) view public returns (uint48, uint56, uint56, uint56, uint56, uint56, uint48, uint64, uint64, uint48, uint40) {

        Sample storage sample = samples[_stackID];

        return (sample.tm, sample.tdn, sample.ash, sample.ndf, sample.adf, sample.cp, sample.nitr, sample.rfv, sample.rfq, sample.nel, sample.grower);
    }
}


texts: Difference between truffle-contract and web3.eth.Contract

texts:
maybe this is a very simple question but I've tried unsuccesfully to understand the difference between truffle-contract and web3.eth.Contract from web3.js 1.0.

As far as I've understood they seems to me two different module used for working with smart contracts' abstraction.

Am I missing something?
If they both serve the same purpose which one should I use (functionalities, easy-to-use,ecc)?

Thanks.


texts: How do I handle end-user gas cost in a DApp

texts: So let's say I have a ERC20 token and a DApp that uses said tokens as the currency. Obviously when users interact with my DApp (by sending it some amount of tokens), there will be a gas price involved. I do not want users to have to worry about keeping their wallets stocked with ETH in order to pay the transaction fees involved with using my DApp. Is there any work around for this?