texts: Is there any hardware wallet available for Ethereum?

texts: What are the various available hardware wallets for Ethereum?


texts: How will Ethereum encourage users if their blockchain is not free?

texts:
Once Dapps start to appear, how should an average user accept this model when he/she knows that every information eventually stored on the blockchain costs money (ether-gas)?

Why wouldn't one stick to the system we have now, write as many records as you want to the database with zero cost instead of giving away ether which one day may reach a huge amount of money in FIAT?


texts: How to integrate user tracking into dApp?

texts:
The problem is that it is just me who is working on the project and I have no way to use machine learning, advanced algorithms to detect fraud and prevent abuse of the system.

I was wondering if there is any solution.


texts:
I'm currently trying to understand the Kademlia protocol implemented in Ethereum in order to discover other peers in the network. If I understand these lines correctly, a nodes uses both random addresses as well as his own address as target address. It then sends this address to its neighbour peers which in turn will return their closest addresses to this target address.
Does a node periodically ask their neighbour peers about their closest addresses to his own address? Wouldn't that be wasteful as the answers will not much change over time?


texts:
I made a conversion from Solidity 0.4.17 to 0.6.2 of a contract that have a MINT option.
The biggest problem here is that I am not sure if this function mint is okay (will return the correct id).
Look:
     function mint(string memory _outer, string memory _inner) public payable onlyOwner{
    Filio memory _filio = Filio({ outer: _outer, inner: _inner });
    filios.push(_filio);
    uint _filioId = filios.length - 1;
//    return _filioId;

    _mint(msg.sender, _filioId);

The full code are here:
pragma solidity ^0.6.2;

import 'openzeppelin-solidity/contracts/token/ERC721/ERC721.sol';
import 'openzeppelin-solidity/contracts/access/Ownable.sol';

contract FiliosToken is ERC721, Ownable {

    constructor() ERC721 ("FiliosToken", "FIL") public {

}

  struct Filio {
    string outer;
    string inner;
  }

  Filio[] public filios;

  function getFilio( uint _filioId ) public view returns(string memory outer, string memory inner){
    Filio memory _fili = filios[_filioId];

    outer = _fili.outer;
    inner = _fili.inner;
  }

  function mint(string memory _outer, string memory _inner) public payable onlyOwner{
    Filio memory _filio = Filio({ outer: _outer, inner: _inner });
    filios.push(_filio);
    uint _filioId = filios.length - 1;
//    return _filioId;

    _mint(msg.sender, _filioId);
  }
}

So, when I try to deploy the truffle return an revert error.


texts:
If I set up a filter to receive changes, I only seem to receive transactions for addresses that are contract addresses.

How to put a filter to receive transactions that are sent to an address that is non-contract?


texts: Smart contract machine learning use case with highly mutable model

texts:
I was thinking about different smart contract uses cases.

Idea

Imagine a service that classifies images. It takes an image of an animal (e.g. a cat) as input and determines the type of the animal.

This kind of classification problem is solved using machine learning. The image recognition service uses training data to create a machine learning model. This model is open to the public via a prediction api. Users pay a fee to query this api. The machine learning model is not immutable. As new images are provided the model is retrained to improve future predictions.

Business transaction

To get a prediction following steps are required:

input image
check account balance, when enough money is available, proceed, else abort
wait for image recognition service to deliver output
receive output

Smart contract

So my question is, can this idea/ business transaction be implemented as a smart contract? Does it make sense?

Since a smart contract is immutable, for each (retrained) machine learning model, a new smart contract must be created. And one must keep track of old smart contracts, because they will deliver worse predictions. Or is there an option to destroy "old" smart contracts?

Having a highly mutable service, would it not be better to use a service like oraclize.it to implement API calls to the external service?


texts: How to set the call back in WEB3 with Jquery

texts:
I have 2 functions in blockchain contract to get the investors and funds for an address and tried to save that in excel.

1st Function  To get the list of investors

getInvestorsList()

2nd Function  This will take the investor address as input and returns the investors address and the funds saved for that address

getInvestorsAndBalances(address investorAddress)

I was able to get the list of investors and the finds sponsored by them using the functions "getInvestorsList" and "getInvestorsAndBalances".

Question

The below snippet which convert the data to excel has to executed only when the function "getInvestorsAndBalances" executes completely for all investors. But this code is executed even before the call to the contract completes. Hence I am not getting the values from the blockchain to the below snippet.

How to make the below code wait for the successful completion of the function "getInvestorsAndBalances" ?

                dataSample = dataSample + "]";
                console.log("dataSample: " + dataSample);
                //var dataSample = [{"address": "abc","balance": "21.22"}];
                const xls = new XlsExport(dataSample,  'Example WB');
                xls.exportToXLS('export.xls')

Complete Code

    crowdSaleContractObj.getInvestorsList(function(error, result){
            if(!error)
                {
                    for (i=0; i < result.length; i++) {

                        crowdSaleContractObj.getInvestorsAndBalances(result[i],function(error, result1){
                        console.log(i);

                        if(!error)
                            {
                                console.log(i + " - Address : " + result1[0]+ ",  Balance : " + result1[1]);
                                element = " {\"address\": " + result1[0] + ",balance:" + result1[1] + "},";
                                console.log("element: " + element);
                                dataSample = dataSample + element;
                            }
                        else
                            console.error(error);
                        });
                    }

                    dataSample = dataSample + "]";
                    console.log("dataSample: " + dataSample);
                    //var dataSample = [{"address": "abc","balance": "21.22"}];
                    const xls = new XlsExport(dataSample,  'Example WB');
                    xls.exportToXLS('export.xls')

                }
            else
                console.error(error);
    });


texts:
I'm a complete beginner, but managed to download Mist.  It was downloading blocks quite slowly, and I got the message to install the latest version (9.1).  I uninstalled the previous one, and went ahead with 9.1.  However, now I can't get started as I had previously.  I'm getting the following message that I could not connect to the node:

Node type:  geth
Network:  main
Platform:  win32 (Architecture x64)

...flag provided but not defined:  -syncmode


texts: Deploying MakerDAO Oasis on Kovan Testnet

texts: I'm trying to deploy MakerDAO Oasis on Kovan Testnet & Ganache but I'm struggling to figure out how to do so. The error shown occurs when I use my metamask, on Kovan network, to try and create a vault.


texts: When I send ether from one of my accounts to the other a transaction is sent but after the confirmations there is still no ether transferred. I didn't get any obvious error messages


texts: What is the verification process of nodes on chainLink?

texts:
chainLink is a decentralized system similar to Ethereum, which can help smart contracts execute get requests and return the results. The result of chainLink execution also needs to be verified by other nodes on the network. I want to know what is the verification process of other nodes on chainLink. Do other nodes need to initiate a get request to the same url when verifying, and then verify based on the result?
Hope you can give me some help, thanks!


texts: How transaction with gas used ok 28k succeed for payable?

texts:
I'm trying to understand what I can do in fallback payable (I have read the docs and I know what I can't do for sure).

Here is my contract:

pragma solidity ^0.4.22;

contract SmartMsgData {
    // events
    event onDeposit(int128 id, address person, uint amount);

    function bytesToBytes16(bytes b, uint offset) private pure returns (bytes16) {
      bytes16 out;

      for (uint i = 0; i < 16; i++) {
        out |= bytes16(b[offset + i] & 0xFF) >> (i * 8);
      }
      return out;
    }

    function () payable external {
        require(msg.value > 0);
        require(msg.data.length == 16); // 16 bytes = int128

        // TODO: add checking for msg.value if i have enough gas

        int128 id = int128(bytesToBytes16(msg.data, 0));
        address person = msg.sender;
        uint amount = msg.value;

        // fire event
        emit onDeposit(id, person, amount);
    }
}

I've sent some amount from one address to contract address with data provided on myetherwallet.com with metamask.

Here is succeeded transaction. You can see gas used is 27826.
However, in the docs it's written that fallback payable function can rely on 2300 of gas only:

  In the worst case, the fallback function can only rely on 2300 gas being available

How did the transaction succeed if gas used exceeds the limit? Will it work in 100% of cases or depends on anything (miner, etc)?

Ideally, I'd check msg.value to be valid (within some range) so I'm trying to figure out if I have enough gas to read struct from storage and check it. How can I measure gas requirement beforehand as Remix evaluates loops incorrectly and measures gas requirement for bytesToBytes16(..) as infinite?


texts: View functions that temporarily modify state

texts:
It is currently possible to use a view or constant function to temporarily modify state, for example:

contract Thingy {
    uint public thing;

    function doubler(uint input) public view returns (uint) {
        thing = input * 2;
        return thing;
    }
}

The above code will actually work, but as we are only using a call, the value of thing is reverted after doubler returns.

The following behaviour was actually useful to me recently as a bit of a hacky work around on some problem I was dealing with.

My question is - the compiler currently only throws a warning, not an error, meaning the code will still compile. Will this still be true in the future, or should I avoid exploiting this behaviour?


texts: How does Ethereum differentiate between 0x0 and null during contract creation?

texts:
According to the EVM documentation, all values are initialized. This means to will contain the 0 address, as null is not a recognized state. The 0 address links to an external account (which we all know contains a trove of ether and tokens). So, how does ethereum distinguish a contract creation request from a value transfer request originating from sender to address 0x0..0?
Does the payload content of the data property then determine whether this is a contract creation request, e.g., parser sees to == 0x0 && data == 0x0 and results in value transfer to account 0x0..0.


texts: Getting ParserError: Expected ',' but got 'payable' and also one important security issue with contract

texts:
I have write a small smart contract for lottery system. however there is problem. please see below full code.

 pragma solidity >=0.4.22 <0.6.0;

contract Lottery{
address[] public players; //dynamic array with players addresses
address public manager; //contract manager

//contract constructor, runs once at contract deployment
constructor() public{
    //the manager is account address that deploys the contract
    manager = msg.sender;
}

//this fallback payable function will be automatically called when
   somebody
//sends ether to our contract address
function  ()  payable  external {
    require(msg.value >= 0.01 ether);
    players.push(msg.sender); //add the address of the account that

                              //ether to players array
   }

function get_balance() public view returns(uint){
    require(msg.sender == manager);
    return address(this).balance; //return contract balance
}

//returns a very big pseodo-random integer no.
function random() public view returns(uint256){
return uint256(keccak256(block.difficulty, block.timestamp,
players.length));
}

function selectWinner() public {
    require(msg.sender == manager);

    uint r = random();

    address winner;

    //a random index
    uint index = r % players.length;
    winner = players[index];

    //transfer contract balance to the winner address
    winner.transfer(address payable(this).balance);

    players = new address[](0); //resetting the players dynamic array
}
}

