texts: How to capture my emitted event value after my bet function is executed

texts:
I have this contract:
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity 0.7.4;

contract CoinFlip {
  uint public contractBalance;
  address owner;

  constructor() {
    owner = msg.sender;
    contractBalance = 0;
  }

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

  event WinOrLose(bytes4 coinSide);

  // 0 is HEADS and 1 is TAILS
  function bet(uint chosenSide) public payable {
    // Must be no less than 0.01 ETH and no more than 10 ETH in value
    require(msg.value >= 10000000000000000 && msg.value <= 10000000000000000000, "Improper amount entered.");

    // Contract must have enough funds to cover paying the bet, if won - plus some extra for gas
    contractBalance += msg.value;
    require(contractBalance >= msg.value * 2 + 100000000000000000, "Sorry, the contract cannot cover this bet.");

    uint side = block.timestamp % 2;
    bytes4 result;

    if (side == chosenSide) {
      result = "won";
      uint winnings = msg.value * 2;
      contractBalance -= winnings;
      (bool success, ) = msg.sender.call{value: winnings}("");
      require(success, "Ether send failed");
    } else {
      result = "lost";
    }
    emit WinOrLose(result);
  }

  fallback() external payable {}
  receive() external payable { contractBalance += msg.value; }

  function withdrawAll() public onlyOwner returns(uint) {
      uint toSend = address(this).balance;
      contractBalance = 0;
      (bool success, ) = msg.sender.call{value: toSend}("");
      require(success, "Ether send failed");
      return toSend;
  }

}

And this is the JS file I am using to interact with it.
var web3 = new Web3(Web3.givenProvider);
var contractInstance;

$(document).ready(function() {
    window.ethereum.enable().then(function(accounts){
      contractInstance = new web3.eth.Contract(abi, "0x6B966608067c98A74c782e521e0d4f7FEd238250", {from: accounts[0]});
      console.log(contractInstance);

    });

    $(document).on("click", "#flip_button", function() {

      var amount = $("#amount_input").val();
      if (amount < 0.1 || amount > 10) {
        alert('invalid amount submitted');
      } else {
        $("#amount_input").val(null);

      var choice = $("input[name='flipping']:checked").val();

      var config = {value: web3.utils.toWei(amount, "ether")};

      contractInstance.methods.bet(choice).send(config)
      .once('transactionHash', function(hash){ })
      .once('receipt', function(receipt){ })
      .on('confirmation', function(confNumber, receipt){ })
      .on('error', function(error){ })
      .then(function(receipt){
        contractInstance.events.WinOrLose({})
        .on('data', function(returnValues){
          console.log("Result" + returnValues.coinSide);
      });
      });

      }
    });
});

I am trying to figure out how to capture my emitted event value after the ‘methods.bet’ function is executed. Have tried several things but nothing seems to work. No error, but nothing showing in the console either.


texts: Ethminer 0.9.41-genoil-1.1.9, fails to submit Hashrate

texts:
I am new to this mining, I started yesterday with downloading the chains for geth and today it finished and so I got the newest version of ethminer. But when I start it this comes:

JSON-RPC problem. Probably couldn't connect. Retrying in 1...
  m  17:30:29|main  Getting work package...
  X  17:30:30|main  Failed to submit hashrate.
  X  17:30:30|main  Dynamic exception type: class jsonrpc::JsonRpcException
std::exception::what: Exception -32003 : Client connector error: libcurl error: 7 -> Could not connect to http://127.0.0.1:8545

I have searched in several Forums about this, but I don't know what to do?
Please help thanks! Btw. I am using the latest version of windows 10 and use a gtx 1060 3gb.
Andy


texts: How to add or modify account_signTransaction function

texts:
In this github.com/ethereum/go-ethereum/accounts/external/backend.go of Ethereum project i see the "account_signTransaction" function and i want to edit or update the logic for this function, where must i find it. i searched and not found anywhere.

Thanks so much.


texts: Deploy Imported Smart Contract in Test case

texts:
I have a project that contains a Token Smart Contract,
it has been added to my project by means of:

npm install ../token_project

In my testcase I have:

var MyToken = artifacts.require("token_project/contracts/token/MyToken");

but when I

truffle migrate

the following error happens:

Error: Could not find artifacts for token_project/contracts/token/MyToken from any sources

The file is definitely in the folder, with the correct name and constructor.
I have tried referencing it directly by specifying ../node_modules but the problem persists.
Problem also occurs on other projects like openzeppelin_solidity - I can't use anything there in my tests for the same reason.

thanks


texts:
I'm trying to implement my own version of a SmartContract-driven Discover protocol and in order to get it fully working, I want to remove the admin.addPeer() command from the console.

I know there's a way to add my own custom commands as said in here but I haven't been able to find a way to remove a command.

Even though I am confident programming in Go, I'm not so experienced in JS.


texts: what does the second address refer to in this link

texts:
What does the second address refer to in this link?

https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2&address=0x4e83362442b8d1bec281594cea3050c8eb01311c&offset=10000000000&sort=asc&apikey=YourApiKeyToken


texts: Send from Drizzle useCacheSend hook sends trasactions twice

texts:
I'm following the old documentation about hooks and I'm getting a problem at sending transactions: every transaction is sent twice, why?
The next is the current core:
<form
            onSubmit={React.useCallback(
              ({
                to = drizzleState.clientAccount,
                value = toHex(parseAmountToToken(amountToSend, tokenDecimals)),
              }) => send(to, value),
              [amountToSend]
            )}
          >
            Amount:
            <input
              type="number"
              name="value"
              onChange={(e) => setAmountToSend(e.target.value)}
            />
            <button type="submit">Send</button>
          </form>

Also TXObjects is ever undefined:
{TXObjects?.map((t) => t.status)}
.
I'm seeing the send function is calling the contract method twice for each transaction:

But I don't understand why it is happening.
Now, if i decide use cacheSend directly, i don't get duplicated transactions:
  const sendTokens = (e) => {
    e.preventDefault();
    contract.cacheSend(
      drizzleState.clientAccount,
      toHex(parseAmountToToken(amountToSend, tokenDecimals))
    );
  };

Can anyone guide me? Is this a bug?


texts: Call not working on declared variable in a contract with truffle

texts:
I have created a simple contract with Truffle to test things out. I am using testrpc with this.

pragma solidity ^0.4.11;

contract HelloSystem {

    address owner;

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

    function remove() {
        if (msg.sender == owner) {
            selfdestruct(owner);
        }
    }
}

After deploying this contract, though I can call remove from truffle console, I am not able to call the owner which is set at the initiation of contract.

Have tried:

truffle(development)> HelloSystem.deployed().then(function(instance){HS = HelloSystem.at(instance.address)})
HS.owner.call().then(console.log)
HS.owner
HS.owner.call()

I am very well able to call remove function on my contract and remove it. But owner is not working. I am sure I am missing something simple, if any one can point it out, would be much wow many thanks.

I created another simple contract with numeric uint balance and made it public.

contract helloWorld {
    uint public balance;

    function helloWorld() {
        balance = 1000;
    }
}

Now, my call to balance works fine.

truffle(development)> helloWorld.deployed().then(function(instance){HW = helloWorld.at(instance.address)})
truffle(development)> HW.balance
{ [Function]
  call: [Function],
  sendTransaction: [Function],
  request: [Function: bound ],
  estimateGas: [Function] }
truffle(development)>

Would this be because of the declaration public/ private?

Update
Inline with my argument of public declaration, I tried declaring address public owner still doesn't work. Hence open to your guys. Please help.


texts: Lets say if I want to have method in contract to show all the transactions in which one account requested to deposit tokens to another account during a certain period of time.  How can this be achieved.


texts: How to use openzeppelin contracts for a specific version

texts:
Consider me a beginner to writing smart contracts.
My question is, openzeppelin's contracts are using latest versions of solidity (by their repo). How do I use say 0.6 version, do they have it available?
This is because I'm also importing another contract which is of 0.6, so I can't use it with OpenZeppelin's contracts which are 0.8


texts: Do smart contract transactions get signed?

texts: When you send a transaction to a smart contract by using the contract.methods.methodName().send() is it signed by the sender?  If not how can I link the sender to that transaction call


texts: Returned value arent valid did it run out of gas?

texts:
After migration command line (truffle migrate --reset --network rinkeby), it is deploy. However i couldnt see at etherscan website when i enter the contract address. Should i see? Whatever then i write these comman lines respectively.

  truffle console
  Election.deployed().then(function(instance) { app = instance })
  app.address

These are fine but after this command it gives error.

  app.candidate()

Can you help me please?


texts: Solidity contract compilation on open github repository

texts:
What are the ways to check that all the .sol files in a github repository can be successfully compiled (like travis, circle etc)?

Basically I want to check that in an open repository there is no compilation error in the contracts being pushed. If contract compilation fails, PR/build fails.


texts: How do ERC721 tokens get created on private blockchain?

texts:
I'm creating a prototype using solidity for asset tracking where I need to create a new token for new items that are being added to the tracking system. I have gone through all possible tutorial on ERC721 token standard so far.

I need a very basic sample that can explain how tokens get created.
Can tokens be created on demand or do we have to create an initial
set of tokens when the contract is deployed? Thanks!


texts:
I am working on a smart contract and thinking about future scope of the coin so I would like to ask.
Is there any testing exchange available to test smart contact from rinkeby test network?


texts:
In pub-sub scenario there can be a need when one contract would like to notify all listeners about some fact. It may also contain enough ethers for gas as listeners, during registration, sends some up front.

Can one smart contract easily call (notify) all registered listeners? Or are there some limitations or maybe even that kind of behaviour is impossible in Ethereum's smart contracts?


texts: Invalid number of arguments in Solidity function

texts:
Why am I getting Uncaught (in promise) Error: Invalid number of arguments to Solidity function

sol file:

uint id  = 1;
    struct Multihash {
        bytes32 digest;
        uint8 hashFunction;
        uint8 size;
    }
    mapping (uint => Multihash) private ipfsHashes;

    function addFile(bytes32 _digest, uint8 _hashFunction, uint8 _size) external {
        Multihash memory entry = Multihash(_digest, _hashFunction, _size);
        ipfsHashes[id] = entry;
        id = id + 1;
    }

calling the function is js:

