texts: What is "issuer-backed assets" in ethereum white paper?

texts:
When talking about options to tackle volatile cryptocurrency prices, Ethereum's white paper has the following discussion:

  Such a contract would have significant potential in crypto-commerce.
  One of the main problems cited about cryptocurrency is the fact that
  it's volatile; although many users and merchants may want the security
  and convenience of dealing with cryptographic assets, they may not
  wish to face that prospect of losing 23% of the value of their funds
  in a single day. Up until now, the most commonly proposed solution
  has been issuer-backed assets; the idea is that an issuer creates a
  sub-currency in which they have the right to issue and revoke units,
  and provide one unit of the currency to anyone who provides them
  (offline) with one unit of a specified underlying asset (eg. gold,
  USD). The issuer then promises to provide one unit of the underlying
  asset to anyone who sends back one unit of the crypto-asset. This
  mechanism allows any non-cryptographic asset to be "uplifted" into a
  cryptographic asset, provided that the issuer can be trusted.

Any one can elaborate on the concept "issuer-backed assets", especially the words in bold above? Does it mean the issuer raise the funds in USD/gold/etc and repay them in Ether? Any link to ICO here?

Confused here. Thanks a lot!


texts:
Facing an issue while working multi-http-provider.
When I write
var Web3 = require('web3');
require('multi-http-provider');

It throws an error
uncaughtException : RangeError: Maximum call stack size exceeded

No error if I use
var web3 = require('web3');
web3 = new web3();
var provider = new web3.providers.HttpProvider("http://" + truffleConfig.networks.development.host + ":" + truffleConfig.networks.development.port);
const maxGas = truffleConfig.networks.development.gas;
web3.setProvider(provider);

Web3 version
web3: ^1.2.0
solc: ^0.4.24
truffle-contract: ^3.0.1


texts:
I have been running a geth node, mostly to see event logs fired by my contracts. I ran the node with syncmode=fast and finally the node is synced. I can successfully read the logs.

Now, I read here the option --gcmode=archive described as:

  Trie pruning is enabled on all --syncmode variations (including
  --syncmode=full). If you are running an archive node where you would like to retain all historical data, you should disable pruning via
  --gcmode=archive.

What does the historical data mean here? Is it more than the normal logs that are created by events fired during transactions? What does it include and when should I use --gcmode=archive?


texts: Is there a simple Ethereum address generator that consists only of private key and public key?

texts:
I can go to https://www.bitaddress.org/ , download their software to my system, disconnect my system from the Internet, then move my mouse over their page randomly to generate entropy and then get a single Bitcoin wallet. The single wallet address is really simple that I can carry with me in any form (print it to a paper, copy it to a file on any device and secure it the way I wish, etc.)

Does something equally simple exist for Ethereum?

I tried https://www.myetherwallet.com/ but I think it enforces added complexity on me to secure the private key. For example, first it forces me to pick a password that it would use to secure the private key. Then the resulting wallet looks complex like the following:

{
  "version": 3,
  "id": "54f...",
  "address": "46d...",
  "Crypto": {
    "ciphertext": "9c3...",
    "cipherparams": {
      "iv": "ac6..."
    },
    "cipher": "aes-128-ctr",
    "kdf": "scrypt",
    "kdfparams": {
      "dklen": 32,
      "salt": "9c8...",
      "n": 1024,
      "r": 8,
      "p": 1
    },
    "mac": "559..."
  }
}

(Note: I have used ... to truncate long strings. Also don't worry, I won't use this wallet anywhere.)

Along with saving this JSON file in exactly this format, I also need to remember an additional password.

So back to my question: Is there any Ethereum address generator that can just give me a private key and a public key that I can secure however I wish?


texts: What are the simplified steps to mining ethereum

texts:
I'm totally new to this.  I had a chance to buy 100 bitcoins a few years back for $500,
Recently, with the bitcoin bubble, I learned about ethereum.  I barely understand the technology, but find it fascinating.  I bought a couple "ethers" a few weeks ago and then...............
I bought a computer with 8gigs RAM, a quad processor, AMD radeon 5070 graphics card , etc and dedicated the whole deal to downloading eth.........

2 days ago.

I've made every mistake and assumption I think a person can make trying to download ethereum.(including asking multiple questions in the same post, editing now) I've looked at a lot of Q/A on the web. Step by step answers are scattered all over.
The box is currently cooking along.  My "geth" is currently
running ad nauseum the phrase, "imported new chain segment", but it doesn't seem to be catching up with the blockchain.  Every few hours the block count
on my "geth attach" screen increases about 2k give or take.  So....can someone answer simply a few questions please?

if/when the blockchain is completely downloaded can ethereum wallet and ethminer be drag/dropped into the window or do i have to execute a command?

Thanks

Steve


texts: Security of Exclusively using MetaMask's Account as a Login Process

texts:
I am currently developing a Dapp in vue.js/node.js which will use MetaMask to interact with the Ethereum Network. I have the following code implemented in a JavaScript module.
 import web3 from 'web3';
 const web3Cont = () => new Promise((resolve) => {
  window.addEventListener('load', () => {
  let currentWeb3;

  if (window.ethereum) {
   currentWeb3 = new web3(window.ethereum);
    try {
     window.ethereum.enable();
      resolve(currentWeb3);
    } catch (error) {
    alert('Please allow access for the app to work');
    }
    } else if (window.web3) {
     window.web3 = new web3(web3.currentProvider);
     resolve(currentWeb3);
    } else {
     alert('You will need MetaMask to use this Site.');
    }
  });
 });
 export {web3Cont};