I am getting below issues.

1) I am getting  ParserError: Expected ',' but got 'payable'
winner.transfer(address payable (this).balance); on line.

    winner.transfer(address payable(this).balance);

2) There is one security issue on below code.They are not really random because the minor can modify or can set a specific time stamp.That difficulty can be known by the minor in advance and also somehow the minor could know how many players entered the lottery.
so there is other way to secure the contract from above the issue as mentioned.

function random() public view returns(uint256){
   return uint256(keccak256(block.difficulty, block.timestamp,
  players.length));
}


texts: Pop-up instructing me to start Geth with "repccorsdomain" when running Mist on OSX?

texts:
Macbook Pro
OS X 10.10.5
Mist/Ethereum-Wallet 0.8.1
Node type: Geth 1.4.10 (Go)

When running Ethereum-Wallet I have been receiving this pop-up message (presumably from within the application) quite regularly:

  Unable to connect. Please start geth with the following options:

  geth --rpc --rpccorsdomain "https://wallet.ethereum.org"

  Optional add: --unlock <yourAccount>.

This does not prevented me from syncing with the network; nor have I experienced any problems with transactions or my balance.

Is this a potential security issue I, and other users, should be concerned about?


texts: Insert data whithout overwriting the already stored whit the same address

texts:
i'm new to solidity and i'm developing an easy app.
This is the contract i'm working on. It's all functioning but i need to:
do some sort of function that return me all the array value whit the same user hash;
I need to insert automatically a new _address because when i insert new data whit the same addres, the stored data is overwrited and i don't want that because i need to store all data.
For example: i inserted .setUser('0xb23A1ff49C4d7c8997C414276917f974E6dD93D7','some md5','user m5d'), and after a couple of min i needed to insert other data that is linked to that same userHash.
how can i do that?
pragma solidity >=0.4.22 <0.7.0;

contract crud{
struct user{
    string hash;
    string userhash;
}

 mapping(address=> user)  users;

 address[] public user_arr;

 function setUser(address_address, string _hash, string _userhash) public {
     var array=users[_address];
     array.hash= _hash;
     array.userhash= _userhash;

     user_arr.push(_address) -1;

 }

 function getAllUser() view public returns (address[]) {
    return user_arr;
}

function getUser(address_address) view public returns (string, string) {
    return (users[_address].hash, users[_address].userhash);
}

}


texts: Buying tokens with OpenZepplin crowdsale

texts:
I am running into a very strange bug while interacting with my OpenZepplin crowdsale.

Here is my repo for context https://github.com/GenusDev/crossfit-coin-backend

Here is what I have working so far:

Deploy a Crowdsale contract: success
Deploy a MintableToken: success
Transfer ownership of MintableToken to Crowdsale: success
Attempt to buyTokens from front-end app (line 76 of app.js):
FAIL...but then,if I run the same buyTokens command once through the Truffle
CLI, I can then refresh the page of my front-end app and run the
exact same code (line 76 of app.js) and successfully buyTokens.

Its not a timing issue. I have waited several minutes after deployment, and step 4 works from the front-end immediately after running the same command through the CLI. Can anyone offer advice here?


texts:
How to encode and decode ABI data?

Can someone show me an example with web3js library?


texts: How would you render this structure of data?

texts:
I have coded a smart contract which allows one to store a certain type of structure of datas which can be described as something like that :

├── Client1(Contract)
│   ├── Year2018 (Struct containing string,uint and struct)
│   │   ├── Case 1 (Struct containing string)
│   │   └── Case 2 (Struct containing string)
│   └── Year2017
│       └── Case 1 (Struct containing string)
├── Client 2
│   └── Year2018
│          ├──Case1 (Struct containing string)
│          └──Case2 (You got it)

I managed to fill it correctly and parse it too ( But only one case INDIVIDUALLY). I would like to be able to have a function which returns all the datas in a organized way (such as a multi-dimensionnal array or a JSON for example). What should I use ? Is it possible to store all these value in a bytes array ?

Thanks for your ideas and have a good day !

EDIT:

Should i try something like this ?

function massImport(bytes[] _datas)  view external onlyOwner(){
        for(uint i = 0;i<_datas.length;i++){
            addYear(bytes(_datas[i]));
            for(uint j = 0; j<_datas[i].length;j++){
                addCase(bytes(_datas[i][j]));
            }
        }
    }

I typed the function bytes() because I assume that bytes are the only possible array in this case?

EDIT 2 :
Here is the struct 'YEAR'

struct Year{
    string entryName;
    string entryYear;
    uint permissionType;
    Elem elem;
    uint[] elemList;
    mapping(uint => Elem) allElem;
    uint elemId;
}

Do you think that it's too heavy to be stored fully on the blockchain ?


texts: unable to read updated value after smart contract execution

texts:
I am new to blockchain. I am trying to implement a dapp project in my college curriculum. I am trying to implement seller-buyer smart contract on private ethereum node(using solidity, geth console, mist browser). Please help.

Problems that I am facing:

Once the seller contract is executed after entering all the values. I want to capture the updated product quantity. Ex: The seller is selling 10 apples and each apple costs an ether. Once the buyer transfers 1 ether to seller account then the product quantity should be updated to 9 (it means the seller sold 1 apple) based on the ether sent by the buyer the product quantity should get updated in read from contract.
How to display this updated product quantity
How to show that the buyer received the product

I created 2 contracts: buyer and seller. I created 2 accounts: buyer account and seller account.

Buyer contract: I am writing/reading from contract:  buyer name, buyer address
seller contract: I am writing to the contract: seller name, seller address, product description, perunitcost.

Here is the code:

pragma solidity ^0.4.15;
contract Seller {
    uint public value;
    address public seller;
    string public sellername;
    string public selleraddress;
    string public productdescription;
    uint public perunitcost;
    uint public productquantity;
    uint public updatedproductquantity;
    mapping (address => uint) public balances;

function Seller(string tokensellername,string tokenselleraddress, string tokenproductdescription, uint tokenproductquantity,uint tokenperunitcost) public {
        sellername = tokensellername;
        selleraddress = tokenselleraddress;
        productdescription = tokenproductdescription;
        productquantity = tokenproductquantity;
        perunitcost = tokenperunitcost;
    }

  function confirmPurchase(address _seller) payable {
    uint itemstoBuy = value / msg.value;

  // balances[_seller] holds the number of carrots to sell
    require(balances[_seller] >= itemstoBuy);

    balances[_seller] -= itemstoBuy;
    balances[msg.sender] += itemstoBuy;
    _seller.transfer(msg.value); //transfer the ether to the seller

    //display how much product quantity in left: show this on read from contract
    updatedproductquantity = balances[_seller];
  }
}


texts: How to add EthereumWallet's wallet to geth?

texts:
i am struggling to add my EthereumWallet wallet to geth.

I should run a command like this:

get account import <keyfile>

I downloaded a file from the EthereumWallet website, and I ran this command. I got an error like this:

Fatal: Failed to load the private key: encoding/hex: invalid byte: U+007B '{'

I think that I am doing something completely wrong.


texts: How to use recovery mnemonic in metamask to import account instead of private key?

texts: We can import account by importing private key of the account. While creating a new account we give passphrase to encrypt the private key. How to import an account in metamask using the mnemonic?


texts:
From 2nd November MetaMask will not expose user accounts by default anymore and we must do it.
I'm confused about how we are supposed to integrate that in our dapps.

For example, I have a standard web3.js file with the following code:

import Web3 from 'web3';

let web3;
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  // metamask is running
  web3 = new Web3(window.web3.currentProvider);
} else {
  //user is not running metamask
  // create provider through infura
  const provider = new Web3.providers.HttpProvider(
    // pass url of remote node
    'https://rinkeby.infura.io/v3/censored'
  );
  web3 = new Web3(provider);

}
export default web3;

Should changes be in the web3.js file? Or, should I create a button on the website which must be clicked by the user to give me access to his MetaMask account?


texts: Does only one miner collect my transaction fee?

texts:
I just ran in to the concept of gas and found this community. This question and answer were particularly helpful, but they leave one thing unanswered for me:

If I send out a transaction with a given price I am willing to pay for gas and a cap on the gas that can be used, how do miners decide which of them should process it? Say the price I offer is really good. It seems to me they would all try to process it and collect the fee. Now say my computation runs out of gas, and all those miners try to collect the fee. I shouldn't be double-charged, yet the work was done multiple times.

Is there a system for laying claim to transactions so this duplication of work doesn't happen? If there is, how does it work? If there isn't, then which of the miners who take up my task gets to keep the fee?


texts: How can assembly be used to add bytes together?

texts:
To store data on the blockchain, a storage container bytes[6] data is used, each array stores maximum amount based on block gas limit. Can assembly be used to add those 6 arrays together, and return one single bytes array?

function getData() public view {
    uint length;
    for(uint i = 0; i<6; i++) {
        length += data[i].length;
    }
    bytes memory result = new bytes(length);

    uint index = 32; // bytes is an array, and in EVM the first
                     // 32 bytes of an array stores the length
                     // of the array, so add data 32 byte in

    for(i = 0; i < 6; i++) {
        bytes memory oneSixth = new bytes(data[i].length);
        oneSixth = data[i];
        assembly {
            mstore(add(result, index), add(oneSixth, 32))
        }
        index += data[i].length;
    }
}


texts: How to configure go-ethereum? (Config File)

texts:
I setup an exchange with ethereum, I have installed ethereum as documented here.

But I can't find config file of the go-ethereum client, in bitcoin core it's ./bitcoin/bitcoin.conf

Because i wanted create a connection to ethereum server. How do configure it?


texts: Defining the transaction object for offline transaction signing using "web3.js from the broswer"

texts:
I am trying to call a contract method ( a write operation ) and sign the transaction manually using my privatekey. The transaction hash is being generated but when I go to etherscan, the transaction shows failed. My web3.js code is as follows.

 var tx = new ethereumjs.Tx({
                from: '0x3dCDe57Ad49d639c4D702b607Dd5eBc0aB54A671',
                nonce: web3.toHex(txCount),
                gasLimit: web3.toHex(1000000),
                gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
                data: contractInstance.incrementTest.getData(10).
            });