storageInstance
        .addFile(digest, hashFunction, size,{ from: account })
        .then(() => {
        });


texts:
Is it possible to define a smart contract at a predictable address?
0xf0 CREATE in the Yellow Paper suggests that the address is deterministically determined by

  x = A(Ia, σ[Ia]n)

page 29 of http://gavwood.com/paper.pdf


texts: Executing custom JavaScript Snippets through Non-Interactive console (geth --exec)

texts:
I have a JavaScript snippet to get the latest transaction to/from an account. After starting the geth instance, I did this in the interactive JS console:

  jsFunction is a function in filename.js

>loadScript("/path/to/file/filename.js")
true
>jsFunction(<parameters>)
<Returns the results as expected>

But when I try to do the same using the Non-interactive mode, it fails:

$ geth --exec 'loadScript("/path/to/file/filename.js")' attach ipc:/path/to/ipc
true
$ geth --exec 'jsFunction(<parameters>)' attach ipc:/path/to/ipc
ReferenceError: 'jsFunction' is not defined
    at <anonymous>:1:1

I ran the same command (geth --exec) with normal web3.js functions like eth.getTransaction, eth.getBlock and it works fine. I don't understand what's wrong with executing custom scripts. Does geth client support this functionality? Am I missing something?

P.S: I am running a private blockchain but didn't mention --datadir, --networkid, and --genesis etc. in the above commands for readability.


texts: Can a antminer s9 give me a hashrate of 13.5 TH/s even for a few seconds which trying to mine etherium. Albiet electronically, SHA256 computation of ASIC cannot be used for dagger-hashimoto but can it mine even for a few seconds?


texts:
I just coded ether transfer function using REMIX IDE on Ropsten testnet.
It has only two functions that setting receiver address and amount of ether and sending ether to receiver address.

After I deploy the contract and run the "transfer" function, it shows me error like below.

  Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
  Error: gas required exceeds allowance or always failing transaction at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:1401895 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:931969 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:350331 at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:368562) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353161 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:350331 at c (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353437) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353475 at Ht (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:362844) at Object. (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353564) at e.value (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:932884) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:932451 at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:368506) at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:368584) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353161 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:932417 at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:368506) at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:368584) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353161 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:932790 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353971 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:350331 at c (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353437) at s (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353359) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353161 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:353951 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:932672 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:931109 at i (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:1070338)

And my code is this.

pragma solidity ^0.4.16;

contract test {

    address public receiver;
    uint public amount;

    function test(address _receiver, uint _amount) public {
        receiver = _receiver;
        amount = _amount;
    }

    function () public {
        receiver.transfer(amount);
        }
}

please help me.

Thanks.


texts: How will blockchain handle cloned nodes?

texts:
What happens if a server contain fully synced ethereum node is clone and started, how will the blockchain handle cloned instances ?

Cloning the OS disk image, and running it on a different physical server, and maybe different network. assuming we are using go geth in full syncing mode.


texts:
when I am trying to run this command on geth console.it give an error.how to run this command on geth console.

run geth with this commnad

 geth --port 5000 --networkid 58342  --datadir="" --rpc --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3" --testnet

  web3.eth.accounts.create();
  TypeError: 'create' is not a function
      at :1:1


texts: I have several questions all revolving around one core concept: how an Ethereum account relates to a given coin (blockchain). For example, if I have an account I made to mine ETH, how does it know that the Ether on my account is ETH and not say ETC or any other Ethash based coin? I don't recall anything in the setup process where I told it which coin I wanted to mine, it just seemed to presume ETH. Say I wanted to branch out and mine some ETC and maybe Musicoin. Would I need a separate account for each of these? Or is it that each blockchain keeps my address in its own ledger? My question then would be that if I query my account balance in geth, which blockchain is it going to look up on? I can't seem to find any solid answers to this on Google, so any help would be greatly appreciated!


texts:
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }

What do these functions do?
Source: https://github.com/Dexaran/ERC223-token-standard/blob/master/SafeMath.sol


texts: Geth: what does "commit new work on block" exactly mean?

texts:
First intuition was that it signals that there are transactions to be mined, but even without a tx on a private net sometimes I see it three times per block

I0604 10:00:49.877830 miner/worker.go:337]   Mined stale block (#233 / 52f98d53).
I0604 10:00:49.898013 miner/worker.go:555] commit new work on block 234 with 0 txs & 2 uncles. Took 357.428µs
I0604 10:00:49.909992 miner/worker.go:555] commit new work on block 234 with 0 txs & 2 uncles. Took 334.166µs
I0604 10:00:49.960199 miner/worker.go:555] commit new work on block 234 with 0 txs & 2 uncles. Took 337.558µs


texts: How to build a contact that allow rating?

texts: If I have a contract that has a list of sellers, how would I code a simple contract that if some condition applies, the contract in an automatic way will increase the reputation/rating of the sender ??


texts: how to pass fix size array via interface in solidity 0.4.25

texts:
I used the following code
interface test{
  function testfunction(uint[20] memory P, uint[20] memory Q) external returns(uint,bool,uint);
}

It gives the error Location has to be calldata for external functions (remove the "memory" or "storage" keyword)
and when I changes it to
interface test{
  function testfunction(uint[20] calldata P, uint[20] memory Q) calldata returns(uint,bool,uint);
}

It gives error Expected ',' but got identifier function , so what is the correct way declare this in interface, and also how to call that function from inside a function of same contract. please reply for the same solidity version.


texts:
ive been trying for days to create a contract and simply call a function on it. Just to learn. But i can for the love of god not figure out what im doing wrong.
I got truffle and Ganache set up, and i can connect to each. But i can never fire of a contract.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <title>title</title>
  </head>
  <body>
      <script>
    window.addEventListener('load', async () => {
        // Modern dapp browsers...
        if (window.ethereum) {
          window.web3 = new Web3(ethereum);
          try {
            // Request account access if needed
            await ethereum.enable();
            // Acccounts now exposed
            web3.eth.sendTransaction({/* ... */});
          } catch (error) {
            // User denied account access...
          }
          console.log("matamask wie");
        }
        // Legacy dapp browsers...
        else if (window.web3) {
          window.web3 = new Web3(web3.currentProvider);
          // Acccounts always exposed
          web3.eth.sendTransaction({/* ... */});
        }
        // Non-dapp browsers...
        else {
          console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
        }
        startapp();
      });
      </script>
      <script>
     function startapp() {
var address = "0xA2B5f586B69f8d82a18CC5a453174E9F90eD6520";
var abi = [
    {
      "constant": false,
      "inputs": [
        {
          "name": "x",
          "type": "uint256"
        }
      ],
      "name": "set",
      "outputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [],
      "name": "get",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }
  ];
var SimpleStorage = new web3.eth.contract(abi, address);

SimpleStorage.methods.get().call()
.then(console.log);
     };
      </script>
  </body>
</html>

and my simple solidity code

    pragma solidity 0.5.8;
contract SimpleStorage {
    uint storedData;

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

    function get() public view returns (uint) {
        return storedData;
    }
}

Please help me fire of a smart contract function. Im very frustrated right now!!!!


texts: Why does some of the DAPP uses PHP and how would they do so?

texts: I always wonder how come many DAPPS uses PHP extension at the end of the filename and how did they do so ?? There is slighlty possibility that they are using the Web3PHP library to interact with the Smart contract..if this is the case, then why are they using web3Js as well...It makes no sense to use both of the libraries..Do they use both centralized and decentralized approach for Dapps?? How do they use PHP with DAPPS..???


texts: The meaning/specification of "config" in genesis.json

texts:
As I tried to search from Google, there are some genesis.json example files to customize the parameter of genesis block in Ethereum private blockchain.

In the file, there is a part called "config"

"config": {
    "chainId": 1,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
}

What is the meaning or specification for those parameter in "config"?
May I setup part of parameter(s) only if necessary?


texts: Getting return values from constant functions with signed transactions using web3 @1.0.27

texts:
I have a setup where no accounts exist on a local node and communication with contracts is done by creating raw transactions with Web3 (signed in code and not by user or node).

On the contracts there are permissioned constant getter functions. EG

function getSomething() public onlyOwner constant returns(bool) {
    return something;
}

I understand it is easy to use contract.methods.getSomething.call() with Web3 but that would require an unlocked account on the local node.

It is also possible to make "calls" with web3.eth.call(obj) but only with raw unsigned transactions.

How would I make a call with a signed transaction?


texts: How Tornado Cash Relayer trustless protocol works?

texts:
As anyone can see by the official GitHub repo, to became a Tornado Cash relayer, you need to install a node waiting for ZK Notes of the users. The node will provide them money they want to reclaim, keeping a fee.
Does anyone know how the workflow of this procedure exactly works?
Documentation says you need to host your relayer node then provide some information opening an Issue in the Tornado repo and they accept you.
But what is the security protocol?
What if, for example, I were accepted as a relayer node, then change my software with a malicious one that steals all the money from the users' notes?
I am extremely sure that this cannot happen, can anyone provide a technical explanation of why?


texts: There are some older projects, dated back to 2014 which develop contracts in CLL, C-Like Language. What is this and is this still being developed/used?


texts:
My solidity function is returning a bytes32[] which I am looping in Javascript and converting to string using web3.toAscii(). Printing this in console shows extra � characters at the end as shown below

The function returning bytes32

function myBets() public view returns (uint[] memory, bytes32[] memory, bytes32[] memory, int[] memory){
    uint n = betterCacheData[msg.sender].length;

    uint[] memory betValues = new uint[](n);
    bytes32[] memory options = new bytes32[](n);
    bytes32[] memory winStatus = new bytes32[](n);
    int[] memory moneyLineValues = new int[](n);

    for(uint i=0; i<n; i++){
        uint betId = betterCacheData[msg.sender][i].betId;
        uint optionId = betterCacheData[msg.sender][i].optionId;

        betValues[i] = betterCacheData[msg.sender][i].betValue;
        options[i] = bets[betId].moneyLineData[optionId].option;

        if(bets[betId].betStatus == BetStatus.Open || bets[betId].betStatus == BetStatus.Closed){
            winStatus[i] = "pending";
        } else{
            if(bets[betId].correctChoice == optionId){
                winStatus[i] = "won";
                moneyLineValues[i] = bets[betId].moneyLineData[optionId].value;
            } else{
                winStatus[i] = "lost";
            }
        }
    }
    return (betValues, options, winStatus, moneyLineValues);
}