I also have the following deployed in a vue.js component:
 mounted () {
  web3Cont().then((res) => {
    this.web3 = res
   if (this.web3.utils) {
   }
   this.contractInstance = new this.web3.eth.Contract(contractAbi, contractAddress)
   this.web3.eth.getAccounts().then((accounts) => {
   [this.account] = accounts
   ...
 })

I did not implement any login nor any cookies functionality, and relying exclusively on the account logged into MetaMask (obtained by the current Provider above) in order to identify the user. Is this tactic secure? Could someone hijack the session somehow and trigger transactions on the Ethereum Network using the hijacked session and MetaMask's Account currently logged in.
Thank you. J


texts: Is it possible to retrieve token decimals via API call?

texts:
I'm looking for a way to retrieve token decimals by programmatically. Let's take this Arcade (ARC) token. Token Decimals is 18.

It seems etherscan does't provide API for this purpose. Is there a way to retrieve token decimals somehow?


texts: How can I get MHash value when ethminer doesn't provide one?

texts:
In order to set up the ethminer I need the MHash value. I'm testing CPU, so I ran:

ethminer -M

and I got a weird output:

Trial 1... 0
Trial 2... 0
Trial 3... 0
Trial 4... DAG  17:33:59.896|miner0  Generating DAG file. Progress: 0 %
0
Trial 5... 0
 ⚡   17:34:04.302|ethminer  Terminate worker 500 ms
min/mean/max: 0/0/0 H/s
inner mean: 0 H/s
Phoning home to find world ranking...

I have the DAG file generated and everything should be set up (I tried to mine setting a number and it did report hashes per second and stuff). So I'm not sure if the -M switch is not working properly or I'm doing something wrong, and I need the mhash value so I don't mess it up and end up losing money.

Thank you.


texts: Will Ethereum 2.0 support light-clients?

texts: I am new to Ethereum, and I am trying to understand how different eth2 will be from eth1 in terms of connecting to the network and performing tasks. For example, in eth1 we don't need to be miners to connect to the network and submit transactions. We can simply use Geth's ethclient to connect to the Infura gateway. By contrast, I haven't been able to find any information about this kind of light-clients designed for eth2. Will eth2 demand each client to participate as a full beacon node/validator? Or will it be possible to connect to the shard chains directly using ethclient in some future release?


texts:
I have the following function and don't want to manually sign the transaction every time it's called, how would I go about setting up a way of signing this transaction with an object. I've seen sendRawTransaction and account.signTransaction but can't figure out a way to implement these in my issue.

this.contractObject = this.contractObject = {from: this.account, gas:300000};

this.contract.methods.createCountry(arg1, 1rg2, arg3).send(this.contractObject, (err, res) => {
                if (err) {
                    throw err;
                } else {
                    console.log(res);
                }
            })

The following function gets added in a batch, I don't know if this will matter.


texts:
Is it in Solidity possible to label a function, so that just the contact owner can call it? Or how could I do it?

I want to achieve something like this but in easy:

contract MyContract {
    address public owner;

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

    function ownerOnly() public view returns(uint) {
        if(owner != msg.sender) throw;

        //return some private attributes which just the owner should see
    }
}


texts: How can I pass instance of provider and contract to all of my React components?

texts:
I have done the hardhat greeting tutorial found here and it was very helpful. To continue learning, I am building a slightly more advanced project that uses multiple react components. One thing that has me stuck is how to more efficiently access the user's wallet to interact with the network without having to add several lines of code in each component that connects to the user wallet and creates an instance of the provider and an instance of the contract.
My current code/workflow is to:

check if a wallet is installed
If a wallet is installed, invoke the RPC method
window.ethereum.request({method: 'eth_requestAccounts'});
create an instance of the provider,
provider = new ethers.providers.Web3Provider(window.ethereum);
create in instance of the contract,
contract = new ethers.Contract(contractAddress, <yourContract>.abi, provider);
interact with the contract, access its available methods, etc..

It seems like doing this for every component is not efficient. I tried passing the above as props into my components, but I did not have any success.
I've seen a few libraries around that abstract this out and help, but I really want to know how to do it before I rely on a library. How are folks currently doing this? I imagine there is a generic workflow that can be followed when building a react dapp that uses multiple components and requires access to the user's wallet.
Does anyone have resources or pointers? I checked docs at ethers, metamask, hardhat, I've googled but I'm just not finding a comprehensive resource that covers this aspect.


texts: Is there a way to view or otherwise verify a contract's source code?

texts: In token sales usually the source code for the contract is published. Is there a way to verify whether the published code is actually deployed in the given address?


texts:
I tried decompiling the TheDAO v1 bytecode with disasm and it seems to fail for me. I entered the TheDAO bytecode here and found that the last instruction was :

[10836] PUSH16 0xc84ba6bc95484008f6362f93160ef3e5

As you can see the bytecode ends with f3e5 and it seems to ignore the last byte 63. When I remove this last byte from the TheDAO bytecode and try running it through disasm again, it works properly.

Can someone explain what is the purpose of the last byte (63) there?

I am using disasm packaged with ethereum-go in release 1.3.6.

This is the error I get when I run theDAO bytecode through disasm:

<code>...
10819  CODESIZE
10820  PUSH16  => c84ba6bc95484008f6362f93160ef3e5
10837  PUSH4panic: runtime error: slice bounds out of range
goroutine 1 [running]:
panic(0x598e80, 0xc42000c110)
        /usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
        /root/go-ethereum/build/_workspace/src/github.com/ethereum/go-ethereum/cmd/disasm/main.go:45 +0x43e
</code>

And this is the error with the evm disasm v1.6.0 - https://pastebin.com/zx48s5ax


texts: How to create a contract B that calls a library via contract A

texts:
As I understand it, the logic to deploy contract that uses library is as below: supposed that MetaCoin contract use TestLib library

Deploy TestLib library first, then get a library contract address
Get contract bytecodes that links library address by command solc --optimize --bin MetaCoin.sol --libraries "TestLib:<address>"
Deploy MetaCoin contract by the bycodes

The above is the direct way to deploy contract that uses library.

However, how to deploy it in an indirect way? in other words, how to create a contract B that uses a library via contract A? How to link library to contract B?


texts: get event logs and debug trace from eth_call

texts:
I am looking for a way to execute a transaction locally (using local geth/parity node) for simulation only, before actually submitting it to blockchain.

I know that I can use 'eth_call' RPC call and It will return the function's return value, however thats not enough for me, I would like to see the full event logs and the debug trace of that simulated transaction.

is that possible using todays tools?

One other possibility is to modify an implementation of the EVM an execute the call there, but not sure where to start to achieve that..


texts: Truffle Migrations run only if not dry run (different account0 in dry run)

texts:
I noticed that using HDWalletProvider using the account parameter in the migration you get random/unexpected accounts during dryRun. I added a safety line that an address should be as expected but because of dryRun this always fails.

Can I have a condition that code in the migration is only executed if not in dryRun?

Here a minimal example of my migration (truffle.js needs to be configured to use HDWalletProvider and have expected address as account0):

const expected = "0xcFbB1f35EF57b96cA51221a331165fF9B2c828FD";

module.exports = function(deployer, network, account) {

  console.log("This accounts are not from HDWalletProvider on dryRun and are always different");
  console.log(account);

  //this fails even if HDWalletProvider is configured correctly in truffle.js
  if (account[0].toLowerCase() !== expected.toLowerCase()) {
    throw new Error(
      `Unexpected account0: account0=${account[0]} instead of ${expected}`
    );
  }
};


texts: Warning: The use of low level "call" should be avoided whenever possible

texts:
I am writing my own smart contract and I want to call a function from a contract that has already been deployed. The fragment of my code:

function myFunc(address _contractAddress, address _user, uint _price) onlyOwner {
        //... some code ...

        require(_contractAddress.call(bytes4(sha3("func(address, uint256)")), _user, _price));

        //... some code ...
    }

I am using Remix IDE. It shows me this warning:

use of "call": the use of low level "call" should be avoided whenever possible. It can lead to unexpected behavior if return value is not handled properly. Please use Direct Calls via specifying the called contract's interface.

How should I solve this issue? Delegatecall produces similar warning. Maybe there are other ways on how to call other contract's function?


texts:
Not sure what the best approach is to get around this. New to solidity. I've read the complicated 'answers' to this that suggest using structs, arrays, etc. but I can't figure out how to address this. Any help welcome!
Here is the code:
    pragma solidity ^0.7.5;
// "SPDX-License-Identifier: UNLICENSED"

contract myLSCDocVerfReqsts {
    uint256 public docVerfReqstsCount = 0;
    mapping(uint => DocVerfReqst) public docVerfReqsts;

    address owner;

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

    struct DocVerfReqst {
        string _intstitutionId;
        string _clientId;
        string _documentId;
        string _requestDate;
        string _requestType;
        string _requestReasonCode;
        string _statusCode;
        string _clientActionedDate;
    }

    constructor() {
        owner = msg.sender;
    }

    function addDocVerfReqst(
        string memory _institutionId,
        string memory _clientId,
        string memory _documentId,
        string memory _requestDate,
        string memory _requestType,
        string memory _requestReasonCode,
        string memory _statusCode,
        string memory _clientActionedDate
    )
        public
        onlyOwner
    {
        incrementCount();
        docVerfReqsts[docVerfReqstsCount] = DocVerfReqst(
                _institutionId,
                _clientId,
                _documentId,
                _requestDate,
                _requestType,
                _requestReasonCode,
                _statusCode,
                _clientActionedDate
                );
    }

    function incrementCount() internal {
        docVerfReqstsCount += 1;
    }
}


texts:
This my delpoy.js file:

const HDWalletProvider = require("@truffle/hdwallet-provider");
const Web3 = require('web3');
const {abi , bytecode} = require('./compile');
const provider = new HDWalletProvider(
    'december blossom school two brief lunar siren truth purse violin car submit',
    'https://rinkeby.infura.io/v3/737d5964ada94e2a8d812f1414c89c4e'
)
const web3 = new Web3(provider)
async function scan(message) {
    process.stdout.write(message);
    return await new Promise(function(resolve, reject) {
        process.stdin.resume();
        process.stdin.once("data", function(data) {
            process.stdin.pause();
            resolve(data.toString().trim());
        });
    });
}

async function getGasPrice(web3) {
    while (true) {
        const nodeGasPrice = await web3.eth.getGasPrice();
        const userGasPrice = await scan(`Enter gas-price or leave empty to use ${nodeGasPrice}: `);
        if (/^\d+$/.test(userGasPrice))
            return userGasPrice;
        if (userGasPrice == "")
            return nodeGasPrice;
        console.log("Illegal gas-price");
    }
}

const deploy = async() =>{
    const accounts = await web3.eth.getAccounts();
    console.log('attempting to deploy from account',accounts[0])
    const result = await new web3.eth.Contract(abi)
        .deploy({data:'0x' +bytecode ,arguments: ['hii']})
        .send({from: accounts[0],gas: 1500000,gasPrice: await getGasPrice(web3)})
    console.log('contract deployed to', result.options.address);
}
deploy()

Output:

node deploy.js
attempting to deploy from account 0x010Ff624891610c8538824AB6F5AF4abfD1c3bfd
Enter gas-price or leave empty to use 1000000000: 1000000000
Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
D:\github\blockchain\solidity-etherium\index\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { "use strict";var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in
Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_HAS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_HAS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_NODE=ENVIRONMENT_HAS_NODE&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Modu

RuntimeError: abort(Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!). Build with -s ASSERTIONS=1 for more info.
    at process.abort (D:\github\blockchain\solidity-etherium\index\node_modules\solc\soljson.js:1:14506)
    at process.emit (events.js:189:13)
    at emitPromiseRejectionWarnings (internal/process/promises.js:119:20)
    at process._tickCallback (internal/process/next_tick.js:69:34)


texts: Which RPC command does web3.js use to call into an arbitrary smart contract function?

texts:
I am trying to duplicate some of the function of web3.js in C++. I don't really know much javaScript. I can see how the code calls into simple RPC calls such as eth_getBlockByNumber or eth_getTransactionByHash. That's easy enough.

I can't figure out how web3.js calls one of the functions on a smart contract though. For example, how does it call a function like an ERC20 token getTotalSupply?

I'm not looking for Javascript code explain how to use the capability, but instead the code that implements the functionality.


texts: Api do not return response with promise handling, works without it

texts:
I have already deployed ethereum private blockchain network on linux and on windows 10, but api's do not return response.
For example

contract.methods.freezeAccount(address,tempStatus).send({from:'042b1b16eccb6c6bafdceaafea5e9e117990feef'}).then((result)=>{
                        res.send('Account Frozen:'+' '+address+' '+tempStatus);
                }).catch((error)=>{
                        res.send("Invalid Address");
                })

It does get executed but it is not returning response.

Using this to interact with api from console.

curl -v http://10.200.10.64:3000/freezeAccount/0x191e6cf5f81c9a6864c4e157fadde3c94967e321/false
*   Trying 10.200.10.64...
* TCP_NODELAY set
* Connected to 10.200.10.64 (10.200.10.64) port 3000 (#0)
 GET /freezeAccount/0x191e6cf5f81c9a6864c4e157fadde3c94967e321/false HTTP/1.1
 Host: 10.200.10.64:3000
 User-Agent: curl/7.55.1
 Accept: */*

Following works

contract.methods.freezeAccount(address,tempStatus).send({from: '0x042b1b16eccb6c6bafdceaafea5e9e117990feef'}, (error, transactionHash) => {
                        if(!error)
                        res.send('Account Frozen:'+' '+address+' '+tempStatus);
                        else
                        res.send("Invalid Address");
                });

But it throws following nodejs warning on console

(node:11200) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11200) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


texts: MEW - Is it possible to generate transactions for "Contracts" offline?

texts: I am trying to use MEW on an offline computer under the tab "Contracts". Is this possible ? When I try it, I get to the final step where the pop up box lets me hit the "Generate Transaction" button, but then nothing happens. Any ideas ? If I am on an online computer, the transaction generates fine. But I don't want to expose my private key online. Thanks in advance.


texts: Why does ERC721 have transferFrom and safeTransferFrom?

texts:
ERC721 has both safeTransferFrom and transferFrom, where safeTransferFrom throws if the receiving contract's onERC721Received method doesn't return a specific magic number. This is to ensure a receiving contract is capable of receiving the token, so it isn't permanently lost.
But why would transferFrom exist too when it doesn't have this check? My only guess it to make ERC721 compatible with ERC20, which has a transferFrom method with the same signature. However the semantics of the method in each standard are different (the uint256 in ERC20 refers to the value, whereas in ERC721 it refers to the tokenID) so compatibility there seems misleading.
What am I missing?


texts: How to Issue /Mint / Generate additional tokens? Contract is mintable

texts:
I have Token on ropsten network (https://ropsten.etherscan.io/token/0x975FB1824F82E446DD3F5c4cb04474468ED7d878) which is Mintable with initial supply of 10B and Mintable Cap up to 50B.

My ether account (owner) has only 10B, I now want to start MINTING/GENERATING additional tokens, let's say add 20B more tokens.

How do I do that?

[1] some important codes of my contract:

   constructor() public {
           name = "PPT";
           symbol = "PPT";
           initialSupply = 10000000000;
           totalSupply_ = initialSupply * 10 ** uint(decimals);
           balances[owner] = totalSupply_;
           mintCap = 50000000000;
           emit Transfer(address(0), owner, totalSupply_);
       }

[2] some important codes of my contract:

    function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
           require(mintCap >= totalSupply_.add(_amount));

           totalSupply_ = totalSupply_.add(_amount);
           balances[_to] = balances[_to].add(_amount);
           emit Transfer(address(0), _to, _amount);
           return true;
       }


texts: How to implement variable interest rates efficiently

texts:
If a smart contract wants to pay interest on a balance of a user that's pretty much straight forward. You record the balance and the timestamp when a token was deposited and when the token is withdrawn you apply the interest rate on top of the balance using the current timestamp.
But what would be an efficient way to set different interest rates manually? Let's say the interest rate is 2% after a few months it's increased to 5% and after a while that it's lowered to 3% again. My current approach would be to have an array of timestamps/interest rates and when withdrawing I iterate through that array and apply the interest rates for these certain time periods. But I know that iterating through unbounded arrays should be avoided, as this could result in high gas usage over time and worst case lock all withdrawals due to running out of gas.
Is there another approach I could take to apply variable interest rates upon a withdrawal?


texts: Why is my proofOfWork() working on every nonce?

texts: I am running proof of work function from my deployed contract in ethereum wallet by providing any random number as nonce. As per my understanding the PoW() shouldn't work on every nonce, but in my case everytime the transaction is getting executed ( PoW works for every nonce ). How am I verifying that it is working everytime - by monitoring the balance of msg.sender, difficulty and currentChallenge parameters. Please correct me if I'm wrong at any point , and suggest a solution or an explanation as to what's happening.


texts: Error trying to swap through balancer pool

texts:
I am trying to exchange tokens through Balancer pools through the swapExactAmountIn function, and I have encountered some issues. Whilst executing the function on a big pool such as the WETH / DAI one, the trade executes fine. On the other hand, executing the function on a pool with less liquidity will revert without giving an error. MinAmountOut and maxPrice parameters were set correctly.
Why can't i swap in such pools?
Thanks


texts:
I am trying to understand smart contracts mappings.

Imagine I have smart contract that can create an object "car" and store in its mapping. This object has parameter like "tires" with black value. Meanwhile i have a function, in that same smart contract, that can change the tires from black to blue. Now in the mapping this car will have tires blue. So the mappings only store the latest state of the car? And if I want to access all the modifications the car suffered? Should I change the mapping from storing "cars" to store "car modifications"? If a car had like 1 million changes would that be a viable solution? If I stay with storing "car" how can i access to all the modifications it suffered?

Also, where mappings are stored?

Thanks in advance


texts: Parity Chain Spec - Require More GPU RAM?

texts: Is there any setting on a Parity chain spec file that would allow the chain to require more than 1GB RAM to start?  or to change the rate of increase per epoch?  This would make a private blockchain more ASIC resistant since by default it will start at 1GB even though on mainnet a 4GB card is a good minimum.


texts: Unable to unlock account before deploying contract to rinkeby

texts:
Each time i try to unlock my account w/ password i get the error:

Fatal: Failed to unlock account 0x1288AB0bf7FE0Ad09d7f28bd4Ab2C06332c625a2 (no key for given address or file)

my geth command is: geth --rinkeby --rpc --rpcapi db,eth,net,web3,personal --unlock="0x1288AB0bf7FE0Ad09d7f28bd4Ab2C06332c625a2"

When testing this same information on myetherwallet.com and the rinkeby testnet w/ my created password I am able to access my account without a problem.

truffle.js

 module.exports = {
  networks: {
    development: {
      host: 'localhost',
      gas: 6000000,
      port: 8545,
      network_id: '4000'
    },
    rinkeby: {
      host: "localhost", // Connect to geth on the specified
      port: 8545,
      from: "0x1288AB0bf7FE0Ad09d7f28bd4Ab2B06332e625a2",
      network_id: 4,
      gas: 4612388
    }
  }
}

Is there any step i'm missing here for deploying my contract to the testnet?


texts: Web3js - Cannot read property deployed()

texts:
My smart contract was parsed via truffle compile to the following json file:

{
  "contractName": "CryptoSportsToken",
  "abi": [
    {
      "constant": true,
      "inputs": [],
      "name": "promoCreatedCount",
...

The file can be found here:

I am running the following web3 code for my frontend:

App = {
  web3Provider: null,
  contracts: {},

  init: function () {
    return App.initWeb3();
  },

  initWeb3: function () {

    // Is there an injected web3 instance?
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
    } else {
      // If no injected web3 instance is detected, fall back to Ganache
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {

    $.getJSON('CryptoSportsToken.json', function (data) {
      // Get the necessary contract artifact file and instantiate it with truffle-contract
      var CryptoSportsTokenArtifact = data;
      App.contracts.CryptoSportsToken = TruffleContract(CryptoSportsTokenArtifact);

      // Set the provider for our contract
      App.contracts.CryptoSportsToken.setProvider(App.web3Provider);

    });

    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.btn-create', App.createPerson());
  },

  createPerson: function () {
    var cryptosportInstance;

    console.log("App: \n");
    console.log(App);
    console.log("App.contracts: \n");
    console.log(App.contracts);

    console.log("###################")
    console.log(App.contracts.CryptoSportsToken)//returns undefined

    App.contracts.CryptoSportsToken.deployed().then(function (instance) {
      cryptosportInstance = instance;

      console.log(cryptosportInstance)

      var owner = $('#owner').val();
      var name = $('#name').val();
      var price = $('#price').val();

      return cryptosportInstance.createPromoPerson(owner, name, price).call();
    }).catch(function (err) {
      console.log(err.message);
    })
  },
};

$(function () {
  $(window).load(function () {
    App.init();
  });
});

My App.contracts object looks like the following:

It seems to me that it is still undefined. If I console log         console.log(App.contracts.CryptoSportsToken) I get undefined back.

I tried to redeploy the contract, which was done successfully:

Any suggestions what I am doing wrong?

I appreciate your replies!


texts: How to get transaction hash of a function call from web3?

texts:
Lets say I use web3 to call foo.bar() like so:

var foo = await Foo.deployed();
var result = await foo.bar();

If I console.log(result) I just see something that says [Object object]

How can I get the transaction hash of the function call? I'd like to be able to keep track of its status. e.g. failed, pending etc.

Thanks!


texts: Difference between security deposit and stake in Casper?

texts: Is the security deposit equal to the amount of staked ETH, or is the deposit a separate thing?


texts: I just transferred $40 ethereum to cold wallet. Gas fees was over$30. 60% of the transfer. Can anyone tell me what happened?

texts: Gas fees of $30 on a $40 transfer to cold wallet


texts:
I updated from 1.5.7 to 1.5.8 and now all my functions return 0.

Before you ask, yes the functions I am calling don't modifier the blockchain.

I tested both my contract and this simpleStorage code:

pragma solidity ^0.4.2;

contract simpleStorage {
    uint storedData = 4;

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

    function get() constant returns (uint retVal) {
        return storedData;
    }
}

Here is my geth command:

geth --dev --mine --rpc --rpccorsdomain "*" --datadir dev

The get() function should return 4, but it always returns 0 in versions 1.5.8 and 1.5.9

Works perfectly fine in 1.5.7 with the same compiler version.

Same results in both Linux and Windows.


texts: What are the changes to be included with Constantinople fork?

texts:
Recently it was announced that the next hard fork of the Ethereum network mainnet will be at block 7,080,000. From more recent estimates it will occur around 2019-01-15 18:11:20 UTC.

So what are the new changes that will be after the Constantinople fork?


texts:
I am trying to play around enums in solidity, during which I came across following questions--

  Is it possible convert enum members to string??

I am trying to get enum members and convert them to string, It always returns integer ie. position of member,
following is the code snippet

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;

    function getFirstNumber(){
         number=Numbers.zero; //works fine
         uint num=uint(Numbers.zero);//works fine
         string stringNum=string(Numbers.zero);// throws error
    }
}

is it possible to convert them to strings, by using any other approach.

  Is it possible to get enum members by using index??

Can we get enum member by using the index / position of the member in enum
following is the code snippet I am trying.

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;
    function getByIndex(int position){
         number=Numbers.zero; //works fine

         //tried somthings like
         number=Numbers[0];//throws error
         number=Numbers.get(position);// throws error
    }
}

Is this possible to get them using position

  Is it possible to check existence of members using string??

I need to check that the provided string exist in the enum, following is the code snippet I am trying

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;
    function checkIfExist(string member) returns(bool exists){

         //tried somthings like

         for(uint i=0;i<Number.length;i++){
            if(string(Number[i]==member){ //throws error
                return true;
            }
            else{
                exists=false;
            }
         }

         //also tried
         uint flag=Number.member;//throws error
         if(flag>0){
              return true;
         }
    }
}

is it possible to do this by any approach


texts: How contract owner can interact with smart contract?

texts:
I've created a smart contract with ERC20 standards, I am using Ethereum TestRPC, Web3js and remix along with ABI/contract address to interact with contract functions. But I have created a modifier inside contract and applied to few functions (like functions start and stop to start/stop contract any time).

Anyone can interact with my contract using above tools, but my question is how can I specify that I'm the admin/owner of contract, So I can call Start and Stop functions?

Any help would be appreciated.


texts: web3 trying to connect to the rinkeby testnet

texts:
I've installed the mist wallet, connected the rinkebytestnet and transferred  3ETH to myself from the faucet

web3 is defined like so

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
}

setup a meteor app and trying to show the balance using web3

  var my_test_address = "0x269999b8dC883628ed7EE7aaAdD498e50C164905";
  web3.eth.getBalance(my_test_address, 'latest',
    function (err, res){
      console.log('err');
      console.log(err);
      alert(res)
    }
    )

the alert shows 0

any ideas ?


texts: How do I get Method of a smart contract deployed via Instance in Solidity

texts:
Is it possible to get the method of a contract deployed via instance. This is what I did and I am getting an error when I try calling the method from the RegistryLogic contract.

Registry registry = bioreg.SaveLandDetail(_OwnerAddr,_regAddr,_ReferenceCode,_Longitude)
different number of components on the left hand side than on the right hand side

RegistryLogic.sol

import "./ExternalStorage.sol";
import "./Registry.sol";

contract RegistryLogic is ExternalStorage{

    mapping (bytes32 => Registry) private _Registry;
    mapping (bytes32 => Details) private _Detail;
    mapping(address => properties) property;
    struct properties{
        Registry[] assets;
        }

function bioDataReg(
        address _OwnerAddr,
        string memory _FamilyName,
        string memory _FamilyRep
    )
    returns(address, Registry)
    {
        Registry _bioRegistry = new Registry(
            _OwnerAddr,
            _FamilyName,
            _FamilyRep);
        property[_OwnerAddr].assets.push(_bioRegistry);
            return (_OwnerAddr, _bioRegistry);
    }

function Registration(
        address _OwnerAddr,
        address _regAddr,
        Registry _bioRegistry,
        bytes32 _ReferenceCode,
        bytes32 _Longitude,
        bytes32 _Latitude) public
        returns(bool) {
        Registry bioreg = property[_OwnerAddr].assets[0];
        Registry registry = bioreg.SaveLandDetail(_OwnerAddr,_regAddr,_ReferenceCode,_Longitude, _Latitude)

ExternalStorage.sol

contract ExternalStorage{

    //Variables
    address[] public Registry;
    mapping(address => profiles) profile;
    bioData public biodataDetails;
    landDetails public land;

    //profile of a client
    struct profiles{
        uint[] assetList;
        }

    //BioData Details
    struct bioData{
        address OwnerAddr;
        string FamilyName;
        string FamilyRep
    }

    //Land Details
    struct landDetails{
        address OwnerAddr;
        address regAddr;
        bytes32 ReferenceCode;
        bytes32 Longitude;
        bytes32 Latitude
    }

 }

Registry.sol

pragma solidity ^0.5.0;

import "./ExternalStorage.sol";

/**
 * @dev Land Registry Contract module.
 *
 * This module is used to create instance of registry contract.
 */

contract LandRegistry is ExternalStorage {

    constructor(
        address _OwnerAddr,
        string memory _FamilyName,
        string memory _FamilyRep
    )public {
        biodataDetails.OwnerAddr = _OwnerAddr;
        biodataDetails.FamilyName = _FamilyName;
        biodataDetails.FamilyRep = _FamilyRep
    }

    function SaveLandDetail(
        address _OwnerAddr,
        address _regAddr,
        bytes32 _ReferenceCode,
        bytes32 _Longitude,
        bytes32 _Latitude
    ) external
    {
        land.OwnerAddr = _OwnerAddr;
        land.regAddr = _regAddr;
        land.ReferenceCode = _ReferenceCode;
        land.Longitude = _Longitude;
        land.Latitude = _Latitude
    }

    function FamilyDetails()
        external view returns(
            address,
            string memory,
            string memory,
            string memory,
            string memory
        )
    {
        return (
            biodataDetails.OwnerAddr,
            biodataDetails.FamilyName,
            biodataDetails.FamilyRep,
            biodataDetails.FamilyRep_HouseAddress,
            biodataDetails.FamilyRep_Mobile_No
        );
    }

    function RegistryDetails()
        external view returns(
            address,
            address,
            bytes32,
            bytes32,
            bytes32
            ) {
        return (
            land.OwnerAddr,
            land.regAddr,
            land.ReferenceCode,
            land.Longitude,
            land.Latitude,
            );
    }

}


texts: Blockchain.info transactions missing in Ethereum wallet

texts:
I used blockchain.info to received  ETH when their Ethereum wallet was in beta. The transaction was on August 22 and 30, 2017. I was able to see the ETH in my account on their website back then, and the transaction for it also. I checked again a couple of times and it was still ok. But on October 27, when I checked again the ETH was gone. My account show 0 ETH, and no transactions also.

After some researching I noticed that the Ethereum address shown on their website is different from the address when I received the coin. I think they might have made some update that reset my private key and address.

I have sent lots a requests to support but they just keep telling me how to export my private key without answering if my key or address was changed or not. I tried to ask my question again but they haven't replied back for many days. They just stopped answering like this for almost a week once, I had to create a new requests to ask them to answer.

These transactions are lost in my wallet:

augustus 30: https://etherscan.io/tx/0xe230bed43032d667627ec999029b6b46030c643687bc5181ef318708f68158a4

augustus 22: https://etherscan.io/tx/0x7893bc6588d67a5c356997cc4430de736aaf597548004dd367038beae2aedc7b

I have seen an other users (like Duy Thai) having the same problem with blockchain.info. but his post was "put on hold" off topic...

Please contact me if you are facing these same problems with blockchain.info

Many thanks,


texts:
Its a bit of a long question...
I am using Go to deploy a Smart Contract using the following code:

client, err := ethclient.Dial("http://localhost:8545")
if err != nil {
    errorhandler.HandleErr(err, 1)
}

privateKey, err := crypto.HexToECDSA(hexKey)

if err != nil {
    errorhandler.HandleErr(err, 2)
}

publicKey := privateKey.Public()

publicKeyEcdsa, ok := publicKey.(*ecdsa.PublicKey)

if !ok {
    errorhandler.HandleErr(errors.New("pub key not of type ecdsa.PublicKey"), 3)
}

fromAddr := crypto.PubkeyToAddress(*publicKeyEcdsa)
nonce, err := client.PendingNonceAt(context.Background(), fromAddr)

if err != nil {
    errorhandler.HandleErr(err, 4)
}

gasPrice, err := client.SuggestGasPrice(context.Background())

if err != nil {
    errorhandler.HandleErr(err, 5)
}

auth := bind.NewKeyedTransactor(privateKey)
auth.Nonce = big.NewInt(int64(nonce))
auth.GasLimit = uint64(4700000)
auth.GasPrice = gasPrice

address, tx, instance, err := eddns.DeployEddns(auth, client)

if err != nil {
    errorhandler.HandleErr(err, 6)
}

_ = instance
return address.Hex(), tx.Hash(), auth

The above code completes successfully and I get a contract address (as a hex) and transaction hash.

I then use the hex address returned by the above function to load the contract like this:

client, err := ethclient.Dial(rawurl)

if err != nil {
    errorhandler.HandleErr(err, 7)
}
address := common.HexToAddress(hexAddr)
instance, err := eddns.NewEddns(address, client)

if err != nil {
    errorhandler.HandleErr(err, 8)
}

return instance

The above code complete successfully as well. No errors are thrown and I get the instance returned.

I then try to query my smart contract like this:

ip, err := contract.GetIp(nil, []byte(domain), tld, rType)

This is a function call and not a transaction so it should work. But I get an error thrown which is No contract code at give address

I am deploying to a private Ethereum network which I bring up using docker-compose up. The docker-compose.yml file is a bit long but I will show the Dockerfile of the node which I connect to at localhost:8545:

FROM ubuntu:xenial

RUN apt-get update \
     && apt-get install -y wget software-properties-common \
     && rm -rf /var/lib/apt/lists/*

WORKDIR "/root"

RUN add-apt-repository -y ppa:ethereum/ethereum

ARG binary
RUN apt-get update \
     && apt-get install -y ethereum

ARG password
ARG privatekey
RUN echo $password > ~/.accountpassword
RUN echo $privatekey > ~/.privatekey
ADD ./genesis.json ./genesis.json
RUN geth init genesis.json
RUN geth account import --password ~/.accountpassword  ~/.privatekey

ENV address=""
ENV bootnodeId=""
ENV bootnodeIp=""

CMD exec geth --bootnodes "enode://$bootnodeId@$bootnodeIp:30301" --networkid "500" --verbosity=4 --rpc --rpcaddr "0.0.0.0" --rpcapi "eth,web3,net,admin,debug,db,personal" --rpccorsdomain "*" --syncmode="full"

EXPOSE 8545
EXPOSE 30303

If the entire docker-compose.yml file is needed I can provide it.

This works perfectly when using the Ganache test network. No errors are thrown and I can successfully query the smart contract. Its when I try to interact with the private Ethereum network, I run into problems.

Thanks.


texts: Syncing events history for specific addresses, possible?

texts:
I am writing software that needs the full history of events but I only need it for a certain contract address, which I would guess is a very common use case for app developers.

Is there a way I can sync (with parity ideally but geth if need be) to only that specific history and so hopefully speed up the process of syncing? It takes a hours to a day to sync depending on gap in between last sync and now if you grab the full history for everything.

Thanks.


texts: Installing web3.py from source, Command "python setup.py egg_info" failed with error code 1

texts:
Trying to install web3.py from source and getting this error when doing a pip install -e . inside the web3 directory.

  RuntimeError: Format missing, but need one (identified source as text as no file with that name was found).

  Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/

Reference: https://pypi.python.org/pypi/web3/3.16.2

Output:

$ pip install -e .
Obtaining file:///Users/joeyz/Projects/Eth/web3.py
Collecting cytoolz>=0.8.2 (from web3==4.0.0b2)
  Downloading cytoolz-0.9.0.tar.gz (443kB)
    100% |████████████████████████████████| 450kB 2.1MB/s
Collecting ethereum-abi-utils>=0.4.3 (from web3==4.0.0b2)
  Using cached ethereum-abi-utils-0.4.7.tar.gz
Collecting ethereum-keyfile>=0.3.0 (from web3==4.0.0b2)
  Using cached ethereum-keyfile-0.3.1.tar.gz
    Complete output from command python setup.py egg_info:
    Maybe try:

        brew install pandoc
    See http://johnmacfarlane.net/pandoc/installing.html
    for installation options
    ---------------------------------------------------------------

    zip_safe flag not set; analyzing archive contents...
    pypandoc.__init__: module references __file__

    !!! pandoc not found, long_description is bad, don't upload this to PyPI !!!

    Installed /private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/.eggs/pypandoc-1.4-py2.7.egg
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/setup.py", line 33, in <module>
        'Programming Language :: Python :: 3.5',
      File "/Users/joeyz/Projects/Eth/web3.py/venv/lib/python2.7/site-packages/setuptools/__init__.py", line 129, in setup
        return distutils.core.setup(**attrs)
      File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "/Users/joeyz/Projects/Eth/web3.py/venv/lib/python2.7/site-packages/setuptools/dist.py", line 333, in __init__
        _Distribution.__init__(self, attrs)
      File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 287, in __init__
        self.finalize_options()
      File "/Users/joeyz/Projects/Eth/web3.py/venv/lib/python2.7/site-packages/setuptools/dist.py", line 476, in finalize_options
        ep.load()(self, ep.name, value)
      File "/private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/.eggs/setuptools_markdown-0.2-py2.7.egg/setuptools_markdown.py", line 22, in long_description_markdown_filename
        output = pypandoc.convert(markdown_filename, 'rst')
      File "/private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/.eggs/pypandoc-1.4-py2.7.egg/pypandoc/__init__.py", line 66, in convert
        raise RuntimeError("Format missing, but need one (identified source as text as no "
    RuntimeError: Format missing, but need one (identified source as text as no file with that name was found).

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/t2/g8zfp3jd5y388nvcx5_f9qm00000gn/T/pip-build-AjPzos/ethereum-keyfile/


texts: What is the difference between writing emit in an event and not using emit?

texts:
For example, event CoinTransfer(address sender, address receiver, uint amount);

What is the difference between CoinTransfer(msg.sender, receiver, amount); and emit CoinTransfer(msg.sender, receiver, amount);


texts: Ethereum web3 js contract functions not working but they work on the remix online

texts:
I have the following solidity contract code.

pragma solidity ^0.4.18;

contract Coursetro {

    string fName;
    uint age;

    function setInstructor(string _fName, uint _age) public {
       fName = _fName;
       age = _age;
    }

    function getInstructor() public constant returns (string, uint) {
       return (fName, age);
    }
}

Running it on remix ide online it works very well and can set Instructor and get Instructor also, however when I try the two functions from a UI using web3js am not sure if it works since the

Coursetro.setInstructor("Name",34)

in console of browser displays the following in terminal "Where the testrpc is running"

Transaction: 0x58c224f215b33ccf5cc89aa63801c602dd1223726fcd297c7ca2ccf7295f17da  Gas usage: 22360 Block Number: 5  Block Time: Thu Dec 14 2017 15:29:22 GMT+0000 (UTC)

but on running

Coursetro.getInstructor()

returns

(2) ["", e]

And from where am learning from the tutor says it should return

(2) ["Name", 34]

Here is my js code which is in an index.html file but wont include the html content since I do not see its relevance

<script>
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            // set the provider you want from Web3.providers
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        }

        web3.eth.defaultAccount = web3.eth.accounts[0];

        var CoursetroContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_fName","type":"string"},{"name":"_age","type":"uint256"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructor","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]);

        var Coursetro = CoursetroContract.at('0x51b126b8d96feaa77cef03fb0e64f8ec45339958');

        console.log(Coursetro);
    </script>

Mind you this is not the only one, I have tried another contract for voting and it works perfectly on the remix ide online but results fail on the web3 js UI part, suggesting its something am doing wrong but I cant seem to know what it is?


texts: Ethereum without Gas Fees for Transactions

texts:
We have been working on Launching One of the most stable coin on Ethereum Network. And as part of strategy we want to get rid of Transaction fees for every coin transfer between wallets. With Ethereum we can control, make it 0, but then it would lead to dilemma of no transaction validation on Ethereum Network. We are looking doing some research and seeking help from experts in the community.

To have all features of Ethereum Blockchain, shall we customise Ethereum Blockchain Code and launch our public network with no GAS and Miners? Like Quorum did for Private Permission Network. Or any other way we can achieve this? Just to make sure, our system will have some complex Smart Contracts so we cannot choose network like Stellar or similar.

Any hint with some guidance will be appreciated.


texts:
After running for a bit I always get  this with the latest ethereumwallet --fast and latest ubuntu:

[2017-07-01 17:00:30.037] [ERROR] ipcProviderBackend - Send request failed Error: Unable to connect to socket: timeout
    at Timeout.setTimeout (/opt/Ethereum Wallet/resources/app.asar/modules/sockets/base.js:97:43)
    at tryOnTimeout (timers.js:232:11)
    at Timer.listOnTimeout (timers.js:202:5)
[2017-07-01 17:00:30.080] [INFO] Sockets/4 - Connect to {"path":"/home/user/.ethereum/geth.ipc"}
[2017-07-01 17:00:30.081] [WARN] Sockets/4 - Connection failed, retrying after 1000ms...
[2017-07-01 17:00:31.081] [WARN] Sockets/4 - Connection failed, retrying after 1000ms...
[2017-07-01 17:00:32.082] [WARN] Sockets/4 -


texts: Could event watch() traverse from latest block number(tail) to head?

texts:
In general, I assume events traverse from smaller to larger block number.

Example:

contractDeployedBlockNumber = 10000
fromBlock: contractDeployedBlockNumber, toBlock: 'latest'

[Q] Could event watch() traverse from 'latest' block number through 0th block number (or smaller block number)? this is basically reverse traverse operation in order to catch the latest event first and break, this will help to retrieve the latest emitted event as fast as possible.

Smart contract's function keeps a registered users' information and updates it using registerUser() function.

contract Example {
   mapping(address => uint) userLatestEmittedBlocNum;
   function registerUser(string memory userEmail,
                         string memory name,
                         string memory githubUserName) public
       returns (bool success)
   {
       userLatestEmittedBlocNum[msg.sender] = block.number;
       emit LogUser(msg.sender, userEmail, name, githubUserName);
       return true;
   }

   function getUserLatestEmittedBlocNum(address userAddress) public view
    returns(uint)
  {
      if (userLatestEmittedBlocNum[userAddress] != 0)
          return (userLatestEmittedBlocNum[userAddress]);
   }
   event LogUser(address userAddress, string userEmail, string name, string githubUserName);
 }

I can store the block number where the user's information is updated under userLatestEmittedBlocNum[msg.sender] and retrieve the emitted log directly from that block number, but this will cost additional storage and gas usage.

blockReadFrom = Example.functions. getUserLatestEmittedBlocNum(userAddress).call()
my_filter = Example.eventFilter('LogUser',{'fromBlock':int(blockReadFrom),'toBlock':int(blockReadFrom) + 1})

As a results we need to retrieve the latest event for each users for the up-to-date information.

It may be inefficient to iterate from smaller block number to latest block number (that will also get the previous updated events as well), and span range might be very large. Instead, if we could able to scan from latest block number to small block number and break the iteration when we catch the event, it might be faster to find the latest emitted log.

On a smart contract, some information is logged and over time it may updated, hence the latest event is valid. So I want to retrieve the latest event on my smart contract, without start scanning from the much smaller block number, which is time consuming and inefficient. So basically starting from 'latest' block number to smaller block, and break this iteration if I catch the event. Otherwise if I start from smaller block number, no matter what, I have to iterate till the latest block number.

Goal: fromBlock: latest, toBlock: 0

blockNum = 0;
var contract = myContract.LogJob({}, { fromBlock: blockNum, toBlock: 'latest' });
var i = 0;
contract.watch(function (error, result) {
    console.log(i++ + ": " + JSON.stringify(result));
});


texts: Which blockchain would be good for developing fee-free applications?

texts:
I am working on a blockchain project where we are trying to undo the transaction fees from the users completely. The fees is actually bore by other subset of users who earn from the blockchain in some way.
I cannot describe the exact use case, but I will give a similar example,
Let’s say we build a marketplace on blockchain. We want the fees of any transaction to be charged on the seller rather than the customer.
I am new to blockchain space, please help me with this problem.


texts: How mining pools send transactions with 1gwei gas price?

texts: Check this transaction, it is sent by a mining pool with 0.08$ fee, and it is almost mined with in minutes. How is this possible? Current average gas price is 150, that is almost 10$


texts:
Is there any implementation of HMAC-SHA1 or HMAC-SHA256 or any other hashing algorithms for solidity?
I found this but it's not working.


texts: Why is Vitalik Buterin considered the brains of Ethereum even though his Github contributions to the project are negligible?

texts:
As of now Vitalik is the #34 contributor to the main project: https://github.com/ethereum/cpp-ethereum/graphs/contributors

Even in the first year, of commits he is still ranked 23rd: https://github.com/ethereum/cpp-ethereum/graphs/contributors?from=2013-12-22&to=2014-12-22&type=c

Even in pyethereum his contribution is small compared to others: https://github.com/ethereum/pyethereum/graphs/contributors?from=2013-12-15&to=2014-12-14&type=c

Given the above why is Vitalik considered the brains behind Ethereum?


texts: Is it necessary to store transaction data into a database?

texts:
I am wondering if there are no security risks if i store transaction data in a database besides the fact that is stored on the ethereum blockchain.

I am using an API to manage my smart contracts and all the transactions.


texts:
I have an Ubuntu 16.04 instance on Amazon EC2

I can do:

geth console 2>> ~/geth.log
instance: Geth/v1.4.3-stable/linux/go1.6.1
>

Everything looks fine:

> eth.blockNumber
546120

> net.peerCount
13

OK. Great. The blockNumber ticks up as expected.

Now, I'd like to be able to logout and go away and get on with things.

I am using screen

I do Ctrl+A followed by D. I can tail ~/geth.log and I can see the blockNumber incrementing.

I logout. However, when I tail the geth.log file several hours later, it keeps getting stuck:

I0513 05:53:21.227568 eth/downloader/downloader.go:274] Synchronisation failed: no peers to keep download active

The Amazon firewall is wide open. I have ufw running on my instance. It allows port 80, 22 and 443 (IPv4 and IPv6).

I have no idea what's going on. I have spent hours at this.


texts: How to do asynchronous callback in web3j?

texts:
My application is dealing with high speed RPC requests, so it cannot reply on synchronous blocking call to process requests. It wants web3j RPC calls to return tx hash immediately without blocking and invoke callback later after RPC completion. Can web3j do callback as follows as in web3js?

web3.eth.sendTransaction({data: code}, function(err, transactionHash) {
  if (!err)
    console.log(transactionHash); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385"
});


texts: Cannot read property 'deployed' of undefined issue

texts:
I am trying to launch an Election-Dapp.
I have these dependencies installed:
 - Nodejs v9.11.1
 - npm v5.8.0
 - Truffle v4.1.3
 - web3js v0.2
 - ganache-cli

Below is my solidity contract

pragma solidity ^0.4.18;
contract Election {
    //model a candidate
    struct Candidate {
        uint id;
        string name;
        uint voteCount;
    }
    //fetch candidate
    mapping (uint => Candidate) public candidates;
    uint public candidatesCount;
    function Election() public {
        addCandidate("Blockchain");
        addCandidate("Groot");
    }
    function addCandidate(string _name) private {
        candidatesCount++;
        candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
    }
}

Here is my js and Web3 for the Dapp:

    App = {
  web3Provider: null,
  contracts: {},
  account: "0x0",

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    if(typeof web3 !== 'undefined'){
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }
    return App.initContract();
  },

  initContract: function() {
    $.getJSON('Election.json', function(election) {
      //Instantiate a new truffle contract from the artifact
      App.contracts.Election = TruffleContract(election);
      //connect provider to interact with contract
      App.contracts.Election.setProvider(App.web3Provider);
    });
    return App.render();
  },

  render: function() {
    var electionInstance;
    var loader = $("#loader");
    var content = $("#content");

    loader.show();
    content.hide();

    //load account data
    web3.eth.getCoinbase(function(err, account) {
      if(err == null) {
        App.account = account;
        $("#accountAddress").html("Your account: " + account);
      }
    });

    //load contract data
    App.contracts.Election.deployed().then(function(instance) {
      electionInstance = instance;
      return electionInstance.candidatesCount();
    }).then(function(candidatesCount){
      var candidatesResults = $("#candidatesResults");
      candidatesResults.empty();

      for(let i = 1; i <= candidatesCount; i++) {
        electionInstance.candidates(i).then(function(candidate) {
          var id = candidate[0];
          var name = candidate[1];
          var voteCount = candidate[2];

          //render candidate results
          var candidateTemplate = "
" + id + "	" + name + "	" + voteCount + "
";
          candidatesResults.append(candidateTemplate);
        });
      }

      loader.hide();
      content.show();
    }).catch(function(error) {
        console.warn(error);
    });
  }
};

$(function() {
  $(window).load(function() {
    App.init();
  });
});

This is the scrnshot of the issue:

Also I can interact with my contract using truffle console and JS promises like this:

Problem: why is it undefined?

P.S.: if it can help, here is a link to this project on my GitHub:
LINK TO GITHUB

Any help is appreciated, thank you.


texts: Getting the warning Served eth_sendRawTransaction err="already known" on local blockchain with metamask

texts:
The problem: I call a smart contract function on my local blockchain, then I confirm the transaction on metamask and finally the transaction is submitted but the transaction does not get mined.

On the blockchain console I receive the warning below:

WARN [03-26|18:21:48.169] Served eth_sendRawTransaction            conn=127.0.0.1:60092 reqid=1559115320157 t=213.552µs   err="already known"

Instead, when I disable metamask and I send a transaction with the unloacked account then the transaction get mined.

The strange thing that it used to work, I made many operations since yesterday.

Do you have any clue? Thanks!


texts: unable to use testrpc with ethereum wallet

texts:
i am trying to open ethereum wallet with testrpc to quickly test my code.
1) have opened the command prompt and entered cmd "testrpc"
2) opened another command prompt and entered cmd ""Ethereum Wallet.exe" --rpc http://localhost:8545" , this opens ethereum wallet in PRIVATE-NET with fake accounts and ethers .
3) however whenever i try to do a transaction or execute a contract , get error we couldn't estimate gas

please help as i am not able to use testrpc tool . Also while using testrpc which blocks does it sync?


texts: Should I run POW or POS for local Transactions?

texts:
Since prof of Stake is here, and proof of work is in decline, I am trying to figure the best corse of action. I need a local node, Geth node, and I need to be able to post transactions and retrieve balances etc. so to do this, do I need to run a Validator node? or can I run a simple node that doesn't do validating? Also if I do run a Validating node, is it ok to use it for interacting with the blocks, or should I run 2 nodes for this?
To be frank there is a lot of information around and I am suffering Information overload.
I simple want to have a node I can connect to so my servers will have an ethereum end point to post transactions and receive balance and transaction updates. With the possibility that my director may want to stake at some point.
Any suggestions or advice would be welcome.


texts: What information do nodes exchange with each other?

texts:
From my understanding nodes are able to communicate with each other to send and receive information such as newer block info etc...

I would like to understand what those informations are, and why can nodes cannot make RPC call to other nodes.


texts:
Since function owned is public, does it mean anyone can externally call it and own the contract as msg.sender?

contract owned {
    address public owner;

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

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

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


texts: My transaction is pending and it seems like doesnt execute the transaction at all?

texts:
I wanted to transfer ERC20 tokens from MEW to another ERC20 token wallet. It seems like not moving. Now my transaction is pending and it doesn't showing up in myetherwallet as a pending status. Can this transaction be automatically cancelled or I have to do something? (transaction is not showing up in Check TX Status on MEW, please help)

Tx Hash : 0xecf3911df3636c242f48921d241ecb8e313e40361fb6f0dc02c66ebf45a5dc21


texts:
I am pretty new at solidity and I am trying to create a roulette where you can place bets on a color or number and then resolve the bets and receive the amount of currency you won. Currently I am doing it on remix with test ether accounts and I am having problems transferring the winnings for a bet from the contract to the current users address. Any ideas? Thank you in advance.
Also I have noticed when trying to return winnings for just a single bet at a time it doesn't work only for the first win when I launch the app and after that the transfer works.
The error I get when I try:

transact to roulette.spinAll 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.

pragma solidity ^0.5.0;

contract roulette {

    enum BetType { Color, Number }

    struct Bet {
        address user;
        uint amount;
        uint block;
        int choice;
        BetType betType;
    }

    uint public counter = 0;
    int public result;

    mapping(uint => Bet) public bets;
    mapping(int => int) public colors;

    uint public constant NUM_POCKETS = 38;

    uint8[18] public RED_NUMBERS = [
        1, 3, 5, 7, 9, 12,
        14, 16, 18, 19, 21, 23,
        25, 27, 30, 32, 34, 36
        ];

    uint8[18] public BLACK_NUMBERS = [
        2, 4, 6, 8, 10, 11,
        13, 15, 17, 20, 22, 24,
        26, 28, 29, 31, 33, 35
        ];

    function Start() public {
        for(uint i = 0; i < 18; i++) {
            colors[RED_NUMBERS[i]] = 1;
        }

    }

    function makeBet(BetType _betType, int _choice) payable public {
        if(_betType == BetType.Color)
            require(_choice == 0 || _choice == 1);
        else require(_choice >= -1 && _choice <=36);
        counter++;
        bets[counter] = Bet(msg.sender, msg.value, block.number, _choice, _betType);
    }

    function spinAll() public {
        bytes32 random = keccak256(abi.encodePacked(now, msg.sender));
        result = int(uint(random) % NUM_POCKETS) - 1;
        for(uint i = 0; i < counter; i++) {
            resolveBets(i);
        }
        counter = 0;
    }

    function resolveBets(uint id) payable public {
        Bet storage bet = bets[id];
        require(msg.sender == bet.user);
        if(bet.betType == BetType.Color) {
            if(bet.choice == colors[result] && result > 0)
                msg.sender.transfer(bet.amount * 2);       //    < --- This does not work!!!

        }
        else if(bet.betType == BetType.Number)
        {
            if(result == bet.choice)
                msg.sender.transfer(bet.amount * 35);
        }

        delete bets[id];
    }
}


texts: how to create multisign wallet from scratch?

texts:
I am new in creating smart contract
I want to create a multisign wallet from scratch??

I want to create accounts 1st and want to hold private key safely


texts:
I've developed Smart Contracts using Solidity, and then created a front end for them using Web3js. I used Truffle to to get them to communicate. That's how I tried out a couple of Proof of Concepts. I haven't ever deployed anything on the actual Ethereum network.

How do I actually deploy the code I've written on the network ?

What does an Ethereum Client do when I would actually deploy the apps that I've created?


texts: TypeError: Fallback function must be defined as "external"

texts:
function() public payable{

^

pragma solidity ^0.5.0;

import "./EIP20Interface.sol";

contract InitialTokenOfferingIncomeFAIR is EIP20Interface {

    uint256 constant private MAX_UINT256 = 2**256 - 1;
    mapping (address => uint256) public balances;
    mapping (address => mapping (address => uint256)) public allowed;

    string public name;
    uint8 public decimals;
    string public symbol;

    uint price = 0.1 ether;

    function ito(
        uint256 _initialAmount,
        string memory _tokenName,
        uint8 _decimalUnits,
        string memory _tokenSymbol
    ) public {
        balances[msg.sender] = _initialAmount;
        totalSupply = _initialAmount;
        name = _tokenName;
        decimals = _decimalUnits;
        symbol = _tokenSymbol;
    }

    function transfer(address _to, uint256 _value) public returns (bool success) {
        require(balances[msg.sender] >= _value);
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        emit Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        uint256 allowance = allowed[_from][msg.sender];
        require(balances[_from] >= _value && allowance >= _value);
        balances[_to] += _value;
        balances[_from] -= _value;
        if (allowance < MAX_UINT256) {
            allowed[_from][msg.sender] -= _value;
        }
        emit Transfer(_from, _to, _value);
        return true;
    }

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

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

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

    function() public payable{     *//Fallback problem concerning this function*

        uint toMint = msg.value/price;
        totalSupply += toMint;
        balances[msg.sender]+=toMint;
        emit Transfer(0, msg.sender, toMint);

    }
}


texts: How to set msg.sender when reading data from a MyEtherWallet contract

texts:
The deployed contract has a function as below:

function checkBalance() onlyTrainee constant returns (uint256) {
    return traineeBalances[msg.sender];
}

When I call checkBalance(), it always checks the balance of sender 0x00..00. There is no input field that lets me fill out who I am. In web3, I would accomplish that with checkBalance().call({from: '0x123....'}).

Is there any way to indicate to MyEtherWallet who the caller (msg.sender) should be?

Note that this is not about setting the sender of a transaction, which of course only works if I have the private key.


texts: Cannot retrieve data from smartcontract during tests

texts:
I am writing truffle tests for my smart contract solidity version 0.4.24. The tests are emitting events to write data to memory through smart contract. But I am unable to retrieve data from functions.

Here's my smart contract functions:

  previousFarmId = 0;

struct Location {
        string latitude;
        string longitude;
        string locationAddress;
    }

    struct Farm {
        uint farmId;
        string farmName;
        Location location;
    }

mapping (uint => Farm) farms;

function registerFarm(string _farmName, string _farmLatitude, string _farmLongitude, string _locationAddress) public {

        previousFarmId = previousFarmId + 1;

        Location memory newLocation = farmLocation[previousFarmId];
        newLocation.latitude = _farmLatitude;
        newLocation.longitude = _farmLongitude;
        newLocation.locationAddress = _locationAddress;

        Farm memory newFarm = farms[previousFarmId];
        newFarm.farmId = previousFarmId;
        newFarm.farmName = _farmName;
        newFarm.location = newLocation;

        emit FarmRegistered(previousFarmId);

    }

    function getFarmInfo(uint _farmId) public view
    returns (uint farmId, string farmName, string latitude, string longitude, string locationAddress) {
        Farm memory returnFarm = farms[_farmId];
        farmId = returnFarm.farmId;
        farmName = returnFarm.farmName;
        latitude = returnFarm.location.latitude;
        longitude = returnFarm.location.longitude;
        locationAddress = returnFarm.location.locationAddress;
    }

Here is the truffle test:

  const farmID = 1;

it("Testing smart contract function harvestGrapes() that allows producer to harvest grapes", async() => {

        const supplyChain = await SupplyChain.deployed();

        await supplyChain.addProducer(producerID, {from: deployerID});

        await supplyChain.registerFarm(farmName, farmLatitude, farmLongitude, farmAddress, {from: producerID});

        const resultFarms = await supplyChain.getFarmInfo.call(farmID);

        console.log('Farm ID: ' + resultFarms[0]);
        console.log('Farm Name: ' + resultFarms[1]);
        console.log('Farm Latitude: ' + resultFarms[2]);
        console.log('Farm Longitude: ' + resultFarms[3]);
        console.log('Farm Address: ' + resultFarms[4]);
}

  Console Logs:

Farm ID: 0
Farm Name:
Farm Latitude:
Farm Longitude:
Farm Address:

  Events emitted during test:

   ProducerAdded(account: <indexed>)
    FarmRegistered(farmId: 1)
    GrapesHarvested(grapesId: 1)


texts: Custom smart contracts transfering tokens

texts:
I have two simple questions.

Does all the smart contracts that creates ERC20 tokens have the same function names like balanceOf and transfer? Or developer select those names as they want?
Lets say i want to be intermediary, i create smart contract, people send me ether and after sometime they claim X tokens from contract. To do that i have to create instance of X tokens contract. When i do that and do transfer function does the X contract see contracts address as a sender or does it see the ones address who interacted with my contract?
Who has to pay gas if contracts communicate with each other?


texts: How to integrate ERC20 token to microjob website?

texts:
I need an api to handle erc20 ethereum token deposits and withdrawals on my microjobs website.

Users should be able to withdraw their earned token automatically when they pay the network fees.


texts:
Using Geth I am reading from a smart contract and a list of addresses is retrieved when outputting to the terminal. These addresses are in byte array format:

fmt.printLn("address", address)
output = address  [16 22 32 12 22 0 0 0 0 0 16 0 0 0 0 0 0 0 0 3]

when I try to convert back to hex I keep coming against the following:

cannot use address (type common.Address) as type string in argument to bytes.NewBufferString

So far, I have tried various different ways to make the conversion but with no luck: string(address[:] etc etc...

Anyone have any clues?


texts: TRANSFER_FROM_FAILED error when trying to swap BCLNC tokens for ETH on Uniswap

texts:
I'm attempting to swap BCLNC tokens for ETH on Uniswap, but I get the following error:

The transaction cannot succeed due to error: TransferHelper: TRANSFER_FROM_FAILED. This is probably an issue with one of the tokens you are swapping.

However, it is clear that other transactions are successful such as this one.
I've attempted to perform a swapExactTokensForETH directly on the Uniswap contract replicating the details such as Path and the correct values for amountIn, to and deadline, but it attempts to charge me an excessive gas fee (over $160), and MetaMask displays the following error:

ALERT: Transaction Error. Exception thrown in contract code.

Any idea what the issue could be here?


texts:
I have a contract like this

pragma solidity ^0.4.24;

import './MyLibrary.sol';

contract A {
  // Do Stuff
}

And I have a factory contract instanciating A contracts

pragma solidity ^0.4.24;

import './A.sol';

contract B {
  mapping(uint => address) instances;
  function newA(uint id) {
    instances[id] = new A();
  }
}

I want to use B as a factory, and A is calling MyLibrary regularly. Is there any way with Truffle migrations to do something like this (deploying MyLibrary on the network, and then linking each A deployed contracts with the library)?
It's easy to link a library to a contract during deployment, but I don't know how to do it dynamically on the blockchain.


texts: When starting a new public ethereum blockchain can I disclose the genesis file?

texts:
I am using the ethereum codebase to create a new ethereum based blockchain.  I don't want to call it a private blockchain because it will be public.

I have been able to set it up, created my own blockchain and all is good.

I am not sure if one can disclose the genesis file or publish it for example to github.

I cannot seem to find any information as to the sensitivity of this file and I cannot find where the public ethereum Genesis file is located to review.


texts: Can a contract be used without its interface?

texts:
Assuming a contract was created with some public variables and several methods.

If the interface and the contract address is not shared, is it possible for other participants in the chain to use the contract methods and view the public variables?

I presume that the address can somehow be found and sending a tx means everyone in the chain knows about it but can they use the contract? If so, how?

Thanks,


texts: Is it possible to run a couple of nodes on the same computer in geth?

texts:
I try to create a local private testnet network of ethereum. It seems like when I run two nodes on the same computer(without vm), it uses the same port and ip address although I set different port for each one of them. Is it possible to run a couple of nodes on the same computer, or should I use a vm for that?
It also showed me that one of the nodes has 8 peers although I set only 2 nodes. how is it possible?

Thank you


texts: Retrieve EOS LINK tokens sent by mistake to Ledger Nano S

texts:
How to retrieve my LINK Tokens sent by mistake to my Ledger Nano S and transfer them to My Ether Wallet.
I cannot see them in my Ledger Live, but I found the transaction in my Etherscan.io

Thank you.


texts: What is the reason for not just issuing a token on the testnet (e.g. Rinkeby) for your token so that Gas costs are free (Rinkeby ETH from faucet)?

texts:
If someone wants a token to be usable and easily transferable between users, without the prohibitive costs of paying for gas every time with real ETH (and thus, money), why not just deploy it on Rinkeby?

You could top up users wallets from the faucet, or have them do it themselves, so they always have enough rinkeby ETH to cover all the transactions they may do (and set high gas prices for speed).

I have tried looking but cannot find any information on why this would not work in practice and would appreciate any help on the issue. Thank you.


texts: Smart Contract Working on Remix but not TestNet

texts:
This question has been asked before. however, those answers did not help me. (of course, I now can't find the "answer" atm) It said that Ropsten (what I was currently using) has fewer miners - or something to that extent, and therefore isn't the best to run smart contract. They recommended Rinkeby. I tried that, but it did not work either :( Currently, all functions work on Remix.

Here' some info about my Rinkeby and Ropsten:

I have two main functions, the first is PickYourNumbers() which allows you to pick numbers, put them into an array, and then displays them on the contract with GetHash(). This one works.

The second is StartTheLotto() which calls the function random(). This function generates... a random number. It calls this function 6 times, setting 6 vars in an array to different random numbers. Lastly, the array is displayed via lottoWinners().

I am guessing it is because I am having the contract/miners do too much? Do you have any recommendations?

    pragma solidity ^0.4.24;

contract EthereumLottery {

    uint[6] array;
    uint[6] winners;
    string warning = "please be sure to bet below 67 for the first 5 balls and 34 for the 6th";
    address owner;    // current owner of the contract
    uint addr = address(this).balance;
    uint nonce = 1;
    uint startTime = now;

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

    function WARNING() public view returns (string memory) {
        return warning;
    }

    function PickYourNumbers(uint8 firstBall, uint8 secondBall,
      uint8 thirdBall, uint8 fourthBall,
      uint8 fithBall, uint8 powerballllll) public {

        if (firstBall <= 66) array[0] = firstBall;
        if (secondBall <= 66) array[1] = secondBall;
        if (thirdBall <= 66) array[2] = thirdBall;
        if (fourthBall <= 66) array[3] = fourthBall;
        if (fithBall <= 66) array[4] = fithBall;
        if (powerballllll <= 66) array[5] = powerballllll;

    }

    function GetHash() public view returns (uint[6] memory) {
        return array;
    }

    function StartTheLotto() public returns (uint[6] memory) {
        nonce++;
        winners[0] = random();
        nonce++;
        winners[1] = random();
        nonce++;
        winners[2] = random();
        nonce++;
        winners[3] = random();
        nonce++;
        winners[4] = random();
        nonce++;
        winners[5] = random();
    }

    function lottoWinners() public view returns (uint[6] memory) {
        return winners;
    }

    function random() private view returns(uint) {

        uint interval = now - startTime;

        bytes32 randomNum = keccak256(abi.encodePacked(interval + nonce + tx.gasprice + addr));

        uint number;
        for(uint i=0;i<randomNum.length;i++){
            number = number + uint(randomNum[i])*(2**(8*(randomNum.length-(i+1))));
        }
        return number % 67;
    }

}

edit:

Rinkeby DAPP Addr: 0x75AB85fB72Ba93c9a9dF23E6FC775b58Dc7f050B

Ropsten DAPP Addr: 0x8bea60c97DC6BD955a614C58e5D0A0fBD12a8593


texts: Do you know online tool for abi encoding?

texts: Is there easy to use online tool to encode ABI parameters to pass verification on etherscan?


texts: Transfer ether between two EOAs without security breaches

texts:
I have this function (is a SC implementing and auction):
/// @notice Register a new participant
/// @param _preferences agent' preferences
function regAgent(uint[] memory _preferences) notOwner onlyBeforeEnd public {
    require(msg.sender.balance - fee >= 0, "You can't pay the fee.");
    require(!registered[msg.sender], "Agent is already registered.");
    Agent memory newAgent = Agent(agents.length, msg.sender, _preferences);
    agents.push(newAgent);
    registered[msg.sender] = true;
    // 1. the agent must pay the fee to participate
    // 2. owner must recieve that fee
}

But I don't know how to do the last part: a participant have to pay a fee to the owner (the entity who deployed the SC). So I'd like to transfer ether from participant' address to owner address. That's all.
Any advice is welcome.


texts: How do I change a variable in a smartcontract (bool)

texts:
Say I have a published smart contract with a variable:

bool public myvariable = true;

Which is used in the contract later on by way of if's which check whether myvariable is true or false.

How do I then change that variable, how do I communicate with the contract and what on earth do I tell it, in order to flip myvariable to false, say?

I suspect that this is a very basic question but the lack (absence?) of true beginners solidity information means I have to ask stupid questions. So far I've been using MEW to publish the contracts, and that has an "interact with contract" facility, offering me an ABI/JSON field to enter, presumably, the communication I wish to have with the contract?

Also, how do I stop just anyone triggering the same change?

Really not sure how to proceed from here. One idea I had was to code it so that the true/false state is flipped when a certain precise value of eth is sent to the contract, by my particular address. The precise amount of eth simply serving as a message of sorts. But I don't think that would "permanently" change the true/false, anyway.

Thanks for any suggestions.


texts: Cannot figure out how to set constructors and ABI for a contract

texts:
So I've been breaking my head over this for the last 2 days. I cannot seem to figure out how to get the constructors and ABI set up properly.
I'm testing smart contracts by copying Sushi contract from here: https://etherscan.io/address/0x6b3595068778dd592e39a122f4f5a5cf09c90fe2#code
And then compiling and deploying on remix: https://remix.ethereum.org/
After I compile and go to the deploy tab and deploy, I don't see anything in the low level functions section here: https://imgur.com/a/XFEvRoE
How do I set the owner, the symbol and all the other fields since they aren't hard coded in the solidity file?
I was also trying to do this on MEW and I deployed using bytecode output from remix and ABI shown on etherscan, but my deployed contract did not have an interface on etherscan to set these fields or show balanceOf method etc.
So how are these arguments passed and at what stage of the process? I've tried to google but can't seem to figure out what I'm missing.


texts: Can't send data to non-contract address using web3 1.0.0 and ganache

texts:
Problem

According to this question, it is possible to send data to a non-contract address in Ethereum.

However, if I run my code which sends ether from the first account to the second account on Ganache, I get this:

  err Error: Returned error: Attempting to run transaction which calls a
  contract function, but recipient address
  0xe7d6a2a1cbed37ee7446d78fd5e6b38aaae3f3b2 is not a contract address

Code

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

const config = require('./config');
const web3 = require('./web3');

const genRawTx = async () => {
    const count = await web3.eth.getTransactionCount(config.accounts[0]);
    const nonce = web3.utils.toHex(count);

    const txValue = web3.utils.toHex(web3.utils.toWei('0.5', 'ether'));
    const txData = web3.utils.asciiToHex('Does this work?');
    console.log('txData', txData);

    const rawTx = {
        nonce: nonce, // Nonce is the times the address has transacted, should always be higher than the last nonce 0x0#
        from: config.accounts[0],
        to: config.accounts[1],
        value: txValue, // The value we are sending '0x16345785d8a0000' which is 0.1 Ether
        gas: '0xEA60', // 0xEA60 is 60,000
        gasPrice: '0x09184e72a000', // 0x09184e72a000 is 10 szabos or 10,000 gwei
        data: txData
    };

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

    web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), (err, data) => {
        if (err) {
            console.log('err', err);
        } else {
            console.log('data', data);
        }
    })
    .on('receipt', console.log);
};

genRawTx();

Tools

node 9.3.0
web3 1.0.0-beta.34
ganache 1.1.0

Is this a bug or I'm missing something?


texts: Since Ethereum is ASIC resistant, what happens when the GPU mining return is less than electricity bill?

texts: If mining return is less than electricity bill, no miners would like to provide their hash power to support the system, what happens to the system then?


texts: send SignTransaction to contract function using web3 + infura + truffle

texts:
contract has an function "addToWhiteList", only owner of the contract can access this function and add user in whitelist.

/**
* @dev Adds single address to whitelist.
* @param trusted Address to be added to the whitelist
*/
function addToWhiteList(address trusted) public onlyOwner {
   require(!whitelist[trusted]);
   whitelist[trusted] = true;

   emit UserWhitelist(true);
}

I am trying to add the user on whitelist from owner account :

// Send Transaction to the Blockchain
function sendTransaction() {
 const functionAbi = Contract.methods.addToWhiteList("0x9DA80947ACf5Fc16299311EdAabc37fF7d201C95").encodeABI()
 console.log(functionAbi);
 var nonce = web3.eth.getTransactionCount("0x61A44075419C4402f6DE631341d875Ece6A3922e");
 var gasPrice = "2";//or get with web3.eth.gasPrice
 var gasLimit = 3000000;
 var ownerPrivateKey = "0x5c9c7e00edc09d0df072c0de7911026a4ab241aa8a5e9f063fb450ba91fbc360";
 var formatedPrivteKey = ownerPrivateKey.substring(2);
 var tx = new ethereumjs.Tx({
   nonce: web3.utils.toHex(nonce),
   gasPrice: web3.utils.toHex(gasPrice * 1e9),
   gasLimit: web3.utils.toHex(gasLimit),
   to: ContractAddress,
   value: '0x00',
   data: functionAbi
 });

 tx.sign(ethereumjs.Buffer.Buffer.from(formatedPrivteKey, "hex"));

 var raw = "0x" + tx.serialize().toString("hex");

 web3.eth.sendSignedTransaction(raw)
  .on('receipt', function(receipt) {
    console.log(receipt);
  }).on("error", console.error);
}

Note : Add web3 : web3 1.0

<script language="javascript" type="text/javascript" src="web3.min.js"></script>
<script language="javascript" type="text/javascript" src="ethereumjs-wallet-0.6.0.min.js"></script>

Init. web3 :

web3 = new Web3(new Web3.providers.WebsocketProvider("wss://ropsten.infura.io/ws"));

.user is not adding in whitelist
when i use console of the browser and call the function "sendTransaction" from console :

sendTransaction()
undefined

after few seconds :

web3.min.js:1 connection not open on send()
u.send @ web3.min.js:1
u.send @ web3.min.js:1
u.removeSubscription @ web3.min.js:1
a.unsubscribe @ web3.min.js:1
(anonymous) @ web3.min.js:1
Promise.catch (async)
g @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ web3.min.js:1
(anonymous) @ web3.min.js:1
connection.onmessage @ web3.min.js:1
web3.min.js:1 Error: Failed to check for transaction receipt:
{}
    at Object._fireError (web3.min.js:1)
    at web3.min.js:1

when i check

Contract.methods.isAddressWhiteList("0x9DA80947ACf5Fc16299311EdAabc37fF7d201C95").call().then(console.log);

it's return false


texts: If external function declarations are saving gas, why aren't we using it for the transfer functions?

texts:
All the source code I could find (to date) has declared transfer, transferFrom, approve, approveAndCall as public and not external.

Although external can be used, what is the reason behind not using it ?


texts:
I run geth with this command

  geth --syncmode "fast" --cache 2048 --datadir /data/ethereum --ws
  --wsaddr 0.0.0.0 --wsorigins '*' --wsapi 'web3,eth,net,db,personal' --rpc --rpcaddr 0.0.0.0

then i subscribe newHeads and recieve {"jsonrpc":"2.0","id":1,"result":"0x30ebfd74dc99548d16b64d23eda6f964"}.But can not recieve any block head.I try to connect infura wss://mainnet.infura.io/ws and recieve new block head.

import websocket
import json
import time
try:
    import thread
except ImportError:
    import _thread as thread

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        ws.send(json.dumps({"id": 1, "method": "eth_subscribe", "params": ["newHeads"]}))
        print("thread terminating...")
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    # ws = websocket.WebSocketApp("wss://mainnet.infura.io/ws",
    ws=websocket.WebSocketApp("ws://127.0.0.1:8546",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Am I wrong ? My geth version is Geth/v1.9.6-stable-bd059680/linux-amd64/go1.13.1.

Thanks


texts:
I am currently attempting to build an Ethereum based wallet service that is online. I am slightly confused as to how each user would separately interact with web3 on the system using the UI. From my approach I would be implementing a Node.js server that hosts web3. From this perspective, how would I separate each users account/wallet individually as well as managing which wallet to update or read from when the user requests such.
My other approach would be to interact with the provider via AJAX.JS and give the UI a more direct interaction with web3.
I am designing a website as my frontend and I want to understand how to properly develop an Ether wallet using JS and Web3.


texts: What is the correct way to access public variable from contract in Truffle: then or standard callback?

texts:
There are some similar posts to this but none seem to be able to solve my problem.

I have a contract deployed with Truffle running with testrpc.

I want to access the value of a public uint variable named gameStatus defined in the deployed contract game variable as such:

uint public gameStatus = 23;

I have found two ways to do this:

game.gameStatus(function(err, res){
    document.getElementById('amt').innerText = res;
});

And using the then operator from Promises.

game.gameStatus().then(function(result){
    document.getElementById('tableamt').innerText = result;
});

The first method never affects the value of 'tableamt' in the HTML. And the second method always yields a value of '0' in the HTML.

The contract in both cases deploys without errors and web3 does not complain.

Any help is much appreciated.

Thanks!


texts: What is the economic behaviour of a uniswap pool as all its members leave?

texts:
I bought some defi tokens using uniswap. As I understand it, my ETH is now part of a pool. The price of the token changes according to a*b=k as people swap in and out of it, or by arbitrage.
Okay, but what if everyone leaves the pool when my back is turned?
What are the economics if everyone leaves one by one and I am the last person left? Is there a risk of getting stuck?


texts: When there is an unexpected hardfork, what is the procedure taken by the core team?

texts:
Imagine Ethereum had a hardfork like this one that Bitcoin experienced.

Ethereum can learn from this and can be prepared to be more efficient during the crisis, minimize panic, minimize other mistakes, etc.  What is the specific procedure and the specific steps taken by Ethereum's core developers and team?


texts: Transaction signing fails Invalid RLP.","data":"RlpExpectedToBeList"

texts:
I'm trying to sign and push a transaction using ethereumjs and Infura. It seems to be working and I'm getting a transaction hash back, but the transaction is not visible on Etherscan, and when I'm trying to push the hash through a service like this I get an error:

Error! Unable to broadcast Tx : {"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid RLP.","data":"RlpExpectedToBeList"},"id":1}

This is the code I'm using:

var Web3 = require('web3');
var web3 = new Web3(new
Web3.providers.HttpProvider('https://ropsten.infura.io/v3/my_api_key'));
var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');

var rawTx = {
    nonce: web3.toHex(1),
    gasPrice: web3.toHex(20000000000),
    gasLimit: web3.toHex(30000000000),
    to:...
    value: web3.toHex(1000000),
    data: '0xc0de',
    networkId: 3
};

var privateKey = '0x...';
var p = new Buffer.from(privateKey.substring(2), 'hex');
var transaction = new tx(rawTx);
transaction.sign(p);
console.log("tx hash = " + util.bufferToHex(transaction.hash(true)));

What am I missing?


texts: Where and how can I set the mining reward?

texts:
I have been searching for a way to reduce the eth reward on a private deployment from 3 to 1.  The best source I have
( Disable block mining reward in private testnet ) is to comment out the miner reward line so that no reward is given to the miner.

How can I set the miner reward to 1 and where does the 3 ETH reward get set?

It got me thinking, what is stopping someone modifying this function to say reward + 1000, recompile and rejoin the network.

func AccumulateRewards(state *state.StateDB, header *types.Header, uncles
[]*types.Header) {
reward := new(big.Int).Set(blockReward)
r := new(big.Int)
for _, uncle := range uncles {
r.Add(uncle.Number, big8)
r.Sub(r, header.Number)
r.Mul(r, blockReward)
r.Div(r, big8)
//state.AddBalance(uncle.Coinbase, r)
r.Div(blockReward, big32)
reward.Add(reward, r)
}
 //state.AddBalance(header.Coinbase, reward)
}