I have doubt in the data part of the transaction object. Is this the correct way to use it? incrementTest is the contract method and 10 is the parameter i wish to pass to incrementTest.

Error displayed in etherscan : Warning! Error Encounter during Contract Execution [stack underflow (0 <=> 15)

the error is different for different contract methods ie; when i change the data value in the transaction object.


texts: Web3 Javascript API -- Transaction Object Not Matching Documentation

texts:
Noob question about the Web3 Javascript API.

When I use web3.eth.getTransaction(), the object that comes back has some properties that I cannot seem to find in the documentation. For example, here is what I'm seeing when I run web3.eth.getTransaction().

{ blockHash: '0xf2a40da650009deb5b064660c2b3fd8030a1bb0e9e92ed38ab66813cc366c7e0',
  blockNumber: 3593309,
  from: '0x485fbe8fce05a862832ddc9464e96be131544c45',
  gas: 147622,
  gasPrice: { [String: '211000000000'] s: 1, e: 11, c: [ 211000000000 ] },
  hash: '0xdbbcb4d5be94f56ee23bcf7b9f42fa72294d6f5b735f994a05e122e2a2687f51',
  input: '0x9cf5453d000000000000000000000000485fbe8fce05a862832ddc9464e96be131544c45',
  nonce: 34,
  to: '0x1d0dcc8d8bcafa8e8502beaeef6cbd49d3affcdc',
  transactionIndex: 0,
  value: { [String: '500000000000000000'] s: 1, e: 17, c: [ 5000 ] },
  v: '0x26',
  r: '0x48a7fbc581ec4a7509cabbb0d603eceeaf5d43901128fa79b33f0bc73d41ad13',
  s: '0x4c006097a7fe312e9373a3c6488a16ba80d170c77a6b7a124437ac0796005ba2' }

For comparison, here is what the Web3 JavaScript documentation shows:

{ "hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
  "nonce": 2,
  "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
  "blockNumber": 3,
  "transactionIndex": 0,
  "from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
  "to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
  "value": BigNumber,
  "gas": 314159,
  "gasPrice": BigNumber,
  "input": "0x57cb2fc4"}

What are the "v", "r", and "s" properties? And what are "s", "e", and "c" within the "value" object?

Is there an updated documentation I should be looking at? If it matters, I'm using web3 v 0.20.1 with a local instance of Geth.


texts:
I coded different functions and didn't find a standard that define crystal clear how many variables you can use (fields, local or as parameters of modifiers inside this function?

Do you know a cheatsheet with these limitations?

Thanks!


texts: How to set and get marketprice of token in contract?

texts:
I am building a simple erc-20 token. I don't have an idea as how token price is setup. However, I need to get my token's market price inside another contract. If you see this example of token BOMB, it has market price shown on etherscan.

My question is that how this market price is established? Do I need to list it anywhere or what? Please let me know the complete flow and secondly, can I get this market price value inside my solidity contract?

Thanks a bundle


texts: Signing messages off-chain (reproducing keccak256 off chain)

texts:
I'm trying to follow this tutorial: https://programtheblockchain.com/posts/2018/02/17/signing-and-verifying-messages-in-ethereum/
But I cant seem to get it to work:

The following method doesnt make sense to me:

function signPayment(recipient, amount, nonce, contractAddress, callback) {
  var hash = "0x" + ethereumjs.ABI.soliditySHA3(
    ["address", "uint256", "uint256", "address"],
    [recipient, amount, nonce, contractAddress]
  ).toString("hex");

  web3.personal.sign(hash, web3.eth.defaultAccount, callback);
}

It would seem that var hash variable is going to be greater than 32 bytes and thus can never be the same value as:

keccak256(msg.sender, amount, nonce, this)

Has anyone been able to get his tutorial to work? Or explain how those two values are the same? Is there an alternative to soliditySHA3() that matches the functionality of keccak256()?


texts: Limitations of ethereum block chain in terms of contract size

texts:
I have a contract that stores some basic data about a person. It has about 4-5 variables. Each of these contracts is associated with a name.

Say I want to search for a Person smart contract that belongs to Varun, then I can call every single contract, and query whether the it has that name stored or not. Now this is very in-efficient so instead I want to have a CentralRegistry contract in which I can keep a basic mapping of the name vs the address of the contract it belongs to.

Every time a new contract is created, the name and address corresponding to it is appending to the mapping in the CentralRegistry contract. If I have 10,000,000 Person contracts, is there any issue is storing a mapping that has 10million registry. Note each append to the mapping will be done in a separate transaction, and it will be probably done over several months.


texts: How do I know if a submitted block became an uncle?

texts: We need to detect that the submitted work became an uncle. How would I do this with geth api? I thought of checking the submitted block number later for any uncles that match my block's hash. Is there a better way?


texts: Defined GasLimit in genesis file and in web3j gasprovider

texts:
Im having issues when I try to implement a back end that generate smart-contract transaction calls using web3j. But I'm a lit confused with the gas limit concept. I have defined inside the genesis file a gas limit value of:

"gasLimit": "0xE0000000" --> 3758096384

And inside the web3j gasProvider a value of:

30_000_000L

At the time of making the transactions there comes a time which I cannot perform operations. And I get the following exception:

java.lang.RuntimeException: java.lang.RuntimeException: Error processing transaction request: exceeds block gas limit
    at org.web3j.tx.Contract.deploy(Contract.java:391)
    at org.web3j.tx.Contract.lambda$deployRemoteCall$10(Contract.java:496)
    at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:30)

This exception appear when I deploy new SC and also when I do SC function calls. In one way or another, I cannot perform any type of operation and I have to restart the blockchain.

The generated exception who gives me? The blockchain or web3j for having defined a value in the GasProvider lower than that of the genesis?
But the gas limit defined in the genesis is not supposed to be only for the first block?
Why I cant make transactions and how can I manage this situation in a production environment and recover the data and the great functionallity?
How can I know a great gasLimit value for production?

UPDATE

QUORUM_CONSENSUS: default to istanbul

QUORUM_DOCKER_IMAGE: default to quorumengineering/quorum:2.2.3

QUORUM_TX_MANAGER_DOCKER_IMAGE: default to quorumengineering/tessera:0.9


texts: Plasma: can nodes exit to any ancestor blockchain, not just to the one two levels below?

texts:
Diagram extracted from the whitepaper, page 7:

Let's imagine there would be an extra layer, that is, a Blockchain at the 4th Tree Depth. In the event of Byzantine failure, can Alice exit to the Root Chain or her fraud proof is automatically posted to a 2nd Tree Depth Blockchain?


texts: Metamask Transaction does not appear in Ganache

texts:
I'm trying to call the storeQueryResults() function of my smart contract in the following way:

storeInput: function(event) {
    var queryResultHandlerinstance;

    App.contracts.QueryResultHandler.deployed().then(function(instance) {
      queryResultHandlerinstance = instance;
      return queryResultHtandlerinstance.storeQueryResults(1, 2, "a", "b", {
        from: web3.eth.accounts[0]
      });
    }).then(function(result) {
      alert("success");
    }).catch(function(err) {
      alert(err.message);
    });
  },
};

Then, after confirming the transaction in Metamask, I can see it is approved there:

However, in Ganache nothing happens:


texts: Why does sendSignedTransaction return a tx hash BUT does not post to the Rinkeby network (React, Metamask, web3, infura)

texts:
I'm developing a very simple React application wherein a user clicks a button and some ether gets sent from one account to another. Currently, the onClick sendEther function crafts a proper signed serialized transaction and (oftentimes) returns a transaction hash. However, the transaction never actually goes through to the Rinkeby test network (as accessed via Etherscan).

My hunch is that that I'm misusing infura (which I set up in my DOMContentLoaded event, see below).

//1. Set up

document.addEventListener('DOMContentLoaded', () => {
   const endpoint = 'https://rinkeby.infura.io/APIKEY';
   window.web3 = new Web3(new Web3.providers.HttpProvider(endpoint));
});

//2.  React front end component.

sendEther() {
    const fromAccount = **acct1**;
    const toAccount   = **acct2**;

    const rawTransaction    = this.makeRawTransaction(fromAccount, toAccount);
    const signedTransaction = this.makeSignedTransaction(rawTransaction);
    const serializedTransaction = `0x${signedTransaction.serialize().toString('hex')}`;

    window.web3.eth.sendSignedTransaction(serializedTransaction, (error, result) => {
        if(!error) {
          console.log(`Transaction hash is: ${result}`);
          this.setState({
            etherscanUrl: `https://rinkeby.etherscan.io/tx/${result}`,
            error: null
          });

        } else {
          this.setState({ error: error.message })
          console.error(error);
        }
    });
  }

  makeSignedTransaction(rawTransaction) {
    const privateKey   = '**************';
    const privateKeyX  = new Buffer(privateKey, 'hex');
    const transaction  = new EthTx(rawTransaction);
    transaction.sign(privateKeyX);

    return transaction;
  }

  makeRawTransaction(fromAccount, toAccount) {
    const { exchangeRate } = this.props;
    const amount = (1 / exchangeRate) * 5;

    return ({
      nonce: window.web3.utils.toHex(window.web3.eth.getTransactionCount(fromAccount)),
      to: toAccount,
      gasPrice: window.web3.utils.toHex(100000000000),
      gasLimit: window.web3.utils.toHex(100000),
      value: window.web3.utils.toHex(window.web3.utils.toWei(`${amount}`, 'ether')),
      data: ''
    });
  }


texts: Remote Web3 connection to Parity node running on AWS

texts:
I have an Amazon EC2 instance set up running a Parity node. I'm trying to communicate with it via Web3 (using Nethereum.Web3 in C#).

If I connect locally with http://127.0.0.1:8545, everything works great.

If I try to connect from a different EC2 instance using http://somePrivateIP:8545, the RPC request fails to connect.

If I try to connect from my home PC using http://somePublicIP:8545, the RPC request also fails to connect.

I have enabled ALL traffic on TCP 8545 in the AWS security group.

I am starting Parity with everything relevant I can think of enabled:

C:\Program Files\Parity\Parity\ptray.exe --jsonrpc-apis all --jsonrpc-hosts all --jsonrpc-interface all

What am I missing?


texts: Is it possible to run multiple Ganache nodes for private test network?

texts:
I wonder if i can create my own private cluster as it can be  done with Geth for development & test purposes :
https://github.com/ethereum/go-ethereum/wiki/Setting-up-private-network-or-local-cluster#local-cluster