Any help would be greatly appreciated! Thank you!


texts: Reading bytes from bytes32 returns zero value (except first one)

texts:
Why always when I read some bytes from bytes32 only first read return a value, all following will return zeros? 0x00

bytes32 proof = 0x999e7640514e578f5b9b416469d270d559ad4186ef63da6cd63751373512735e;

bytes1(poof[0]); // some real value, e.g. 0xf2
bytes1(poof[1]); // all following are zeros, e.g. 0x00
bytes1(poof[2]); // all following are zeros, e.g. 0x00

No matter from which index I'm started. Solidity docs says per-byte [] is read only, so what is explanation for such output?


texts: my dapp works perfect on local but when i upload to server the address returns null using web3

texts:
I have a project which I've been working on and so far it works perfectly on local. But when I uploaded the project to the server it is unable to get address using web3.

const network = await web3.eth.net.getNetworkType();
console.log(network)

This returns ropsten so I know its connected to the correct network too.
Have anyone faced similar issues?

const accounts = await web3.eth.getAccounts()

This line of code returns the address on local but returns nothing on server.


texts: When should we call( ), watch( ) or get ( ) an event? which is the fastest way to get your data from the smart contract?

texts:
Q1. I find this concept to be very confusing, when should I be using watch, call or get to listen to an event? how are they different and when should they be used?

Also,

var event1 = newInst.getSupplier({'OwnAdd': someaddr},{fromBlock:'latest, toBlock:'pending'}, function(error, result) {
    console.log("listening bro1");
    if (!error)
        console.log(result.args);
});

It returns me the structure twice.

{OwnAdd: "0xfd4e38348590a41e91b5ee57b69b99e746783990", _NameoProd: "lime", _QuantityoProd: BigNumber, _MnfofProd: "Done", _toSrv: "Meh", …}OwnAdd: "0xfd4e38348590a41e91b5ee57b69b99e746783990"_MnfofProd: "Done"_NameoProd: "lime"_QuantityoProd: BigNumber {s: 1, e: 1, c: Array(1)}_comments: "Bajaj"_status: "Saul "_toSrv: "Meh"__proto__: Object
eventwatcher.html:327 listening bro1
eventwatcher.html:329 {OwnAdd: "0xfd4e38348590a41e91b5ee57b69b99e746783990", _NameoProd: "lime", _QuantityoProd: BigNumber, _MnfofProd: "Done", _toSrv: "Meh", …}OwnAdd: "0xfd4e38348590a41e91b5ee57b69b99e746783990"_MnfofProd: "Done"_NameoProd: "lime"_QuantityoProd: BigNumber {s: 1, e: 1, c: Array(1)}_comments: "Bajaj"_status: "Saul "_toSrv: "Meh"__proto__: Object

Q2. I can't figure out why it sends me twice, can anyone figure this out?
Note: I am just trying to get the pending data and not all the records with the above event

Smart Contract:

pragma solidity ^0.4.20;

contract Supplier{
    struct supply{
        string NameoProd;
        uint QuantityoProd;
        string MnfofProd;
        string toSrv;
        string stat;
        string comments;
    }
    uint SaleID=100000;
    mapping (uint=>supply) fmr;
    event getSupplier( address indexed OwnAdd, string _NameoProd,
        uint _QuantityoProd,
        string _MnfofProd,
        string _toSrv,
        string _status,
        string _comments);

    function setSupply(string _NameoProd,
        uint _QuantityoProd,
        string _MnfofProd,
        string _toSrv,
        string _status,
        string _comments) public{
        address snd = msg.sender;
        fmr[SaleID]=supply(_NameoProd,_QuantityoProd,_MnfofProd,_toSrv,_status,_comments);
        emit getSupplier(snd, _NameoProd,_QuantityoProd,_MnfofProd,_toSrv,_status,_comments);
        SaleID++;
    }
  function getSomething(uint ID) public view returns (string , uint  , string , string , string ,
    string  ){
        supply a=fmr[ID];
       return (a.NameoProd, a.QuantityoProd, a.MnfofProd, a.toSrv, a.stat, a.comments);
    }
    function update(uint ID, string rpf) public {
        supply b =fmr[ID];
        b.stat=rpf;
        fmr[ID]=b;
        emit getSupplier(msg.sender, b.NameoProd,b.QuantityoProd,b.MnfofProd,b.toSrv,b.stat,b.comments);
    }

    }

Q3. To get values back to a UI is it more feasible to get the data ID by ID or is it better to use events (what I am trying to achieve now). If I use events then when I call update I will get all the records from the events on page reload. I will have the old records as well as new record for that SupplyID. I can write a filter on the Dapp but can something else be done?


texts: Unable to Generate Same Account from MetaMask Mnemonic in EthereumJSWallet

texts:
I've been unable to generate the Account I see in MetaMask in EthereumJSWallet even if I use the same mnemonic.

Due to the lack of documentation, I may be misunderstanding how to do so.
I have run the following 2 code-blocks in a Truffle Node console in my Terminal but I never got the correct result.

The variable mnemonic holds my MetaMask 12 word string. Per the HD Wallet API section of the EthereumJSWallet docs, I should "use bip39 to create [a seed] from a BIP39 mnemonic." However, I'm still unable to generate the appropriate account.

Neither wallet_test nor any of the derived paths in either of the 2 code-snippets below correspond to my first account.

Attempt 1:

var seed = bip39.mnemonicToSeed(mnemonic)
var wallet_test = hdkey.fromMasterSeed(seed)
wallet_test.derivePath("m/44'/60'/0'/0/0")
wallet_test.derivePath("m/44'/60'/0'/0")

Attempt 2:

var seed = bip39.mnemonicToSeedHex(mnemonic)
var wallet_test = hdkey.fromMasterSeed(seed)
wallet_test.derivePath("m/44'/60'/0'/0/0")
wallet_test.derivePath("m/44'/60'/0'/0")

Any help please?


texts: MetaMask doesn't support synchronous methods like eth_sendTransaction

texts:
I'm trying to call a function in my smart contract and keep getting the error Uncaught Error: The MetaMask Web3 object does not support synchronous methods like eth_sendTransaction without a callback parameter I understand that I need to make the call asynchronous but am unsure how I would do this. My code is:

   mainEvent.watch(function(error, result){
        if (!error)
            {
                $("#instructor").html(result.args.addr);
                console.log(result)
            } else {
                console.log(error);
            }
    });

   $("#button").click(function() {
       console.log(Raffle.main());
   });


texts:
I'd like to understand how uncles reward is calculated.

https://ropsten.etherscan.io/block/4447

https://ropsten.etherscan.io/block/2560

We have two calculated blocks, both of them have 2 uncles, but one block has 8.125 Ether, which other has 6.25 Ether. What have I missed?


texts: Programmatically saving the contract address of a submitted contract

texts:
I understand how the below web3js code block works, adapted from here:

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

But how does one save the contract address programmatically? One could, I suppose, open a file and persist it within the callback, but not that. =:)

And I don't believe the myContractReturned identifier helps us; given the asynchronous nature of JavaScript (not to mention the mining delay). How does one even use that?

It's kind of an academic question (because there's no guarantee an address will even be generated), but curious as to what friends in the community have done (or thought). Thank you!

--

var myContractReturned = MyContract.new(param1,param2, {
   from:mySenderAddress,
   data:bytecode,
   gas:gasEstimate},
   function(error, myContract){
     if(!error) {
        if(!myContract.address) {
            // Step-1: Runs on contract submission/deployment.
            console.log(myContract.transactionHash)
        }
        else {
            // Step-2: Runs after contract is deployed.
            console.log(myContract.address)
        }

     }
  });


texts: I sent a token to a contract address by mistake. can I recover, and how to recover if I can

texts:
I sent some CryptoPunk Tokens to it's contract address, while I was traying to move it to my trust wallet from coinbase wallet. Here is the details of the transaction https://etherscan.io/tx/0xa38b182326b723814cdd86204a6a6aea0fe82a59995a736572d1eb716c917815
Is there a way to recover? If it is how can I do it? I have tried looking into the website of the token, but it does not have any contact email. How can one contact these token creators? here is a link to the token website https://www.app.unic.ly/#/utoken-contract/0x8d2bffcbb19ff14a698c424fbcdcfd17aab9b905


texts: Have I accidently created multiple Ethereum accounts?

texts:
I am brand new to Ethereum. I am reading up on the basics on https://ethereum.org. I am still a little confused about the differences between a wallet and an "account." According to this page https://ethereum.org/en/wallets/ a wallet is just a way of interacting with my Ethereum account, and that I can "...swap wallet providers at any time."
But where do I create this Ethereum account? I have installed several wallets. Coinbase, Exodus, and Trust. And in those apps I have an Ethereum address (the long hex string), but they are all different.
I expected to go somewhere and create one Ethereum account, and then access that account using different wallet applications. But that doesn't appear to be how it works.
Have I created 3 different "Ethereum accounts?" I haven't deposited any Ether or any other crypto in any to any of these addresses. So if I did create 3 different accounts I guess its no big deal. Do I just need to pick one and use that for my "main" account?
Obviously I am misunderstanding the fundamentals here. Thanks for any help.


texts: How can I sign by privatekey1 but sendrawtransaction by privatekey2?

texts: Whether I can sign the tx by private key 1 but I use private key 2 to sendrawtransaction, any sample code for this? Thanks.


texts: Geth: pipe is being closed (if Mist is up)

texts:
When I run Geth it seems to work fine:

"C:\users\john\appdata\roaming\mist\binaries\geth\unpacked\geth.exe"  --datadir=h:\Backup\Wallets\eth_real_data  --syncmode="light"

Then I start Mist (both Geth and Mist are the last ones, Geth is fully synchronized). And as soon as a new data arrives in Mist, I get,

  "The pipe is being closed"

and Mist jumps to its main page from where ever it was (say, in Contract Editor):