I gave shot by running multiple Ganache on same PC. But obviously failed to run as it tried to access port that is already taken by previous one.


texts:
I am trying to do something like this in Solidity as a modifier but it wont work.

modifier onlyManagement {

    require( msg.sender == management || msg.sender == owner );
    _;

}

function someFunction() public onlyManagement{
  // do something
}

I want to be able for the owner of the contract or the manager to have access to it.


texts: Capturing an event fired from a contract that was called from another contract

texts:
I'm trying calculate tax on arbitrary items/values. To do this I have a single contract is used as an 'Oracle' to get the tax from an external system. This contract defines functions to be called from other contracts and will emit an event that is captured by the external code. This will then perform the calculations and send the data back to the contract. The code is

pragma solidity ^0.4.21;

contract TaxContract {
    address public owner;
    event TaxRequest(int price);

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

    function calculateTax(int price) public {
       emit TaxRequest(price);
    }
}

The calling contract is passed the address of the TaxContract in it's constructor.

pragma solidity ^0.4.21;

import "./TaxContract.sol";

// Asset Test Contract
contract AssetContract {
    address public owner;
    address contractAddress;

    // Constructor
    constructor(address taxContractAddress) public {
        owner = msg.sender;
        contractAddress = taxContractAddress;
    }

    // Public functions
    function sellAsset(int price) public {
        TaxContract(contractAddress).calculateTax(price);
    }
}

I'm using Nethereum to both deploy the contracts and listen for events i.e

var sellFunction = contract.GetFunction("sellAsset");
var gasLimit = await sellFunction.EstimateGasAsync().ConfigureAwait(false);
await sellFunction.SendTransactionAndWaitForReceiptAsync(senderAddress, gasLimit, null, null, 563278);

and

var taxRequestEvent = contract.GetEvent("TaxRequest");
var taxFilter = await taxRequestEvent.CreateFilterAsync();

while (true)
{
var taxEvent = await taxRequestEvent.GetFilterChanges<SalesTaxRequestEvent>(taxFilter);
....

When I had all of the functionality in one contract i.e the sellAsset method emitted the event that the external code was listening for and called the sellAsset function it all worked. But now that I have split it into two separate contracts, no event seems to be fired. Any ideas as to why this is not working?


texts: node cannot be made up in private blockchain by using command line

texts:
I have created the genesis.json
The genesis json content is

{
  "config": {
    "chainId": 46860,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "byzantiumBlock": 4,
    "constantinopleBlock": 5,
    "clique": {
      "period": 5,
      "epoch": 30000
    }
  },
  "nonce": "0x0",
  "timestamp": "0x5c596a29",
  "extraData": "",
  "gasLimit": "0x47b760",
  "difficulty": "0x1",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    "0x75AF6589202Dc4275fa56bC57eC77cE8Ce81BD64": {
      "balance": "0x900000000000000000000000000000000000000000000000000000000000000"
    }
  },
  "number": "0x0",
  "gasUsed": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

and have run geth --datadir node1/ init genesis.json to initialise with the genesis block. Then after creating and making the boot node up, I am trying to make my node up using

`nohup geth --datadir node1/ --syncmode 'full' --port 30303 --rpc --rpcaddr 127.0.0.1 --rpcport 3503 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes'enode://00f1bd4f26b16a7216a46de5324aac8b33ec3fbc3de4987c06dfa7549511210b9745961e2664b46cc63eafbfff37fd0b135080766ba5efde28c33131e0c13c9
8@127.0.0.1:30302' --networkid 1505 --gasprice '1' --unlock 0 --password node1/password.txt --mine > node1/01.log 2>&1 &`

where "00f1bd4f26b16a7216a46de5324aac8b33ec3fbc3de4987c06dfa7549511210b9745961e2664b46cc63eafbfff37fd0b135080766ba5efde28c33131e0c13c9
8" is my boot node address.

I am using go-ethereum v1.9.1-stable-b7b2f60f.

The error logs of making the node up is

I have checked with older version of geth v1.8.27 the problem cannot be reproducible, so is it the version issue?


texts: Trying to return an address - gets cut off when returned

texts:
I have these 3 functions in a contract I am writting. I am currently using https://remix.ethereum.org to help me debug/better understand what the code is doing.

When I call GetPassedAddr(address _addr) with say

0xca35b7d915458ef540ade6068dfe2f44e8fa733c

I get back

0x8dfe2f44e8fa733c000000000000000000000000

It cuts the address in half, takes the second half and appends a bunch of 0's and then returns that value. It does this for any address I input.

Any ideas why?

function GetCallingAddr() public view returns(address) {
    return msg.sender;
}

function GetPassedAddr(address _addr) public view returns(address) {
    return _addr;
}

function GetAddrZero() public view returns(address) {
    return address(0);
}

SOLVED
My problem was that I was passing the in contract digits without quotes, therefore remix was interpreting that as an int/float and was cutting off the digits


texts: How can Ethereum be useful in Insurance Industry?

texts:
How Ethereum can be useful to Insurance Industry ?

I'm a Web Developer, still learning about Smart Contracts, and familiar with Blockchain fundamentals to some extent.

Came across safeshareinsurance.com which will be giving insurance to slock.it projects.

I have to write some points and present to my manager how and what solutions can we build using blockchain tech today, and what innovative solutions can be offered to clients.

Cheers,
Satinder


texts: I need a help：Transaction has been reverted by the EVM

texts: Please help me see the problem is wrong where


texts: SQL syntax error near `logsBloom` when call web3.eth.sendTransaction

texts:
When I am trying to call web3.eth.sendTransaction I receive this error stack:

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `logsBloom` = '0x00000000000000000000000000000000000000000000000000000000000000' at line 1
    at Query.Sequence._packetToError (/usr/lib/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
    at Query.ErrorPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
    at Protocol._parsePacket (/usr/lib/node_modules/mysql/lib/protocol/Protocol.js:279:23)
    at Parser.write (/usr/lib/node_modules/mysql/lib/protocol/Parser.js:76:12)
    at Protocol.write (/usr/lib/node_modules/mysql/lib/protocol/Protocol.js:39:16)
    at Socket.<anonymous> (/usr/lib/node_modules/mysql/lib/Connection.js:103:28)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:561:20)
    --------------------
    at Protocol._enqueue (/usr/lib/node_modules/mysql/lib/protocol/Protocol.js:145:48)
    at Connection.query (/usr/lib/node_modules/mysql/lib/Connection.js:208:25)
    at Query._callback (/usr/ico/_common/getMoneyGlobal.js:232:41)
    at Query.Sequence.end (/usr/lib/node_modules/mysql/lib/protocol/sequences/Sequence.js:88:24)
    at Query._handleFinalResultPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:139:8)
    at Query.OkPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:72:10)
    at Protocol._parsePacket (/usr/lib/node_modules/mysql/lib/protocol/Protocol.js:279:23)
    at Parser.write (/usr/lib/node_modules/mysql/lib/protocol/Parser.js:76:12)
    at Protocol.write (/usr/lib/node_modules/mysql/lib/protocol/Protocol.js:39:16)
    at Socket.<anonymous> (/usr/lib/node_modules/mysql/lib/Connection.js:103:28)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:561:20)

Maybe somebody met the same problem and knows how to fix it.

Thanks!


texts: How to allow the owner of a contract to set a deadline in days (and not have it inserted as seconds) in the constructor?

texts:
thanks for taking the time to read this.

I'm having a bit of trouble handling time in Solidity. I want the owner of a contract to be able to set a deadline in days (which will be used in the rest of the contract) on the constructor. I wrote this:

constructor(uint _price, uint _days) public {
    owner = msg.sender;
    price = _price;
    deadlineInDays = now + _days;
}

But as you may be aware, when the owner inputs any value in _days, it is added to the Epoch Time format (now). So, for example, if I set it to "10", when I call this function to return it:

function getPriceAndDeadline() public view returns (uint _price, uint _deadline)
{
    return (price, deadlineInDays);
}

It returns something like this:

_price 1000
_deadline 1544005222 // this is only ten seconds after I ran the constructor

I obviously wanted it to return whatever "now" is plus "_days" in days, not in seconds.

I tried this (below), but it doesn't work.

constructor(uint _price, uint _days) public {
    owner = msg.sender;
    price = _price;
    deadlineInDays = now + _days days;
}

Any ideas on how to handle this?

I appreciate any inputs in advance! Cheers!


texts: In Solidity how to use unnamed function parameters?

texts:
just wanted to know that in Solidity we can give function parameters without any name by just giving type, but how can we use them inside a function:
pragma solidity >=0.6.0 <0.7.1;

contract demo{

function myFunction1(int, int8, int) public{
        // now ho to use these received parameters
    }
}

This question is already asked here but no reasonable answer is given. Thanks in advance.


texts:
1820 keeps the record with

mapping(address => mapping(bytes32 => address)) internal interfaces

Which address is the actual contract which one is the interface?

I assumed the first address is the contract address and the second is the interface, so someone can query if my contract implements this interface and where is the interface at?

But in the erc1820 registery function setInterfaceImplementer

require(
   ERC1820ImplementerInterface(_implementer).canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC,"Does not implement the interface");

under my assumption this is querying the interface for records, that doesnt seems correct?


texts: How do the other nodes know which particular node has the account used in the transaction?

texts:
A brief about my setup. I am using a private Ethereum network with 3 nodes.
I have made all the nodes as peers of each other by using:
admin.addPeer("enode:1234abcd..")

When mining takes place, all the nodes are in sync.

I have also noticed that the accounts created on one node are local to the same node. So the accounts created on one node are available on the same node and not with any of its peers.

However, I am able to process transactions between accounts of different nodes using.
eth.sendTransaction({from:sender, to:receiver, value: amount})

Now my questions are:

How does the network know which node to query for the presence of the account?
Are all the nodes checked for the presence of 'sender' and 'receiver' account?
Does the transaction time increase if more peers are added to the network?
Will it affect the security of my network if I transport the keyfiles of accounts created on one node to all the other nodes?


texts:
I created a private block with custom genesis.json with command geth --datadir {path} init {pathToGenesis}. Then I create two new accounts, there is only two account in this block chain. I start mining by command miner.start(2).
logs are shown below:

INFO [01-02|07:55:09]  mined potential block  number=4138 hash=f2f1b9…35ad00
INFO [01-02|07:55:09] Commit new mining work number=4139 txs=0 uncles=0 elapsed=243.38µs
INFO [01-02|07:55:12] Successfully sealed new block