INFO [11-12|15:23:43] Imported new block headers               count=2    elapsed=14.000ms  number=4538687 hash=b6ce45:40ca0e ignored=0
INFO [11-12|15:24:57] Imported new block headers               count=2    elapsed=7.000ms   number=4538689 hash=cb6966:80abf7 ignored=0
INFO [11-12|15:25:42] Imported new block headers               count=2    elapsed=11.000ms  number=4538691 hash=a46dad:d04ab7 ignored=0
INFO [11-12|15:26:00] Imported new block headers               count=2    elapsed=6.000ms   number=4538693 hash=7667a7:3e6a94 ignored=0
ERROR[11-12|15:26:01] The pipe is being closed.

INFO [11-12|15:26:20] Imported new block headers               count=2    elapsed=6.000ms   number=4538695 hash=254aa0:66faf7 ignored=0
ERROR[11-12|15:26:20] The pipe is being closed.

Any suggestions?


texts: How to get the Total Number of Tokenholders of ERC20 tokens?

texts: Is there any simple API or datafeeds where I can just get the total number of tokenholders of ERC20 tokens?


texts: Setting the sale period in the ICO contract

texts:
Now I'm creating an ICO contract according to the ERC standard and I need to create several sales periods. For example.
The first period. Duration - 2 weeks. The cost of the token is (N) ETH.
The second period. 3 days. The cost of the token N ether. Etc.
How can this be done? Or give a link to a ready-made contract. Thanks.


texts:
Does anyone here know about an available markdown syntax highlighter for Solidity?

Pygments & PrismJS do not include Solidity, Vyper..

What does ethereum.org uses for its docs?


texts: Smart Contract as Part of Consensus Layer | Consensus enforced by Smart Contract

texts:
Often, consensus (POS/POW,PBFT,IBFT) is not associated with smart contract. but smart contract can also be further used enforce consensus as well?

Perhaps to further breakdown consensus, there is business consensus (Smart Contract Enforced) and technical consensus (E.g. no two similar transaction in a similar block)?


texts: How long does an ether transaction take until verification (and where do I get this data?)

texts:
I am wondering if data is stored in the ETH blockchain on the time the transaction got send to the mempool such that I can deduce the time until it got included in a public afterwards (not to be confused with the average time until a new block is mined as not every transaction gets included in the subsequent block directly).

I find related data for BTC but not for ETH...any idea?


texts:
Does anyone know why the below occur.

Command: truffle migrate --reset

Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: invalid JUMP at 77d169e30e9d6e6f0835f612842170d5645160866ff64a47ea0dcca21134db9e/fef606469abd03c7e72bf6cbf8fe9816506af31b:56
at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/node_modules/ether-pudding/node_modules/web3/lib/web3/errors.js:35:16)
    at /usr/local/lib/node_modules/truffle/node_modules/ether-pudding/node_modules/web3/lib/web3/requestmanager.js:86:36
    at request.onreadystatechange (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:114:13)
    at dispatchEvent (/usr/local/lib/node_modules/truffle/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:591:25)
    at setState (/usr/local/lib/node_modules/truffle/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:610:14)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:447:13)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

Contract: https://gist.github.com/ViswanathL/9289c8e00d370d19d2b4534fa743a342


texts: Gas limit exceeded despite function not being complex

texts:
I am writing a function which takes in a bytes32 message and validates it against a signature (this is done without hashing to save gas). I am able to call the recover function and have it execute but I am getting a gas limit on the DeliveryVsPayment method despite it not being much more computation than recover itself. Why is this?

//buyer pays all the fees, seller doesn't even need to have ether to do trade
function deliveryVSpayment(bytes32 offer, uint8 v, bytes32 r,
    bytes32 s) public payable returns(bool)
{
    var (seller, quantity, price) = recover(offer, v, r, s);

    bool agreementIsValid = balances[seller] >= quantity;
    if(agreementIsValid && msg.value > uint(price) * uint(quantity))
    {
        //send over ether and tokens
        balances[msg.sender] += uint(quantity);
        balances[seller] -= uint(quantity);
        uint commission = (msg.value / 100) * transferFee;
        uint sellerAmt = msg.value - commission;
        seller.transfer(sellerAmt);
        admin.transfer(commission);
        numOfTransfers++;
        return true;
    }
    else revert();
}

// to test: suppose the offer is to sell 2 tickets at 0.102ETH
// which is 0x16A6075A7170000 WEI
// the parameters are:
// "0x000000000000000000000000000000000000000000000000016a6075a7170002", 27, "0x0071d8bc2f3c9b8102bc03660d525ab872070eb036cd75f0c503bdba8a9406d8","0xb1649086e9df334e9831dc7d57cb61808f7c07d1422ef150a43f9df92c48665c"  */

function recover(bytes32 offer, uint8 v, bytes32 r, bytes32 s) public pure
    returns (address seller, uint16 quantity, uint256 price) {
    quantity = uint16(offer & 0xffff);
    price = uint256(offer >> 16 << 16);
    seller = ecrecover(offer, v, r, s);
}

Remix gives the following error on each call and I noticed that my transaction fails when calling it from web3j too: https://rinkeby.etherscan.io/tx/0x4f6eb1449fa53c16033cebe7f8619b72e1e868f30d2af16287630f98508d8cbb

Message:

transact to TicketPro.buyATicketFromContract errored: Gas required exceeds limit: 3000000.  An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that's also the reason of strong gas estimation).

Note: I attached value to the transaction which matches the price set in the bytes32 offer variable and the key I am using has a balance that exceeds this.


texts:
http://raspnode.com/diyEthereumGeth.html#installethereum

recipe for target 'geth' failed
make: *** [geth] Error 2

please provide me the solution ?


texts: Why are these transactions not broadcast in my private network?

texts:
There are 3 nodes in my development environment. I use eth.sendTransaction to post some transactions ,and it seems that the transactions are not broadcast to other nodes.

JSON-RPC Request is :

{"jsonrpc":"2.0",
"method":"eth_sendTransaction",
"params":[{
            "gas":"0xea60",
            "gasPrice":"0x384",
            "to": "0x3d30704a45c6fd56b187343f3b3d21c443c2cdc1",
            "from":"0x01b537e37dbf4c917152a6012364193d6cc02ca9",
            "data":"0xf8b2cb4f....daa71b88ff922d735a7"
          }],
"id":1}

How can I broadcast the transactions to the whole network?


texts: How does metamask manage the multiple transaction with same address?

texts:
I'm struggling to implement the functionality which sends multiple transactions using the same address. here the from address is same but the to addresses are different. When I did research on this, I found that there are two ways to implement the approach -

Perform all transactions parallelly by incrementing the nonce one after one. Call getTransactionCount method one time and increment its count on all the subsequent transactions.
Implement the queue, In which the second transaction does not proceed until the first transaction mined.

When I analyzed the above two approach, I got to know about some issues -

In Approach 1, There may be possible that If one transaction will fail, So all the transaction after that nonce would become fail. But how does the metamask manage such type of cases? because the metamask also do the same thing and we can able to perform transactions one after one.
In Approach 2, In the queue process, one transaction depends on the prior transaction and it not initiated until first gets completed.

As I dig more into the approach, I found that the best approach would be the second one. (queue process)

But I stuck on the following cases while implementing the 2nd approach -

Because we don't know the exact time of the transaction mined in the block, how to decide the time interval to check whether the transaction block is mined or not. (I know that we use the ropsten.etherscan to check the transaction status)
If we give time Interval 15 sec. then it might be possible that transaction not mined in 1 hour and it keeps busy the server to send the request.
There might be such case, where one transaction could not mine until 2-3 days, due to some reasons. In this case what we need to do for overwriting that transaction. What will be the best approach to handle this?


texts: Referencing another another contract returns an empty value

texts:
I've created a consortium based network where I have two contracts deployed.

pragma solidity ^0.4.4;

contract ScoreStore{
    mapping(string => int) PersonScores;

    function AddPersonScore(string name, int startingScore){
        if(PersonScores[name]>0){
            throw;
        } else {
            PersonScores[name] = startingScore;
        }
    }

    function GetScore(string name) returns (int){
        return PersonScores[name];
    }
}

This contract works no problem when interacting with it directly. The second contract:

pragma solidity ^0.4.4;
contract IScoreStore{
    function GetScore(string name) returns (int);
}

contract MyGame{
    function ShowScore(string name) returns (int)
    {
        IScoreStore scoreStore = IScoreStore(0xEB058f7E140991811ff815335DA5bB7e593c8359);
        return scoreStore.GetScore(name);
    }
}

When I make a call to the MyGame contract to ShowScore("Oliver") it returns

{ [String: '0'] s: 1, e: 0, c: [ 0 ] }

When I call GetScore("Oliver") through the ScoreStore contract I get the expected result

{ [String: '15'] s: 1, e: 1, c: [ 15 ] }

What is it that I'm missing?


texts:
As I am reading about ERC20 standard, I found some points that confused me a bit. Below, you can see the code that I am trying to understand. So, my questions are the following;

It says as a comment in the code "Create a table so that we can map the addresses of contract owners to those who are allowed to utilize the owner's contract". Who are considered in this context "contract owners"? Are the ones that have bought tokens?

I totally get the first mapping mapping(address => uint256) balances; but the second one mapping(address => mapping (address => uint256)) allowed; is not clear to me. What is the purpose of that mapping and why is that useful?

What is the difference between the functions transfer() and transferFrom().

That's it! Thanks
pragma solidity ^0.4.15;

contract MyERCToken

{

 // Create a table so that we can map addresses

 // to the balances associated with them

 mapping(address => uint256) balances;

 // Create a table so that we can map

 // the addresses of contract owners to

 // those who are allowed to utilize the owner's contract

 mapping(address => mapping (address => uint256)) allowed;

 // In this case, the total supply

 // of MyERCToken is fixed, but

 // it can very much be changed

 uint256 _totalSupply = 1000000;

 // Owner of this contract

 address public owner;

function totalSupply() constant returns (uint256 theTotalSupply) {

   // Because our function signature

   // states that the returning variable

   // is "theTotalSupply", we'll just set that variable

   // to the value of the instance variable "_totalSupply"

   // and return it

   theTotalSupply = _totalSupply;

   return theTotalSupply;

 }

 function balanceOf(address _owner) constant returns (uint256 balance) {

   return balances[_owner];

 }

 function approve(address _spender, uint256 _amount) returns (bool success) {

   allowed[msg.sender][_spender] = _amount;

 // Fire the event "Approval" to execute any logic

   // that was listening to it

   Approval(msg.sender, _spender, _amount);

   return true;

 }

 // Note: This function returns a boolean value

 //       indicating whether the transfer was successful

 function transfer(address _to, uint256 _amount) returns (bool success) {

   // If the sender has sufficient funds to send

   // and the amount is not zero, then send to

   // the given address

 if (balances[msg.sender] >= _amount

     && _amount > 0

     && balances[_to] + _amount > balances[_to]) {

     balances[msg.sender] -= _amount;

     balances[_to] += _amount;

     // Fire a transfer event for any

     // logic that's listening

     Transfer(msg.sender, _to, _amount);

       return true;

     } else {

       return false;

     }

  }

  function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {

   if (balances[_from] >= _amount

     && allowed[_from][msg.sender] >= _amount

     && _amount > 0

     && balances[_to] + _amount > balances[_to]) {

   balances[_from] -= _amount;

   balances[_to] += _amount;

   Transfer(_from, _to, _amount);

     return true;

   } else {

     return false;

   }

 }

 function allowance(address _owner, address _spender) constant returns (uint256 remaining) {

   return allowed[_owner][_spender];

 }

 // Triggered whenever approve(address _spender, uint256 _value) is called.

 event Approval(address indexed _owner, address indexed _spender, uint256 _value);

 // Triggered when tokens are transferred.

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

}


texts: Will deleting DAG data remove the blockchain data too?

texts:
As we know DAG data is stored in:

 Mac/Linux: $(HOME)/.ethash/

My blockchain has been running for  2 months, so there is more than one file in the above directory.

Question 1: Can I remove the older versions?

Question 2: If I mistakenly remove the current version, would my blockchain data (e.g. transactions and deployed contract) be deleted?


texts:
I'm new to Ethereum and try to configure the initial test network.
I have installed geth and I believe that it has been synced (geth folder current size: 48.7 GB)
There are three folders in appdata:

How can I know which network is synchronized fully and how to use it?


texts: UTC/json wallet file: deleted -> recovered -> corrupted. 0.1 ETH REWARD

texts:
--EDIT--

I have advanced in my research. The UTC/JSON file in question is a 491 byte file.

There are 256 random characters in the file with each 16 possible characters. Like a 256-number long padlock with each 16 possible numbers.

Even if I learned how to write a script that creates a UTC/JSON file for each possible combination, there would be 16^256 possible files, which amounts to 16^256*491 bytes or roughly 8.418*10^308 GIGABYTES. You read that well.

Considering this, my only chance resides in retrieving the actual file through file recovery programs.

--/EDIT--

At this point I am desperate and I need your help. I am quite new to ETH, I got very interested and I started mining two weeks ago with my personal computer and, seeing potential in the currency, I bought 1.0 ETH a few days ago.
I will give a 0.1 ETH reward if someone has a solution for me.

Short version:

UTC file was mistakenly deleted, I was able to recover it, but now Mist, Ethereum Wallet, geth and MyEtherWallet don't recognise the file as a valid wallet file. Might be corrupted after recovery.

Long version:

Yesterday I was running geth to update the blockchain.
I wanted to access the %APPDATA%\Roaming\Ethereum folder to see the actual size of the blockchain.

But Windows gave me an error saying that the folder was not in this location.

I found that strange, restarted my computer, nothing changed.
I figured the folder got corrupted, so I carefully noted my ETH address and deleted the "%APPDATA%\Roaming\Ethereum" folder to download the whole blockchain again.

I did NOT know that the UTC-2017-xx-xx-xxxxx file was my actual wallet and did NOT back it up.

I thought with the address and the password I would be in the clear.

Then I wondered why my wallet didn't show up on Mist, so I looked it up and realized I deleted my UTC/json file which was in the "%APPDATA%\Roaming\Ethereum\keystore" folder.

I downloaded a few file recovery programs, ran them and got my UTC/json file back. Recuva said it was not overwritten and that its quality was "Excellent".

So I sighed in relief and put the file back in the new "%APPDATA%\Roaming\Ethereum" folder.

I opened Mist: nothing. I opened Ethereum Wallet: it showed up!... and disappeared a second after. I opened geth and ran "geth account list" and it did not show up.

It made me depressed at this point. Then I saw someone on a forum suggest MyEtherWallet for a different problem but I figured it could work.

So I dropped the file and it said "File selected UTC....... is not a valid file".

So now I'm screwed, big time. I don't know what else to do.
I will take any of your suggestions.

For now I saw that the UTC/json file weighs 491 bytes. It's not heavy. Could I specifically manipulate it and "bruteforce" it into a valid wallet file with trial-and-error?

Thank you for your time.


texts: How to display information from one contract to another

texts:
I am trying to feed information in a contract and display it in another,

I have 2  contracts provider and user:

In Provider contract I am feeding information like name and address of a user, and I want to display that information in user contract. I can very easily feed info to provider contract but not sure how to display same information in contract user


texts: I assume reading global variables don't cost gas since it's not part of the contract, but I wanted to make sure in the future in case I have to optimize contracts for gas usage.


texts: How to Load JSON Build of Solidity Contract into Javascipt

texts:
I'm thinking there's gotta be a way to load the abi (or the entire JSON build file) of a smart contract into my front-end Javascript app after compilation automatically - meaning via some kind of config script.
That way I don't have to copy-paste the abi into the Javascript  code manually, after every single edit and compilation I make on my smart-contract.
But how?
NOTE: I'm not using Node.js here, we're talking pure front-end vanilla javascript file.
Webpack's website clearly states that: beginning with Webpack version 2.0.0 json loaders are no longer needed.
Well right now I'm trying this and getting an error:
import * as contractArtifact from "../build/contracts/MySmartContract.json"

The error is:
import declarations may only appear at top level of a module