Then I checked my eth.getBalance(eth.accounts[0]) and found there are a lot of ether in the account.

In my understanding, account finds pending transactions, provides PoW, seals new transactions in a new block and finally get gas as reward. But, how can the account get ethers when there is not even a single transaction at all.

My question is:
Why I can mine ethers even if there is no transaction in block chain?
What did I seal in the new block?

Thanks in advance.


texts: After POS is implemented, what stops mining pools from being formed?

texts:
There won't be "mining pools" but stake pools but what if someone creates a system where participants stake everthing in one place in order to make the mkst money?

Is this allowed and is this a potential flaw in POS?

TDLR: Everyone stakes their ethereum with everyone else in order to gain the most money.


texts:
When Ethereum wasn't even launched, I remember Vitalik saying that the Ethereum mining process was designed in such a way to prevent the formation of mining pools. (I vaguely remember the reasoning being that the computer finding the proof-of-work solution could claim the mining reward for himself, as opposed to sharing it to the pool.)

Now that Ethereum has launched and mining pools exist, what went wrong? Why do we have Ethereum mining pools?


texts: Multiple Token Classes Within One Contract for ERC20 Standard

texts:
Is it possible to make one ERC20 compliant token contract, but have different classes of tokens circulating under the same token name?

e.g. You are distributing concert tickets validated by a token contract called "TicketToken", and have three open seating areas; Floor, Mezzanine, and Obstructed. Can you attach a classifying string to the token to delineate the class?


texts:
How would you go about creating a token that has a value based on time? (Time-currency Tokens)

What would be the solidity code be? I can't find much examples on this.

Thanks.!


texts:
I know this was asked several times on stackexchange, but after I see there are some alternatives for Ethereum Decentralized Exchange, but none seems to be stable.

I know about http://etherex.github.io/etherex and https://oasisdex.com. Is there anything else which is usable. How stable is EtherEx now?


texts: is there a java library to access or respond to an ethereum contract events?

texts:
We are building a java backend that is expected to interact with an ethereum node. So far I have only seen and tried web3.js api but it seems difficult to run it from java code.

Is there a way to use java to connect to the node ?


texts: Can I get the return value of a .call from a contract from the Blockchain?

texts:
I know that if I use call from a contract, that I cannot get the return value. I get a true or a false.

Is it possible for me to inspect the blockchain afterwords to get the return value?

For example, if the function that I CALL creates an new contract and returns the address, can I endow the the mined block and find the address of the created contract?

What if it returned a uint?

How would I do this? Web3?

I've created a blog post that shows a bit of what I'm trying to accomplish here:  http://catallax.info/news/2017/6/8/calling-future-contracts-from-contracts-in-ethereum-dev-log-6


texts: Can i change data in a database using smart contract and oraclize?

texts:
i understand that smart contract and oraclize can be use to get data from a database but can i manipulate the data inside the database using smart contract and oraclize? If so how can i do it?

Can I use Oraclize to send HTTP POST response and through that use an API to update the existing database?


texts: Is there a point in providing permissionless Ethereum Blockchain as a Service?

texts:
Microsoft's Azure Blockchain as a Service offers Ethereum (adapted for Consortium purpose) and other private blockchain implementations, IBM's Blockchain as a Service offers the Hyperledger Fabric permissioned Blockchain network. It's understandable that currently most organisations/companies would seek permissioned blockchain networks, a blockchain network where they can control who joins the network and who is allowed to conduct transactions etc.

However, there seems to be no interest or even any existing offer for permissionless blockchain as a service. Is there any benefit/point in offering the Ethereum protocol in public permissionless configuration through blockchain as a service / SaaS model?

The point as described by Microsoft for Blockchain as a Service is a quickly provisioned environment where the creator can get familiar with the technology, fail fast, fast recovery, low-price model based on pay per usage etc. But when a permissionless blockchain network is considered by any company such as Storj which currently runs on the permissionless Bitcoin protocol, would they in any case seek blockchain as a service? To me it seems there is no point.


texts: Can anyone call Gnosis wallet `submitTransaction` function? Also only owner can `executeTransaction`?

texts:
When reviewing Gnosis Multisig wallet (https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol#L184) I notice that the comment for submitTransaction function says that Allows an owner. However, on the function declaration, it doesn't have ownerExists requirement. So does this mean that the comment should be allows anyone to?

    /// @dev Allows an owner to submit and confirm a transaction.
    /// @param destination Transaction target address.
    /// @param value Transaction ether value.
    /// @param data Transaction data payload.
    /// @return Returns transaction ID.
    function submitTransaction(address destination, uint value, bytes data)
        public
        returns (uint transactionId)
    {
        transactionId = addTransaction(destination, value, data);
        confirmTransaction(transactionId);
    }

The same goes to the function executeTransaction. The comment says Allows anyone, but it has ownerExists on the function declaration.

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

Since gnosis multisig contract seems to be the most secure and famous for holding a lot of funds. I doubt that this is a bug. but I wonder if my understanding is correct about ownerExists requirement.


texts:
I have successfully run geth --rpc to test some functionality, but I need the personal API which according to this answer should be done by IPC.

When I run

geth --ipcapi "db,eth,net,web3,personal" --ipcpath /tmp/geth.ipc

This creates the ipc file and geth appears to otherwise start normally.

I have the following npm modules installed: web3 web3_extended web3_ipc

Then I run this on nodejs:

var web3_extended = require('web3_extended');

var options =
{
    host:     '/tmp/geth.ipc',
    ipc:      true,
    personal: true,
    admin:    false,
    debug:    false
};

var web3 = web3_extended .create (options);

var coinbase = web3.eth.coinbase;

The last line gives me an HTML response which includes

Your browser sent a request that this server could not understand.

and

Apache/2.4.12 (Ubuntu) Server at localhost Port 80

That Apache line makes me think nodejs isn't even attempting to connect by IPC.

Why not? Or, what else is the problem?


texts:
In POS people bet on the blocks to be added to chain and the honest block wins and the people who have voted for honest blocks get a share in the rewards. But one thing i am still confused is, who really mine or submit these blocks?

I did a lot of search and i am clear how POW works , but in case of POS ,how a participants decides which block is honest to not get penalized if bet goes wrong .


texts:
Excerpt from chapter 9 of the yellow paper, "Execution Model", describing the behaviour of the EMV when clearing storage:

  This refund is effectively paid up-front since the initial usage of a storage location costs substantially more than normal usage.

This seems to counteract this StackExchange answer:

  The gas refund is provided only 1 time, at the very end of the transaction's execution.

I also know that the refunded gas is capped at half of the execution costs, so this is confusing. Does the first statement mean that the refund is actually calculated up-front (formally, in the σ checkpoint state transition) but only transferred to the caller after the execution is finished?


texts: Help fixed point math to initialize a bonding curve

texts:
I'm having difficulty computing an initial tokenSupply parameter in Solidity, one of two required parameters to initialize a Bancor-style bonding curve contract.

Formula:

P = sent Ether in Wei

R = reserve ratio

M = Slope

tokenSupply = (P/(R*M))^R

Suppose:

P = 1 * 10^18

R = .333333

M = .0025

N = Scaling Factor =  1/1,000,000

This seems fine:

tokenSupply = 1*10^18 / ((N)333,333 * (N)2500) * N

Now:

tokenSupply = ( 1*10^18 / (N)833 )^R

But #1:

Can I divide the unscaled wei by the scaled product (N)833 and assume the quotient has the same scaling factor N?

.#2:

How on earth do I raise this quotient to R? (Assuming R's initial Scaling Factor, 333,333 is out of the question) And how do I know what the scaling factor would be of the result tokenSupply? (I don't know how to handle scaled exponents).  Thanks

I am using SafeMath to handle overflows

Sources:
https://blog.relevant.community/bonding-curves-in-depth-intuition-parametrization-d3905a681e0a
https://en.wikipedia.org/wiki/Fixed-point_arithmetic


texts: What is the set number of Ether in existence during POW and then POS?

texts: How many Ether exist during POW and then POS? Is it unlimited inflation?


texts: What does chain foundation means in parity? What's the difference between mainnet and foundation?

texts:
the parity --help has description below:

--chain=[CHAIN]
        Specify the blockchain type. CHAIN may be either a JSON chain specification file or
        olympic, frontier, homestead, mainnet, morden, ropsten, classic, expanse, musicoin,
        ellaism, testnet, kovan or dev. (default: foundation)

I really can't find what foundation means. And it seems having no difference with mainnet if you check the block on etherscan. So, dose anyone knows what's the difference between "foundation" and "mainnet" ? Branch of thanks!


texts: How to change the password to an account?

texts: The private key of an owned Ethereum account is encrypted with a password and kept in a so-called key file. How can I change this password?


texts: Difference between method id, event id and ABI signature for event

texts:
I am confused as to what is the difference between method id, event id and abi signature. I got the abi signature of a token transfer function according to the following web3js function

const signature = web3.eth.abi.encodeEventSignature("Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId)");
console.log(signature)

If I want the method id of the token transfer function of ERC721 tokens should I just consider the value returned from the above code, or it is the first four bytes of the answer returned according to this. Will the same value also be called its event id?


texts: How is it possible to print tokens out of nowhere with the batchOverflow problem?

texts:
As stated in the title I've been looking at the Batch Overflow issue that happened last year where someone printed tokens out of nowhere.

I see that when you create a token, you specify a totalSupply of the token that you are going to create so the amount of tokens must not be bigger than the TotalSupply.

When the BatchOverflow problem occured last year, someone printed tokens out of nowhere, that leads to the question which I cannot solve.

How was it possible for the guy that discovered the bug to create more tokens than the totalSupply specified ?

Isn't the totalSupply a constant value in the erc20 contract ?


texts: Difference between a byte in a bytes32 and a byte in a bytes structure

texts:
One can read in the docs:

A bytes is similar to byte[], but it is packed tightly in calldata and memory.

What does this exactly mean? For instance, according to this link, why should we convert a bytes object to a bytes32 one using:
function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) {
  bytes32 out;

  for (uint i = 0; i < 32; i++) {
    out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
  }
  return out;
}

and not using:
function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) {
  bytes32 out;

  for (uint i = 0; i < 32; i++) {
    out[i] = b[offset + i];
  }
  return out;
}

Furthermore:

Why isn't it possible to set an element of a bytes32 structure individually, but it is possible with bytes?
If I want to do some computations with bytes (litterally bytes, not the type bytes) by considering them as uint8, will it work for both structures by simply casting b[i] to uint8(b[i])? For instance, in order to get an uint256 from these types, would the following code:

uint res;

for (uint i = 0; i < 32; i++) {
    res += uint8(b[i]) * (256 ** i);
}

work, be b be a bytes object or a bytes32 one? Finally, are uint res = uint(b[i]); and uint res = uint(uint8(b[i])); two equivalent codes?


texts: Are funds returned if one transfers from an exchange to an invalid Ethereum address?

texts: I transferred some ether form an exchange site to an invalid address (invalid in that the correct address was trailed by 6 numbers I  accidentally pasted in). Looking for that address on Ethereum chain explorers I am told that is invalid. Will the blockchain refuse the transaction and return the funds?


texts: Listening to events in Ethers.js with websockets

texts:
I'm trying to listen to all emitted events from a contract with Ethers.js and Websockets.

Any idea why this is not working?

var wsProvider = new ethers.providers.WebSocketProvider("wss://rinkeby.infura.io/ws/v3/idhere");

let contract = new ethers.Contract(rinkebyAddress, CONTRACT_ABI, wsProvider);

contract.on("*", (from, to, value, event) => {
  console.log("event: ", event);
});

The websockets connection seems to work because this returns all new blocks:

wsProvider.on('block', (blockNumber) => {
  console.log('New Block: ' + blockNumber);
});


texts:
I am trying to read an address parameter in contract B from contract A and assert equality, but i get a type error:

TypeError: Operator == not compatible with types function () view external returns (address) and address

code:

contract A{
    ...
    function confirm(B _address) public returns(bool){
        B b = b(_address);
        require(b._addr == msg.sender);
        return true;
    }
    ...
}
contract B{
    address public _addr;
    ...
}

Thank you very much :)


texts: Is the following model correct for a DAPP?

texts:
I am trying to make a DAPP using React Native.
I have made a flowchart of all the pieces i need to build in order for it to work.

I was hoping if someone could verify it so that I can start working on it.


texts: How big is the Ethereum blockchain now (May 2016)? And what is it expected to be in the future?

texts:
How big is the Ethereum blockchain now (May 2016)? And what size is it expected to be in the future?

a) Now
b) One month from now
c) Two months from now
d) One year from now


texts: How can I check if a DAG file is corrupted?

texts:
When mining it's very common for a DAG to become corrupted. To resolve the problem deleting the file and restarting the miner is required.

I'm working on a miner manager to control RIGs and one of the features I want to include is to check if a DAG was corrupted instead of deleting it every X hours.

At this moment I'm only reading "REJECTED" on proxy which can be a cause of corrupted DAG.

So, there is any way (code/commandline) to check if the current DAG file is corrupted?


texts: what is the role of Migrations.sol contract in truffle project?

texts:
I have started working with truffle since 4 months and I don't give importance to Migrations.sol, I thought it's just a "get started" contract.
But when I removed it caused a problem.
can anyone explains the role of this contract?


texts:
Id like to run some unit tests in truffle with huge sums of ether (over 30k ether), but my default accounts only seem to have 100 ether in them.
Does anyone know how to increase this?

Thanks


texts:
I had five accounts on ETH before the hard fork with various balances. Over the last few days, I've sent all the ether in all of those accounts to Kraken. When I was done with that, all of my ether was in a brand new account (that did not exist prior to the fork). I then created a new account on Mist, and sent it all back to a brand new, did-not-exist-before-fork account in Mist. Am I now totally safe from replay attacks?