For what it's worth, my code for instantiating the contract in my Javascript code - which works perfectly - is as follows:
contractArtifact = {
    "contractName": "MyContract",
    "abi": [
      {
        "inputs": [
          {
            "internalType": "string",
            "name": "name",
            "type": "string"
          },
     ...
     ...etc...
}

contractABI = contractArtifact["abi"];

// Get the Contract's ADDRESS:
network = Object.keys(contractArtifact.networks)[0];
contractAddress = contractArtifact.networks[network].address;

// Now instantiate the Contract using the ABI and the Address:
contractInstance = new web3Instance.eth.Contract(contractABI, contractAddress);

So this works perfectly - I just don't want to have to manually copy-paste that entire JSON file into here every single time I make the tiniest change to and then compile my smart-contract.


texts:
How to return an array from a function in solidity. Function is given :

function getTrackDetailsNew(bytes32 _iswc) public constant returns(bytes32[] isrc) {
    bytes32 s;
    for(uint8 i=0;i<count;i++) {
        s = track[isrcKeyArray[i]].iswc;
        if(s == _iswc) {
            isrc[i] = isrcKeyArray[i];
        }
    }
    return isrc;
}


texts:
At this point I've given up any hope.

I've tried syncing with geth --fast --cache=1024. I have ~99% synchronization and the remaining ~1% (the last 1000-2000 blocks) is taking forever.

With Parity 1.3.9 --geth I've gotten to a block ~2 420 000 with a rate 200 blocks/second (it took just a couple of hours) and after this point I'm getting 0-1 blocks/second.

What's the problem? Does it have to do with the ongoing attacks or is it the result of the previous attacks that bloated the blockchain? Or is it something else?


texts: How to concatenate a bytes32[] array to a string?

texts:
I am passing an array of bytes32 to my function. This array can contain numbers or hashes etc. to identify an object. In a new use case I want to pass a URL to this function by splitting the URL into parts converted to bytes32. How can I concatenate the single bytes32 to restore the URL?

I know I can create a bytes array and set bytes at indexes. But I don't know how I can access a specific position in a bytes32.

function bytes2string(bytes32[] data) returns (string) {
    bytes memory r = new bytes(1);
    r[0] = bytes1(data[0]);
    return string(r);
}


texts: Ethereum Skipping Empty Blocks --preload option doesnt work

texts:
In my clique PoA  private network setup I try to mine skipping empty blocks and mine only when there is transaction present.
I try to follow How to make miner to mine only when there are Pending Transactions? but I cannot notice that the mining works when I load he script with -- preload followed by .js file.

Instead on starting the node, I open the ipc console and then use loadScript which works fine.

Is there a better way to load the js script while starting the node?

Also is there a way to specify inside the js script the miner gas target and miner gas limit since I need to set up a uniform block gas limit in the network. I noticed that this option is missing in RPC API definitions  which could be the reason ?


texts: Why eth_getLogs returns empty result for Ethereum account address?

texts:
I'm developing an Ethereum platform and need to fetch the events log of a desired address. I found a code like this:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"topics":["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]}],"id":74}'

but when I replace my own address in this code, I receive an empty result as below:

{"jsonrpc":"2.0","id":1,"result":[]}

May you tell me what is my mistake here?


texts: Need help with start mining: I am getting stuck with ? mark ( New work: header #2ef2a542?)

texts:
I have referred to other information found on web to start on mining, but now I am stuck where it is about to begin to mine.

What is this mean when I try to use ethminer? It displays "New work: header" and gets stuck. What do I need to do here? Please see below

 i  16:47:32|main      Found suitable OpenCL device [ GeForce GTX 1080 Ti ] with 11811160064  bytes of GPU memory
 cl  16:47:32|cl-0      No work. Pause for 3 s.
  m  16:47:32|main      Waiting for work package...
  m  16:47:32|main      Got work package: #2ef2a542
  m  16:47:33|main      Speed   0.00 Mh/s    gpu/0  0.00  [A0+0:R0+0:F0] Time: 00:00
  m  16:47:34|main      Speed   0.00 Mh/s    gpu/0  0.00  [A0+0:R0+0:F0] Time: 00:00
  m  16:47:35|main      Speed   0.00 Mh/s    gpu/0  0.00  [A0+0:R0+0:F0] Time: 00:00
 cl  16:47:35|cl-0      New work: header #2ef2a542?


texts: Problem with smart contract's constructor instantiating another smart contract

texts:
I have the following two smart contracts in the same ".sol" file: Credentials and Proposals.
Every Proposals smart contract should refer to a single Credentials smart contract, in order to do that, when Proposals is created (constructor method) it instatiates a Credentials smart contracts as you can see below.
Credentials.sol:
contract Credentials {

    uint256 _numberOfProviders;
    mapping(address => bool) public _owners;
    uint256 _numberOfOwners;

    constructor(address[] memory owners) payable{
        _owners[msg.sender] = true;
        _numberOfOwners = 1;
        for (uint i=0; i<owners.length; i++) {
            if(false == _owners[owners[i]]){
                _owners[owners[i]] = true;
                _numberOfOwners += 1;
            }

        }
        _numberOfProviders = 0;
    }
}

Proposals.sol:
contract Proposals {

    Credentials  _credentialsContract;
    address payable _chairperson;

    constructor() payable{
        _chairperson = payable(msg.sender);
        address[] memory listOfOwners;
        listOfOwners[0] = msg.sender;
        _credentialsContract = new Credentials(listOfOwners);
    }
}

In Remix the compiler works but when I try to deploy Proposals I get the following error which I do not understand:
creation of Proposals errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.


texts: Re-entrancy attack explanation and possible fix for specific NFT token - hashmasks

texts:
One popular recent NFT project - Hashmasks - Tweeted that some coder called 'samczsun' uncovered a possible re-entrancy attack in their mint function which would have allowed to mint more than the possible supply of 16,384 Hashmasks.They say , If timed perfectly correctly, the maximum number of extra masks mintable mathematically would have been 210 (20 + 19 + … 1)
Hashmasks token link on etherscan:  HASMASKS
The mint function is as follows:
'''
function mintNFT(uint256 numberOfNfts) public payable {
    require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
    require(numberOfNfts > 0, "numberOfNfts cannot be 0");
    require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once");
    require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
    require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");

    for (uint i = 0; i < numberOfNfts; i++) {
        uint mintIndex = totalSupply();
        if (block.timestamp < REVEAL_TIMESTAMP) {
            _mintedBeforeReveal[mintIndex] = true;
        }
        _safeMint(msg.sender, mintIndex);
    }

    /**
    * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
    */
    if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
        startingIndexBlock = block.number;
    }
}

function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
    _mint(to, tokenId);
    require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}

'''
I do not understand why the issue occurs. Could anyone enlighten me why this re-entrancy attack can happen and also how it could be fixed in the code. Thanks all.


texts:
I am using Truffle suit to develop, test and deploy my smart contracts. It works pretty well on test networks but on live one it slow like a snail.

For instance this transaction  - it is just migration contract (from truffle infrastructure) deployment, estimated time of confirmation with price 40 GWei is about 2 hours. Overall deployment has about 18 transactions (truffle, after each successfully confirmed transaction stores it in its own migration contract to avoid redeployment of already deployed stuff).

40 Gwei is more then maximum gas price across the network and I am wondering is it possible to speedup deployment somehow? 2 hours per transaction is unacceptably slow.


texts: error when trying to upload picture from ipfs

texts:
$("#image").change(function(event) {
    const file = event.target.files[0]
    reader = new window.FileReader()
    reader.readAsArrayBuffer(file)
  });

function saveOnIpfs(reader) {
    return new Promise(function(resolve, reject) {
      const buffer = Buffer.from(reader.result);
      ipfs.add(buffer)
      .then((response) => {
        console.log(response)
        resolve(response[0].hash);
      }).catch((err) => {
        console.error(err)
        reject(err);
      })
    })
  }

this is the error i get in the console

index.js:107 Uncaught (in promise) TypeError: Cannot read property 'result' of undefined
    at index.js:107
    at new Promise (<anonymous>)
    at new t (_export.js:36)
    at HTMLFormElement.<anonymous> (index.js:106)
    at HTMLFormElement.dispatch (jquery.min.js:3)
    at HTMLFormElement.q.handle (jquery.min.js:3)


texts: Sending signed transaction to create a contract

texts:
My goal is to send a signed transaction to create a smart contract, however, I am facing an issue I have not been able to solve for  few days:

When I send the transaction (on a private chain), there are two different ending:

- 1
Web3js tells me it worked, I can see the transaction on the block. However, when trying to contact the contract, I have the following output:

  Error: Couldn't decode uint256 from ABI: 0x

When I try to run eth.getCode(contractAddress) in Geth, it returns 0x

- 2
Web3js tells me that the transaction has not been mined for 50 blocks (the node did not have time to mine 50 blocks). But I can see the transaction in the block (in geth).

Here is the code I use:

web3g = result;
getContractInstance(function (error, instance) {
    if (error) {
        console.log(error);
    } else {
        let newContract = instance;
        let deploy = newContract.deploy({
            data: bytecode,
            arguments: [MY ARGS]
        }).encodeABI();
        let gas = web3g.utils.toHex(3000000);
        let gasPrice = web3g.utils.toHex(21000000000);
        let gasLimit = web3g.utils.toHex(4000000);
        let nonce;
        web3g.eth.getTransactionCount(req.body.sender_address)
            .then(function (result) {
                nonce = result;
                nonce = web3g.utils.toHex(nonce);
                let transactionObject = {
                    gas: gas,
                    gasPrice: gasPrice,
                    gasLimit: gasLimit,
                    data: deploy,
                    from: req.body.sender_address,
                    nonce: nonce
                };

                web3g.eth.accounts.signTransaction(transactionObject, req.body.private_key, function (error, signedTx) {
                    if (error) {
                        console.log(error);
                    } else {
                        console.log(signedTx);
                        web3g.eth.sendSignedTransaction(signedTx.rawTransaction)
                            .on('confirmation', function (number, receipt) {
                                if (number == 1) {
                                        // do stuff

Can someone point me out what I am doing wrong?

Note: I am able to send signed transaction using the method above to transfer ether between addresses.

Edit: Estimating gas returns the following: error: Returned error: gas required exceeds allowance or always failing transaction


texts: Why can`t I get more transactions from a batch in the same block?

texts:
So, the other day I tried batching a lot of transactions ~100 from the same account and sent them out to ethereum. I was programmatically creating a lot of txs, incremented the nonce accordingly, signed them and sent them put (all via web3js 1.0).

All of them got processed eventually but I could rarely see 2 or more txs go in the same block. they mostly got mined every other block one at a time. even when I increased the gasPrice a lot I couldn`t see an improvement in how quickly the batch got mined.

Does somebody have an idea why this happens?

Before moving to mainnet i tested on ropsten and an entire batch of 30txs got mined in the same block. Is this related to how miner pick which tx to put into blocks? I understand why a miner does not include in a block a tx that has its nonce in the future but i dont get why it would not include more txs from the same account if they have consecutive nonces, they're valid and the gasPrice is high. Funny thing is that every once in a while a block came out with 2 or more consecutive txs but this was rare.


texts:
I was playing around with call, delegatecall and callcode and discovered that the function reset stopped working after I had made a callcode call (here are my actions):

FROM JS SIDE:

— A.makeCall({gas:300000}); // NO ERRORS
— A.sender(); // 0x0000000000000000000000000000000000000000 AS EXPECTED
— A.myVar(); // 0 AS EXPECTED
— B.sender(); // addressA AS EXPECTED
— B.myVar(); // 1 AS EXPECTED

— A.reset({gas: 300000}); // NO ERRORS;

— A.sender(); // 0x0000000000000000000000000000000000000000 AS EXPECTED
— A.myVar(); // 0 AS EXPECTED
— B.sender(); // 0x0 AS EXPECTED
— B.myVar(); // 0 AS EXPECTED

— A.makeCallCode({gas:300000}); // NO ERRORS
— A.sender(); // 0x0000000000000000000000000000000000000002 Oops! It looks like there was no access to msg.sender and sender variable was assigned argument x instead.
— A.myVar(); // 0 Oops! Nothing was assigned, because of the ↑
— B.sender(); // 0x0 AS EXPECTED
— B.myVar(); // 0 AS EXPECTED

— A.reset({gas: 300000}); //ALL KIND OF ERRORS; WTF IS GOING ON HERE? NO MATTER HOW MUCH GAS I SUPPLY IT STILL FAILS. https://testnet.etherscan.io/tx/0x6654b6739f55690c7114fa9e8cfb7a5959e73d60c37782aee4e211487de859f2

contract A {
    address public addressB;
    address public sender;
    uint public myVar;

    function A() {
        addressB = new B();
    }

    function makeCall(){
        addressB.call(bytes4(sha3('set(uint256)')), 1);
    }
    function makeCallCode(){
        addressB.callcode(bytes4(sha3('set(uint256)')), 2);
    }
    function makeDelegateCall(){
        addressB.delegatecall(bytes4(sha3('set(uint256)')), 3);
    }

    function reset(){
        sender = 0;
        myVar = 0;
        B(addressB).reset();
    }
}

contract B {
    address public sender;
    uint public myVar;

    function set(uint x){
        myVar = x;
        sender = msg.sender;
    }
    function reset(){
        sender = 0;
        myVar = 0;
    }
}


texts: Provisioning a VPS - help predicting disk space needs

texts:
I am going to provision a VPS for a Parity ETH node.

Can anyone give me a guess what my disk space needs will need to be for the Parity download of the Mainnet blockchain?

Date is 12 September 2017.  Similar questions exist but the answer changes over time.


texts: Setting methods permissions a quorum network

texts:
I have 3 solidity smart contracts that run in a quorum network with 7 nodes.
At the moment i use the constructor to set the owner of the smart contract, that is the node that deployed it.

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

This allows me to consent the access of some methods with

require(owner == msg.sender);

Now, I would like to allow access to these methods also to two other nodes. Is it possible to set these permissions at run time? Or you suggest me to write the addresses of the allowed nodes directly in the code? If so, where do I find the quorum node addresses?


texts:
I am an Ethereum beginner and was following this guide: https://www.ethereum.org/cli

I want to create a private Ethereum network. So I executed:

geth --datadir ~/.ethereum_private init ~/dev/genesis.json

But it fails:

  Fatal: failed to read genesis file: open /Users/xxxxxxx/dev/genesis.json: no such file or directory

The tutorial does not tell me where I get the "genesis.json" file from. Where do I get it? Do I need to create it myself? How?


texts:
First of all, I have already searched on Google, and I didn't find a clear answer.
What I would like to do :
For example, I would like to make one swap on uniswap, and the second to sushiswap, in the same transaction, like this :
UNISWAP : ETH -> UNI
SUSHISWAP : UNI ( last output ) -> ALCX
I know it's possible by writing a smart contract, but I don't know at all how to do.
Anyone has an idea ?
Thank you a lot.


texts: Why (conceptually) can't mappings be local variables?

texts:
My understanding is that the mapping type cannot be used as a local variable, and must be a member (i.e., state) variable.

Is there a conceptual reason for this to be the case?  I can't imagine this couldn't be implemented as a memory variable?


texts: Is there a drawback of setting a too high gas limit for a transaction?

texts: Say, I want to send a transaction that consumes around ~40,000 gas. Could I just set the gas limit of the transaction to 1 million or is there some disadvantage and I should set a more realistic gas limit? In the end I only pay for what was actually consumed, so a too high limit shouldn't matter, right?


texts: Passing the address of a structure allocated in storage on one contract, to a function on another contract

texts:
I have a contract which declares a array of structures allocated in storage.

From this contract, I invoke a function in another contract, which takes a single structure as input.

In order to workaround "syntax obstacles", I pass the contents (variables) of the structure instead.

I needed to add a few more variables to the structure, and now I get the following  compilation error:

  Stack too deep, try removing local variables.

Instinctively, I believe that the only solution is to pass the structure to the function "by address"

Since I have the array of these structures allocated in storage, I think that it should be feasible.

However, no matter how I try to write it down, I keep getting errors.

When I declare the return-type as address, I get the following compilation error:

  Return argument type struct MyStruct storage ref is not implicitly convertible to expected type address.

When I declare the return-type as MyStruct storage, I get the following compilation error:

  Location has to be memory for publicly visible functions (remove the "storage" keyword).

When I declare the return-type as MyStruct memory, I get the following runtime error:

  Static memory load of more than 32 bytes requested.

Does the Solidity standard state anywhere that this is not feasible?

Thank you.


texts:
We have been developing a dapp which submits a very basic transaction (placing a short hash and some Eth into a contract). We set the gas relatively high (250000). Often the transaction is mined in good time, within a minute, which is just about tolerable to a waiting user. Sometimes, however, it is very long, occasionally threatening to take hours according to Etherscan.

We have considered e.g. Gas price strategy, but we can't quite see how that would deal with these strange delays.

What can we do to overcome this?

Is there a good description for how to do this?


texts: Is it possible to store / catalogue every file which is being published over IPFS ? Is only encryption the viable way to securely publish files over the internet ?


texts:
The code is as following, if Contract send ether to Contract Receiver, I will recevice:
transact to Sender.send errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value.

However, if I annotate line "addr = msg.sender;" "amount = msg.value;" everything is ok, and I will receive the event log

pragma solidity ^0.4.11;
contract Receiver {
    address public addr;
    uint public amount;
    event log(address, uint);
    function() payable{
        addr = msg.sender;
        amount = msg.value;
        log(msg.sender, msg.value);
    }
    function Receiver() public payable {
        addr = msg.sender;
        amount = msg.value;
    }
}

contract Sender{
    function send(address addr, uint amount) payable{
        addr.transfer(amount);
    }
    function getBalance() payable returns (uint) {
        return this.balance;
    }
    function Sender() payable{ }
}


texts:
If you've ever seen the ethereum blocktime chart, you've noticed that always it's between 10-19 and when ever it comes bigger than, network will set difficulty lower than before and again the block time is between 10 and 19.
Is there any config in genesis or somewhere to set this time?


texts: Solidity. Return a Sruct that lives inside an array

texts:
I am not sure how to return a struct that is inside an array of structs. This is my code:

contract StudentsInfoTracker{

    Student[] students;

    struct Student{
        string name;
        address ethAddress;
        uint numberInClass;
        uint[] marks;
    }
    function getStudent(uint) public view returns(string memory name, address ethAddress, uint numberInClass, uint[] memory marks){
        return(students[uint].name, students[uint].ethAddress, students[uint].numberInClass, students[uint].marks);
    }

I need to return the student given the uint index. I know I can't return a complete struct but I can try to retrieve its data. Anyway I get this error:

  TypeError: Type type(uint256) is not implicitly convertible to
  expected type uint256.


texts: Read and write private variable from child contract

texts:
I have a contract MyContract is ERC721. MyContract needs to concatenate a string with an existing token URI using this function:

string(abi.encodePacked(_tokenURIs[_tokenId], _URI));

Problem is all tokens' URIs are stored in a private variable in the parent ERC721 contract like so

mapping(uint256 => string) private _tokenURIs;

Gas efficiency is a key requirement here. MyContract should not call the standard ERC721 tokenURI getter function: it needs a direct access to the mapping so as to concatenate the strings in one step (concatenation via tokenURI function would involved three steps: fetch initial URI string, concatenate appendice string, push concatenated string).

I'd like to use the standard URI functions provided by ERC721. Is this a dead-end? Can I simply change _tokenURIs mapping from private to internal and still be ERC721 compliant? Is there a work-around where I could directly overwrite _tokenURIs mapping from child contract?


texts: Where to find ICO contract with linear / logarithmic decrease?

texts:
I had a look at some existing crowdsale contracts:

https://github.com/aragon/aragon-network-token/blob/master/contracts/AragonTokenSale.sol
https://github.com/sonm-io/presale-token/blob/master/contracts/PresaleToken.sol
https://github.com/ConsenSys/Tokens/tree/master/Token_Contracts/contracts
https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/crowdsale
https://github.com/Giveth/minime/blob/master/contracts/MiniMeToken.sol
https://github.com/TokenMarketNet/ico/tree/master/contracts
Etheroll: https://etherscan.io/address/0xa9a8108994bb704261567e53b49607a73876ddf1#code

Below is an ASCII graph from Aragon source code. Rather than stages, I'd like to find a contract that implements linear or logarithmic decrease in the amount of tokens...


texts: Sign a transaction programmatically with a bash command line command

texts:
Let's suppose i have my metamask/ledger secret seed phrase.
Here is what i want to do:

I want to calculate the first account private key
I want to sign a message with this private key

It is possible to do that with some online services which works with metamask wallet. But i want to do this myself on my computer, with my program.
Are there some linux command line tools (like openssl) which can do this task ?
Thanks a lot


texts: Is it possible to schedule transactions without locking all the ether right away?

texts:
Let's assume I want a contract with function that sends X Ether each month. A user agrees to send a certain amount of Ether to the contract every month, and makes a transaction corresponding to a function call with X as one of the arguments.

The ideal way would be to automatically send the Ether every month, and handle exceptions planned in the contract if the user doesn't have enough Ether.

I don't want to have to send a big number of Ether at once, like a year's worth every year, but that would mean that the contract is allowed to debit Ether by itself.

How would that work in practice, is it possible?


texts: Problem with sending ERC20 token using web3@1.0.0

texts:
Circumstance

I have followed all indications from this GH issue and from other SO posts. The transaction gets successfully broadcasted but no tokens are transferred.

When I check the balance before and after running the code, I get the same result: 10000, which is the original supply.

const Tx = require('ethereumjs-tx');

const config = require('../config');
const contract = require('../contract')('PaulCoin', config.contracts[0]);
const web3 = require('../web3');

const main = async () => {
    try {
        const count = await web3.eth.getTransactionCount(config.accounts[0]);
        const nonce = web3.utils.toHex(count);
        const txValue = web3.utils.toHex(parseInt(process.argv[2], 10) || 10);

        const from = web3.utils.toChecksumAddress(config.accounts[0]);

        const to = web3.utils.toChecksumAddress(config.accounts[1]);
        const rawTx = {
            nonce: nonce,
            from: from,
            to: to,
            value: '0x0',
            gasLimit: '0x30D40', // 54,000
            gasPrice: '0x2CB417800', // 12 gwei
            data: contract.methods.transfer(to, txValue).encodeABI(),
            chainId: '0x03'
        };

        const privateKey = Buffer.from(config.private, 'hex');
        const tx = new Tx(rawTx);
        tx.sign(privateKey);
        const serializedTx = tx.serialize();

        const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
        console.log(`Receipt info:  ${JSON.stringify(receipt, null, '\t')}`);

        console.log(`From\'s balance after transfer: ${await contract.methods.balanceOf(from).call()}`);
        console.log(`To\'s balance after transfer: ${await contract.methods.balanceOf(to).call()}`);
    } catch (err) {
        console.log(err);
    }
};

main();

Environment

node 9.3.0
web3 1.0.0-beta.35
infura ropsten
os osx 13.13.5


texts: how to hook up web3 injected by metamask in angular 2

texts:
As described in metamask github, one can bootstrap metamask like this:

window.addEventListener('load', function() {

  // Checking if Web3 has been injected by the browser (Mist/MetaMask) if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);   } else {
    console.log('No web3? You should consider trying MetaMask!')
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));   }

  // Now you can start your app & access web3 freely:   startApp()

})

How do I implement in angular 2 typescript, and where do I hookup this metamask web3 inject so that it will popup the metamask wallet whenever I trigger web3.eth.sendTransaction()


texts: Have the curators emptied the whitelist of all splits after the 17 June attack?

texts:
Would like to understand if an imitator attack is possible in the next days?
Explain if the split list of MEW https://www.myetherwallet.com/#dao-proposals reflects the whitelisting.
Explain if splits are in the whitelist at all.


texts: Problem verifying contract code on rinkeby

texts:
I've deployed a basic MichaelCoin ERC20 contract without issue and able to interact with it via geth console. My issue is verifying it on http://rinkeby.etherscan.io.

I am inputting MichaelCoin as the contract name and when I run truffle version I get:

Truffle v3.4.5 (core: 3.4.5)
Solidity v0.4.11 (solc-js)

The compiler version I am choosing is v0.4.11+commit.68ef5810

The error I'm getting is:

 Note: Contract was created during Txn# [0xb9c93fc42899022b578594706fcb770899e976054c1377df22f02273c6608a37]
 Result: Does not match the input creation bytecode found at this address

Sorry! The Compiled Contract ByteCode for 'MichaelCoin' does NOT match the Contract Creation Code for [0xba598b093bf468053ad740729466045b17701d87].

Contract name(s) found: 'MichaelCoin'
Unable to Verify Contract at this point time.

Contract address on rinkeby etherscan is https://rinkeby.etherscan.io/address/0xba598b093bf468053ad740729466045b17701d87

Here is my contract code:

pragma solidity ^0.4.11;

contract MichaelCoin {

  mapping (address => uint256) balances;
  mapping (address => mapping (address => uint256)) allowed;

  string public name = "Michael Coin";
  string public symbol = "MC";
  uint8 public decimals = 18;
  uint256 public totalAmount = 1000000;

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

  function MichaelCoin() {
    // constructor
    balances[msg.sender] = totalAmount;
  }
  function totalSupply() constant returns(uint) {
    return totalAmount;
    }
  function transfer (address _to, uint256 _value) returns (bool success) {
    if (balances[msg.sender] >= _value
        && balances[_to] + _value > balances[_to]) {
      balances[msg.sender] -= _value;
      balances[_to] += _value;
      Transfer(msg.sender, _to, _value);
      return true;
    } else { return false; }
  }

  function transferFrom(address _from, address _to, uint _value) returns (bool success) {
    if(balances[_from] >= _value
        && _value > 0
        && balances[_to] + _value > balances[_to]
        && allowed[_from][msg.sender] >= _value) {

        balances[_from] -= _value;
        balances[_to] += _value;
        Transfer(_from, _to, _value);

        return true;
    }
    return false;
}

  function balanceOf(address _owner) constant returns (uint256 balance) {
    return balances[_owner];
  }

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

  function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
  }

  function() {
    throw;
  }
}

Thank you for any guidance.


texts:
Dealing with the code below:

contract myContract {

    struct myStruct{
        bytes32 name;
        bool active;
        uint[] changes;
    }

    myStruct[2] myStr;
    uint[] steps;

    Event activatedEvent(uint time);

    function myContract{
        myStr[0] = packStruct('foo', true, steps);
        myStr[1] = packStruct('bar', false, steps);
    }

    function activate(){
        myStruct ms = myStr[0];
        ms.changes.push(now);
        activatedEvent(now);
    }
}

If I call the activate() function, the activatedEvent does not get triggered. Anybody knows where I'm wrong? Any help appreciated.


texts:
I would like to emit event in function modifier. Is it legitimate to do so in solidity?

Here is a event and a modifier

uint timeStamp;

event beforeTimeStamp();

modifier NotTooLate() {
  require(timeStamp > now);
  emit beforeTimeStamp();  //can I emit event here in modifier?
  _;
}


texts: What is an example of when a solidity variable must NOT be public? Where it would break the security of the contract?

texts:
I'm really struggling to understand variable visibility. I'm aware that everything is public on a blockchain. Yes you can make a variable private to make it invisible to other contracts, but so what? What harm does allowing other contracts to view it, as long as they cannot change it?

Can I just set every variable in my contract public without putting too much thought into it? I can't really see why not...


texts: Geth response: invalid content type, only application/json is supported

texts:
I started geth on a remote server running on rinkeby with the parameters --rinkeby --fast --cache=128 --rpc --rpcaddr 0.0.0.0

When I try to test my access to geth using

curl -X POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}' http://my-geth-remote-server:8545

I received the response

invalid content type, only application/json is supported

Pretty confused about the error, isnt the RPC payload given in JSON already?

Geth used is Geth/v1.7.3-unstable-9b97f983/linux-amd64/go1.9.2

Response of curl after adding -v

curl -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":42}' http://8.8.8.8:8545 -v

* Rebuilt URL to: http://8.8.8.8:8545/
* timeout on name lookup is not supported
*   Trying 8.8.8.8...
* TCP_NODELAY set
* Connected to 8.8.8.8 (8.8.8.8) port 8545 (#0)
> POST / HTTP/1.1
> Host: 8.8.8.8:8545
> User-Agent: curl/7.55.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 57
>
* upload completely sent off: 57 out of 57 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Mon, 13 Nov 2017 21:39:48 GMT
< Content-Length: 109
<
{"jsonrpc":"2.0","error":{"code":-32600,"message":"invalid character '\\'' looking for beginning of value"}}
* Connection #0 to host 8.8.8.8 left intact

curl --version

curl 7.55.0 (x86_64-w64-mingw32) libcurl/7.55.0 OpenSSL/1.0.2l zlib/1.2.11 libssh2/1.8.0 nghttp2/1.23.1
Release-Date: 2017-08-09
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smtp smtps telnet tftp
Features: IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL libz TLS-SRP HTTP2 HTTPS-proxy Metalink

This is the windows versions of curl.


texts: Login to an ethereum dapp on sending a transaction?

texts: I'm trying to build a sample dapp. The login process in ethereum dapps usually involves signing a message from metamask to prove ownership of an account. Is there a way we could design login in such a way that the user gets logged in automatically when sending a transaction (invoking a state changing function). This is feasible since both operations require signing. Any ideas please ?


texts: transferFrom in contract function doesn't work

texts:
I'm trying to make a simple transferFrom within my contract using remix.
Contract code:
pragma solidity >=0.7.0 <0.9.0;

// Import OpenZeppelin's ERC20 interface defenition
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/token/ERC20/IERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/token/ERC20/utils/SafeERC20.sol";

// Simple ERC20 token that mints the given initialSupply to the deployer
contract MYTOKEN is ERC20  {
    constructor()  ERC20("mytoken", "MYTOKEN") {
        _mint(msg.sender, 100000000 * (10 ** uint256(decimals())));
    }

   function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {

    }
}

contract SmartSub {
    using SafeERC20 for MYTOKEN;

    mapping(address => uint256) public bank;

    function deposit(uint amount) public {
        // The address is MYTOKEN address after i have deployed it
        MYTOKEN(0x0fC5025C764cE34df352757e82f7B5c4Df39A836).transferFrom(msg.sender, address(this), amount);
        bank[msg.sender] += amount;
    }

}

beforehand i approve 10000 tokens, where i allow the contract address to transfer MYTOKEN from my account (the one i created all contracts with). After calling allowance with contract address i see the amount i have allowed before as expected.
Then i head to deposit function, where i input 10. After executing it, i see success but when i check the balance of my contract address i still see 0.
Why are the tokens not being transferred? What am i doing wrong?


texts: Quorum - Was the raft log corrupted, truncated, or lost? Incremental/Differential Backup Strategy and Restoring EVM State in a Quorum Node

texts:
Say, there is only one quorum node within each organisation (among many other quorum nodes which are spread out in other organisations) and that quorum node encountered some catastrophic incident where all the data (i.e., EVM state) is wiped out.

How can one restore the data? Or perhaps the question is how can one backup the evm state? What will be the backup and recovery strategy?

Does connecting the quorum node back to the network work? I tried removing the entire node data and tried to connect the quorum node back it did not work. I am using Raft consensus and the error returned: Was the raft log corrupted, truncated, or lost?


texts: How does a node handle smart contracts during sync?

texts:
I was thinking to set up an Ethereum full node, but have some questions I can’t find the answers to.

Does my node have to execute every smart contract that was put in the blockchain over the past years to verify if the outcome was the same? If so, doesn’t that make the electricity cost add up a lot over time, also for the nodes in the future? From what I understand only the miner gets paid for a smart contract, but my node would have to do work too.

If I don't have to execute all those smart contracts, how does my node know what happened in the past and what the blockchain looks like now?

What happens if the data input of a smart contract was changed or isn’t available anymore? How does my node still get in sync with the rest of the network?

Thanks in advance


texts: Deploying smart contract with truffle and infura giving me error

texts:
I am having trouble deploying my smart contract to the ropsten network using infura and truffle am getting error that says

"var sig = secp256k1.sign(msgHash, privateKey);
                      ^
TypeError: private key should be a Buffer"


texts: Etherscan Unable to locate Transaction entry

texts:
I'm using the Ropsten network with Parity and when I send a transaction from an account to another account I get the good transaction hash. When I'm trying to call getTransaction(transaction_hash) I can see my transaction but I can't see it on etherscan. When I search my transaction with my hash I got this message Unable to locate Transaction entry. I don't understand why because I can see the pending transaction with the getTransaction()

So I have to know when my transaction is published on the blockchain. But my transaction is stuck in pending status since 1 month. I don't understand why...

Do you have an idea why all my transactions are stuck up ?


texts: Solidity group addresses with a name. Eg: Whats app groups

texts:
I want to create a squad(group) which consists of a group addresses.
Like Squad XYZ consists of Addr1 with name 'A',Addr2 with Name 'B', Addr3 with name 'C'.

pragma solidity ^0.5.9;

contract Squads{

    struct squadMemberInfo{
        string memberName;
        address memberAddress;
    }
    struct squadInfo{
        string squadName;
         squadMemberInfo[] squadMembers;
    }
    squadInfo[] public SI;
    squadMemberInfo[] public SMI;
    //Function to create a Squad/Group and name that group
    function createSquad(address[] memory _addressesToBeGrouped,string memory _squadName) public returns(string memory isCreated){
        //Yet to be coded
    }
    //Function to add Members to an existing Squad
    function addMember(string memory _squadName,address _memberAddress, string memory _memberName) public returns(bool isAdded){
        squadMemberInfo memory squadMember = squadMemberInfo(_memberName,_memberAddress);
        SMI.push(squadMember);
        squadInfo memory squadInformation = squadInfo(_squadName,SMI);
        SI.push(squadInformation);
        return true;
    }

}

I want make squadMemberInfo[] public SMI; as a local variable inside function addMember so that the function could return array of squadMemberInfo[]. I can directly use this return array and feed the struct squadInfo.

Also I am a bit confused how could I achieve this. :(


texts: I am trying to call a function from my back-end to my front-end. I know that my contract is deploying, however, I don't think my function is not being called correctly. My code is provided below. Does anyone know how I could fix this? Help would be insanely appreciated!


texts:
I wonder, since Ethereum is based on a decentralized p2p network, how does it get through the NAT Firewall? There is no server Ethereum can connect on, so there has to be a way for nodes to accept incoming connections. How does Ethereum do that?

Thanks in advance,
rpanic


texts: How to pass and store more than 16 arguments in a contract

texts:
I'm trying to create a contract which stores simple user profile information like name, email, age, address, etc (all string/bytes type) and I've come across the size restriction issue when passing the arguments to the constructor/function.

What are the best possible options to work around this limiation?

Should I serialize and pass this data somehow? Or is it better to just store this simple data object of every user in IPFS and save the hash in the contract?