Also--just a side note--when I transferred to Kraken, ETHC magically appeared in my kraken account. I immediately sold it to US dollars and the bought new ETH, so the whole process was a net gain for me (assuming ETHC doesn't skyrocket).


texts: Given Buterins statement of a hard fork to return all the money after theDAO hack, does this mean that the DAO is unofficially dissolved? Officially when the hard fork has happened.


texts: Getting errors if sending transactions at short time intervals

texts:
I am on the kovan network and use web3 to execute transactions and query the blockchain. If I send many requests in short time intervals (1-15 seconds) one after the other, I get several errors >70% of my transactions fail! Here is the error I get:

  Error: Returned error: Transaction gas price is too low. There is
  another transaction with same nonce in the queue. Try increasing the
  gas price or incrementing the nonce.

  Error: Returned error: Transaction nonce is too low. Try incrementing
  the nonce.

If I send a transaction every 20 seconds, every transaction works!
Is this a problem of the kovan network or something else? What is the best way to improve this?


texts: How simulate blockchain and smart contract in VANET?

texts:
I am a beginner in the blokchain, I am blocked how I start simulate a blockchain and smart contract in vanet.
Can you help me and inform me how I have to simulate blockchain and smart contract in the vanet. What tool do I use, what language of development, how do I build blockchain in the vanet?


texts: How to create a new account with ethereumjs in Mix IDE

texts: Can I create a new account in Ethereum (with MIX IDE) by calling a contract method triggered by a button event in the html/js Dapp ?


texts:
Is geth --fast safe to use? Yes or no and motivation.

Just that.


texts:
This is a continuation of my first question re: DAO withdraw problems.

I'm running EW (latest update) on my MAC. I never connect with more than two peers and my wallet has not synced correctly since the DAO's inception. Assume others have had this problem. Here's a screenshot when I launch the EW App.

I understand the EW will not show correct balances until the entire block chain syncs. Does this also mean that I cannot execute the DAO Withdraw until the blockchain has 'completely' synced? I tried The DAO Withdraw a month ago without a complete blockchain sync. Nothing happened. Here's a screen shot of the transaction and none of the DAO was withdraw from the Main DAO.

Any guidance would be appreciated.


texts: Confusion about usage of throw in Solidity by Example docs

texts:
It seems like the usual way of handling a failed send in the Solidity docs is to use throw. I was confused when in the withdraw function of the blind auction example they don't use throw and instead manually set the state back to before the call was made. I was wondering why they decided not to use throw here?

        if (!msg.sender.send(amount)){
            // No need to call throw here, just reset the amount owing
            pendingReturns[msg.sender] = amount;
            return false;
        }


texts: Where are "pending" (newly submitted) transactions stored?

texts:
First of all, my terminology may be off, sorry about that.

I understand how a blockchain holds data on transactions that have been "accepted" (i.e. a block has been mined). But if I decide to transfer from 0xA to 0xB, where is that stored (before it makes it into a valid block)? Is it sent to a specific node and then shared between other nodes as a "possible" transaction?


texts: overload standard erc-20 methods in solidity

texts:
Can I overload and use standard ERC-2O methods?
For example:

Standard function : transfer(address to, uint tokens) public returns
(bool success)
Overload function : transfer(address to, uint tokens,    uint param1,
uint256 param2)
standard function: transferFrom(address from, address to, uint
tokens) public returns (bool success)
Overload function:
transferFrom(address from, address to, uint tokens, uint param1,
uint256 param2) public returns (bool success)


texts: Any idea how to add new contracts into drizzle react app using the address?

texts:
I have a react app which creates new contracts. lets say A creates B.
I have the addresses of the newly created contracts of B.

How do i add the newly created contracts of B using its address to drizzle so i may use it.

Code examples would be helpful.


texts: Will pooled staking be implemented using multisig deposits?

texts:
Would this be a valid implementation for an ether staking pool if the goal was to eliminate the need for depositors to forfeit control of their ether to the pool owner?

Depositor creates a contract and sends the ether they wish to stake to that contract
The contract controls 2 of 3 keys in a multisig address and the pool owner controls the other key
The pool owner calls a function in the contract, providing info on the block they want to vote on
The contract would then generate a signature for the block using one of the depositors two keys and return the signature to the pool owner
The pool owner would also create a signature using the key they control
Together, the signatures from the depositor and pool owner constitute proof of ownership of the staked ether and therefore a vote for whatever block the pool owner provided info on
The pool owner would then be able to submit a vote and repeat the process all over again
The contract would have a spending limit of 0 ether unless the keys used to sign a tx included both of the depositors keys (prevent pool operator from stealing funds)

I was reading about the necessity of speed in updating block votes to reduce lost funds due to DDoS here, and was trying to think of possible implementations that would prevent the depositor from introducing additional delay into the voting process.

If the pool needed to request a signature from a depositor, and the depositor had their ether staked using an 'EthPool-Qt' client running locally that generated signatures for the pool, wouldn't the delay introduced by the network significantly increase the potential not switching votes fast enough, getting left on the losing side, and therefore losing the ether at stake?

Do you think pools that require depositors to forfeit control of their ether will have an advantage in staking because they can simply vote on blocks because they would literally own all of the depositors ether and could create votes without needing to collect additional signatures?


texts: How to pass a struct as an argument in call using web3.py

texts:
Following is a working code on remix. It is recommended to use memory keyword for the struct parameter.

Please also see: Solidity Storage Array Bugs

Which does not work on Web3.py and gives the following error:

ValueError: No matching entries for 'tuple' in encoder registry

[Q] How could I fix this error?

Example code:

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

    contract HelloWorld {

        struct User {
            string name;
            uint age;
        }

        User[] users;

        function addUser(User memory user_) public  {
            users.push(user_);
        }

        function getUser(uint index) public view returns(User memory) {
             require(index >=0 && index < users.length);
           return users[index];
        }
    }

user = ["hello", 10];
HelloWorld.transact().addUser(user);


texts: How can we integrate IPFS with ethereum in DApps?

texts:
How can integration of IPFS with ethereum be done in DApps?
Which parts of a DApp will be on IPFS?
Do any examples exist?
If a DApp's site is hosted on github, is it not centralized?


texts: private network - preallocate units off the chain and release those in specific time intervals

texts: is there a way to pre-allocate x amount of ether units off the chain - not through genesis.json  - and release y amount every z amount of time in the private network ?


texts: What is the equivalent of keccak256(uint256(4) . uint256(1)) in web3?

texts:
This line :

keccak256(uint256(4) . uint256(1)) in web3?

is taken from this Ethereum web page:

http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage

How would I write this line using the web3 JS module?


texts: HashMaps: How to handle duplicate keys & retrieving multiple entries all at once

texts:
I want to write a smart contract that:

Stores education certificates within the contact, and
Allow the users to search these records.

Each certificate is represented by a struct, Cert.

struct Cert {
 uint256 ipfsId;
 address issuerAddress;
 address recipientAddress;
}

Once a struct is created I store them in maps so it's easier to retrieve them.

The user can retrieve certificates base on the certificate's ID, the issuer's address, or the receiver's address.

mapping (uint256 => Cert) certificates;
mapping (address => uint256) certificatesByIssuer;
mapping (address => uint256) certificatesByRecipient;

My issues are with the maps certificatesByIssuer and certificatesByRecipient.

Both maps can have duplicate keys if the same issuer issued multiple certificates
I can only retrieve one certificate at a time from the map which can be a problem if the same issuer issued multiple certificates.

Question:

Is there a way to avoid key duplication in my case? (For instance, switching the uint256 variable in both maps to a dynamic array, but how would I update the array then?)
Even if I resolve the issue in part 1, is it possible to retrieve multiple entries from the map all at once? (I plan to let the user interact with the contract through HTML browser interface.)


texts: Ethereum node wont sync on Widows 10, transferred eth through shapeshift and it wont show up in wallet

texts:
I recently created an ethereum wallet through the latest update of mist/ethereum wallet off github. I also transferred some decred through shapeshift into my ethereum wallet on the account. I'm very worried I've lost my funds.

However, the node wont sync. At one point, it displayed "4,465,185 blocks out of 4,465,035) and still wouldn't display my funds.

I tried deleting the chainlink directory from the appdata folder but that didn't work. Just made me restart the block downloading process.

I'm very new to the blockchain and don't have adequate programming knowledge. Any help would be greatly appreciated. I especially want to access my funds and know they're still available.

Thank you.


texts: After building from Quorum source, I can see Swarm as on the binaries. How can one get Swarm to work alongside Quorum?


texts: find & download all smart contracts deployed?

texts:
is there any existing tools that can find & download all smart contracts deployed on Ethereum blockchain, regardless they have source code or not?

if there is no such a tool, what is the best way to implement one? i suppose we can look at all the transactions sent to 0x0, but this requires access to a big full node?

thanks.


texts: Accessing External Contract's Struct Array mappings

texts:
I have struct in an external contract that I need access to

Contract Ext{
 Struct user{
    uint dailybalance;
 }
 mapping ( address => user[] ) userDailyBalances;
}

How do I access the dailybalance for a specific index in the mapped array of structs?

Contract Need{

   function need(){
      Ext x = Ext ( Extcontractaddress );
      uint256 bal = x.userDailyBalances( msg.sender )[0].dailybalance;

  }
}

Does not work nor does
x.userDailyBalances( msg.sender[0].dailybalance )
nor
x.userDailyBalances( msg.sender.[0].dailybalance )


texts:
Regarding the fact that in Proof-of-Stake, a stakeholder will be elected randomly as the next author of the next block in each epoch (or each round or slot), logically, in each round (or slot) there is only a single author of block, and so a single proposed block. With these conditions, and whether this new block will be validate or not by the rest of the network, is there still the possibility of occurring a fork in each round? (As in each round a single author is selected.)
IMPORTANT : In this question, I mean "slot" by saying "round" and "epoch".
Related questions:
Proof-of-Stake: How to prevent someone from being always selected as an author of block?
How to select the next author of block in Proof-of-Stake?


texts: "Signing" a Smart Contract after it has been deployed

texts:
I've been tasked with writing a Smart Contract to create NFT/digital collectibles. For the most part, I'm using a standard ERC721 contract.

I will be responsible for deploying the contract. Is there a standard way this company can securely endorse this contract as the official one?

My initial thinking is to have them sign a message containing the deployed contract address and adding that signature after deploying it.

Thoughts?


texts:
I'd like to create a contract through which people can set publicly available key:value information in exchange for some Ether sent to me (the owner of the contract).
This is to create a public decentralized database on which anyone can read and write, and the Ether cost would be to limit spam.

However, I'd like it to be free for all users to retrieve any key stored in the contract. My understanding of Ethereum is limited, is this possible?


texts: Help Storing Smart Contracts For Later Use

texts:
I am a new blockchain developer and need some advice.
I understand that when I deploy a smart contract on my private network I receive a transaction hash and an address of the smart contract. If I we're to interact with a smart contract from another node I understand that I need a copy of the smart contract ABI and the address of the smart contract on the network.

What is the proper way or suggestions to store these pieces of information so I can interact with that particular smart contract sometime in the future?


texts:
Im trying to make some test using the remix test library. I create a VM with a Ubuntu Server 18.04 I update the system to latest version and I install npm and node.

I generate a folder with the following files according to the web page example

Inside test.js I have write this piece of code:

const RemixTests = require('remix-tests');

remixTests.runTest(simple_storage_test.sol, contractObj, testCallback, resultsCallback);

I have many doubts

params like contractObj, testCallback, resultsCallback i think that I have to change. What is the expected value according to my files?

2.Once this is executed I have some result file or just appear in the terminal screen?


texts: How to get the returned value from the delegate call on the function of another contract?

texts:
Here is my example:
contract A {
    function a() public returns(uint256) {
        return 1;
    }
}

contract B {
    address addrOfA;
    function b() public returns(uint256) {
        (, bytes memory returnData) = addrOfA.delegatecall(abi.encodeWithSingature("a()");
        return uint256(returnData);
    }
}

What should I do to make the b() return 1? How to deal with the return value returnData so that I can get the value 1 from the delegate call on a()?


texts: I've been looking for an api similar to bloopi (not local), which gives you ability to quickly and easily create a wallet. Do you have any suggestions?


texts: Pros & Cons of Using the "wei" Method to Track User Deposits in Ethereum

texts:
With Ethereum it's  notoriously difficult to accept deposits from many users due high operational costs for making new ETH addresses. On the other hand, if all users of a service send ETH to one address it would be impossible to track who sent which funds.
To solve the tracking issue when sending funds to a single address, a user suggests using the "satoshi" method as a marker for user deposits in Bitcoin in this question.

Another method I’ve seen used on bitcoin is using satoshis as a
marker. For example, when paying for a one bitcoin item, an additional
7 satoshi could be added to the amount due to distinguish from another
user asked to add 6 satoshi. Payments must be in exact amounts for
this to work (but you can always refund an incorrect payment, less
fees, to a sender). This does not scale all that well if your IDs must
be permanent. This avoids the need for users to interact with a
contract to include metadata.

In short, the method allows all users of a service to deposit funds to the same Bitcoin address while allowing us to keep track of who deposited which funds.
I would like to know if this concept can be applied to Ethereum.
Off hand I can think of two potential issues with this method:

If we reserve 1 ETH address for 100 users, we are adding a minuscule amount of $$$ to each payment
It only works when we know in advance how much the user intends to deposit (otherwise there's no way of calculating how much extra "wei" was added to a payment (so it won't work for general deposits)

What are some of the other pros and cons of using this protocol to keep track of user deposits? Are the issues above solvable?
Thanks


texts: User experience while using sendTransaction

texts:
What is best practice for user experience when sending a transaction? I was blocking UI with a spinner.
I am doing this:
//BlockUI

const sentTransaction = await sendTransaction(transaction)
persistTransactionInDB()

//UnblockUI

This is sometimes taking over 60 seconds to get a response with a transaction, and hence a transactionId I can use to track it.
I could do :
const regularTransaction = sendTransaction(transaction).then(res => persistResponse)

alert('well done, we'll let you know')

...but then if the user navigates away from the page then my function isn't executed?
What is the best way to do this?
Can I or should I somehow off load this to a worker or something?


texts: How does Ethereum plan to handle thousands of transaction per second?

texts:
The one issue I've been thinking about Blockchain is scalability. I see that the execution time of API calls (transactions) is slower than with legacy applications. So in the coming years, if Blockchain is adopted globally and there are requirements to mine thousands of transactions (probably more than this) per second, how does the Ethereum community plan to handle this situation?

If this question is already answered then please point me to the answer, I couldn't find it.


texts: Truffle Drizzle: Passing String address results in Invalid Number of Parameters

texts:
I have a view function in my contract that takes an address as a parameter and returns a uint:

function getNumber(address _address) public view returns (uint) {
    require(_address != 0x0);
    return theList[_address].length;
}

In my App.js:

this.contracts.TheContract.methods.getNumber(this.state.account).call()

where:

this.state.account

is set in the constructor

Result:

Error: Invalid number of parameters for "getNumber". Got 42 expected 1

I tried converting to a byte array but that produces other errors.

Any Ideas?

Thanks


texts: Can cross-chain atomic swaps be implemented for ERC721 too? What are some limitations, if any?


texts: Use full ethereum balance for token transaction

texts:
I want to use whatever ethereum is available in my account as transaction fee to send a token transaction. I know the gas I need, so in theory I thought the following formula would work:

gasPrice = balanceInWei / gas

so I tried with 0.001 ETH:

gasPrice = 1000000000000000 Wei / 130091

which results in 0.000000007686926843 ETH per gas unit

But I got

  Error: Returned error: insufficient funds for gas * price + value

I am sending no value, so in theory the gas * price do match the funds.

What am I missing? Do I have to use a minimum of 1 gwei as gas?

I am using Web3js version 5.6.0. Here's the code:

function main() {
    console.log('Transferring from address 0x8..');
    web3.eth.getTransactionCount(SOURCE_WALLET_ADDRESS).then(function (nonce) {
        console.log('The nonce is ' + nonce);
        web3.eth.getBalance(SOURCE_WALLET_ADDRESS).then(function (balance) {

            console.log('Balance ' + balance);
            sendTransaction(nonce, balance);
        });
    });
}

function sendTransaction (nonce, balance) {
    var tokensToSend = '1000';
    var contract = new web3.eth.Contract(abiArray, CONTRACT_ADDRESS, { from: SOURCE_WALLET_ADDRESS });
    var balanceInWei = balance * 1000000000000000000;
    var gas = 130091;

    // Find out gas price to use full eth balance
    gasPrice = balanceInWei / gas;

    console.log('\r\nStarting transaction. with nonce ' + nonce);
    console.log('Gas price : ' + gasPrice + '\r\n');

    let details = {
        "to": CONTRACT_ADDRESS,
        "from": SOURCE_WALLET_ADDRESS,
        "data": contract.methods.transfer(DESTINATION_WALLET_ADDRESS, tokensToSend).encodeABI(),
        "value": web3.utils.toHex(tokensToSend),
        "nonce": nonce,
        "gas": gas, // tx fee (gas * gasPrice)
        "gasPrice": gasPrice, // has to be in Wei
        "chainId": 1 // EIP 155 chainId - mainnet: 1, rinkeby: 4
    }

    const transaction = new EthereumTx(details);
    transaction.sign(Buffer.from(WALLET_PRIVATE_KEY, 'hex'));
    const serializedTransaction = transaction.serialize();

    web3.eth.sendSignedTransaction('0x' + serializedTransaction.toString('hex')).then(function (transId) {
        console.log('My job here is done. ' + transId.transactionHash);
    });
}

main();

Example output:

*** PROGRAM START ***

Transferring from address 0x8Df3..
The nonce is 71
Balance: 0.003703316

Starting transaction. with nonce 71
Gas price : 28467119170.426853


texts:
In MyContract, I am providing special rights to the manager. But after some time and for some reason, I want to invalidate the manager. The following is my approach:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract  MyContract{
    address manager;
    constructor(){
        manager = msg.sender;
    }

    function invalidate() public {
        require(msg.sender == manager); // Only manager can invalidate itself
        manager = address(0);
    }
}
Is the right way of doing this or does this have some loopholes?
Reference to 0 address behavior.


texts:
Why contract addresses are larger than account addresses?

For example:

'0xb794F5eA0ba39494cE839613fffBA74279579268' - This is an account address
'0x756d5ef58a6617002255726a99b3b72f4c30ea25fc2be2de0c6bede5a71e4e54' - This i s a contract address

Why is this?

Also, when I need to call MyContract.at(myAddress)with web3.js I need to shorten the contract address (instead it gives you an invalid address error). Any idea on how to do it?


texts: Do users of ERC20 coins need to hold Ether?

texts:
Suppose there exists Fancycoin, an ERC20 altcoin which has some functionality implemented by the EVM. It does some nontrivial things that take up gas.

According to my understanding, I can receive Fancycoin in my wallet if somebody sends it to me, without having any ether myself.

My question is: if I have Fancycoin and I want to use it to do something (maybe it checks an oracle, or does compututations with some data internal to a block, etc.) but I don't have any ether in my wallet, will I be unable to use any of the features of Fancycoin? As mentioned in the answer to the question linked within the first comment below, I probably will not be able to send Fancycoin to someone else.) However, could functions in Fancycoin requiring gas be paid in Fancycoin somehow, and not ether?

Answering the above counts as an answer to my question, but in case you want to expand: I think most generally I'm interested in how coins built on top of Ethereum interact with ether. I don't understand this.


texts: Deployed contracts without Solidity code

texts:
I reviewed lots of contracts on etherscan and I have noticed lots of them are without published Solidity code. In my opinion there is no point of using/publishing a contract without the Solidity code, it breaks the whole concept of Smart Contracts. If one can not verify the Solidity code of Smart Contract he is interacting it, what's even the point of using Ethereum then ? Do you think it should be obligatory in some way to publish the associated code ? I know one can decompile the bytecode to assembler like commands, but uhhh it should be more transparent right ?
I believe on the etherscan.io the published solidity code is not stored in the ethereum blockchain, but only in some interlan etherscan.io database.
I know it would take a lot of space in the ethereum blockchain to store the Solidity code....


texts: Web3 promise stuck on pending on forked mainnet

texts:
I am trying to run a method and the return is stuck on promise pending, if i have to do await it still stuck waiting for return. I have no idea why this happen, i log the value of localWeb3 and it returns an object without a problem
There is the snippet:
txChecker = async () => {
const localWeb3 = new Web3(
      ganache.provider({ fork: "wss://eth-mainnet.ws.alchemyapi.io/v2/apikey" })
    )

console.log(localWeb3) // image attached

console.log("latest_block forked 1: ", localWeb3.eth.getBlockNumber()) // promise state pending, value undefined

console.log("latest_block forked 2: ", await localWeb3.eth.getBlockNumber()) // black
}

Why is this happening and how do i resolve this issue?


texts: Should I set an extremely high gas price while participating in a popular token crowdsale?

texts:
Am I right that

Gas amount in this case is constant or at least predictable

How to figure it out? Using this answer? - How do I know how much gas to use when calling a contract?
Or maybe there is some average 'recommended' gas amout for this kind of contracts?

Setting gas price higher and higher is the best strategy for each competing buyers that is natural due to high demand to get tokens first

How to figure out the adequate price?
What can it depend on (interest in particular token, contract specificities, number of buyers...)?
Can I use the normal price not being a looser?


texts:
I’m new in NFT and Rarible as NFT sell point.
I have enter one of my images to sell, but after 2 days of pending signing contract in my Coinbase  Wallet, I received message “failed“.
I have started all over again (for same image) and then second attempt passed and everything was fine, but then I noticed that it has took Etherum also for the first failed attempt and put same image on sell.
So, I was charged $120 in whole for miners and gas, so what now?
Is there possibility to change image in that first contract?
What is “Transfer token”? Can I do anything here and not loose $60?
As I see, this is Coinbase Wallet error, there was obviously end of signing attempts, because it stop spinning and I received Failed message.
Why did it then charge me anyway? Or this will try endlessly (even if I got failed message) until contract pass?
Thanks in advance for helping me here.


texts: truffle migrate does not return anything

texts:
I am following the tutorial from Truffle to create a "pet shop" contract. I can follow everything until he tells me to truffle migrate.

Here is the contract:

pragma solidity ^0.5.0;

contract Adoption{
    address[16] public adopters;

    function adopt(uint petId) public returns (uint) {
    require(petId >= 0 && petId <= 15);

    adopters[petId] = msg.sender;

    return petId;
}

function getAdopters() public view returns (address[16] memory) {
    return adopters;
}
}

The migrate #1:

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

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

The migrate #2:

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

module.exports = function(deployer) {
  deployer.deploy(Adoption);
};

The network seems to be configured right on the truffle-config file

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // for more about customizing your Truffle configuration!
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    }
  }
};

And Ganache(testing) seems to not have mined any blocks even though the network is right:

It is weird, I haven't found anyone else with the same issue as me, any ideas?


texts: I'm wondering about how selfdestruct() actually works. Does it actually delete contract codes from the storage? Or just delete the contract address from state trie? If just deleting the contract address from state trie, does other new contract code overwrite it?


texts:
How can I send eth on specific time?

In case the ICO crowd sale starts on 9:00:00 UTC, how can I make txid on 9:00:00 exactly when I send eth?


texts: Ethereum taken from MEW? Any way to trace owner?

texts: can anyone help with this. I think somebody has stolen all my ether from my ether wallet. Their address on etherscan is here: https://etherscan.io/address/0x4b03b72d8ce714b14efe4843170a219c02a3f5c2 and the 6.9547 Ether in is from my wallet. I haven’t done any transactions today so it can’t be a wallet on an exchange that I’ve forgotten about. Does anybody know what I can do about this?


texts:
I understand web3 can be basically used for every existing task, however, is there anything we can use for C? My C program is communicating with the RPC server using the curl library, by posting JSON data to the server via HTTP. However, the data of a transaction part, currently, I have to get the hex code from somewhere else(web3.js Remix etc.).
Is it possible for me to construct the hex code of a function call in C directly without relying on calling a javacript program using system(node ...)?
I understand SHA3-256 is used for hashing a function call using the abi information and parameter information, however, the sha3-256 generator that I have used do not produce the same result as web3. Calling system(node ...) is too slow.
I want to use C because C is often faster... And my project requirement, it has to be C.


texts: Always get `Dai/insufficient-allowance` error

texts:
Scroll for EDIT
I'm using Solidity 0.7.5 and I'm trying to swap DAI to ETH from my account, through UniswapRouter02.
Here's my environment

REMIX IDE
Metamask with KOVAN testnet
I have about 2 ETH and 3 DAI on my linked account (msg.sender).

And my code follows
pragma solidity >=0.7.0 <0.8.0;

import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";

contract UniswapExample {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

  IUniswapV2Router02 public uniswapRouter;
  address private kovanDAI = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
  address private myAccount = msg.sender;

  constructor() payable {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
  }

  function convertDAItoETH(uint daiAmountIn, uint minETHAmountToReceieve) public payable {
    IERC20 daiToken = IERC20(kovanDAI);
    require(daiToken.transferFrom(myAccount, address(this), daiAmountIn), "transferFrom failed");
    require(daiToken.approve(address(uniswapRouter), daiAmountIn), "approve failed");
    uint deadline = block.timestamp + 15; // using 'now' for convenience, for mainnet pass deadline from frontend!
    uniswapRouter.swapExactTokensForETH(daiAmountIn, minETHAmountToReceieve, getPathForDAItoETH(), myAccount, deadline);
  }

  function getPathForDAItoETH() private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = kovanDAI;
    path[1] = uniswapRouter.WETH();

    return path;
  }
}

I followed the example from various YouTube videos and from Uniswap (https://uniswap.org/docs/v2/smart-contract-integration/trading-from-a-smart-contract/).
I encounter 2 problems.
First, when I click convertDAItoETH with param 280000,0 (random number with 0 ETH lower-limit)

I get this message.

When I ignore it and click Send Transaction, and go through Metamask to confirm the transaction, my transaction is failed soon. And this is my second problem.
When I go to etherscan and see the transaction details, it tells me that it failed
Failed with error 'Dai/insufficient-allowance'.
What does this even mean? As you can see, I have 3.5 DAI, so swapping 280000 DAI should be Okay.

Please help. Barely started learning this, but I just simply cannot find any good resources on how to debug this type of error.
Thank you!
EDIT
I moved my network to Ropsten.
I've created a function
  function setSmartContractAllownace(uint daiAmountIn) public {
     daiToken.approve(address(this), daiAmountIn);
  }

When I run this it successfully ran through (tx: https://ropsten.etherscan.io/tx/0x1a3b29699f353938f7e8b1825ff69aa44e262d90165e87b107131fc5813d05e3)
And then I go to https://ropsten.etherscan.io/address/0xaD6D458402F60fD3Bd25163575031ACDce07538D#readContract to check the allowance.
_owner (address)
0x548F97658C6acb9a5A0B034116E79bcF98B9a15a  -> (my account)
_spender (address)
0x99941f04C4a1cba96c237e02F1B2f2b3C5Bae5ea  -> (my contract)

returns 0.
However, if I enter both _owner and _spender as my CONTRACT address, I get what I set to.
I thought approve(spender, amountIn) approves owner (account)'s token for spender (contract in this case) to spend.
What am I misunderstanding?