texts: What are good ways to randomize a million people into pairs?

texts:
I came up with this, each person invokes the function that randomizes them into a pair, it generates a random pair, and if that pair is full, the function scans through pairs until it finds a vacant one. The contract memorizes regions that have been scanned through, and other people do not have to re-do the work that people before them have done, so that the last couple of people should be able to find a vacant pair.

contract randomizePairs {

    uint population_size;
    mapping(address => bool) inPopulation;
    mapping(uint => address[]) pair;
    mapping(address => uint) inPair;
    bytes32 entropy;
    mapping(uint => uint) iterationMemory;

    function commit() {
        require(inPopulation[msg.sender] == true);
        require(inPair[msg.sender] == 0);

        uint[] memorize;
        uint pairNumber = uint64(sha3(sha3(block.blockhash(block.number), entropy), now)) % (population_size / 2);

        if(pair[pairNumber].length < 2) {
            pair[pairNumber].push(msg.sender);
            inPair[msg.sender] = pairNumber;
        }
        else {
            memorize.push(pairNumber); // memorize from this point
            for(uint i = 0; i < 100; i++) {
                pairNumber = (pairNumber + i) % (population_size / 2); // continues from 0 when it reaches population_size
                if(pair[pairNumber].length == 2) {
                    if(iterationMemory[pairNumber] != 0) {
                        memorize.push(iterationMemory[pairNumber]); // memorize from that point
                        pairNumber = iterationMemory[pairNumber] - i; // skip the pairs that have been scanned by other people
                    }
                }
                else {
                    pair[pairNumber].push(msg.sender);
                    inPair[msg.sender] = pairNumber;
                    break;
                }
            }
            // record the regions with full pairs up to the current pair
            for(uint m = 0; m < memorize.length; m++) {
                iterationMemory[mem[m]] = pairNumber;
            }
    }
    }
}


texts: Does Using Infura Breaks Decentralization?

texts:
Decentralized applications have a philosophy: they are immutable,secure and trustless applications. You can connect to Blockchain and be sure about that features.

Infura is a great tool when communicating with Blockchain. However, Infura has its own API which connects you to Blockchain or IPFS. So, as similar to a middle man, doesn't it break the philosophy of decentralization?


texts: URGENT-refinding the private key in metamask

texts: when I added the extension on a different laptop and I tried to access my account, metamask asked me to insert a new password and to confirm it OR to insert the 12 words phrase. I had not the 12 words phrase (having to leave my home and not imagining I will need the phrase or private key so soon), so that I inserted the same password I had, as a new one. And I was expecting to find my ETH address, filled with the ETH I had...But no, metamask created a new ETH address in which I had 0 ETH and a new 12 words phrase. In that account (accoun 1), at the top of the page, the new ETH address had a link (which contained the new eth address too) . Then, in that link, I replaced the new ETH address with the old ETH address (which is connected to Empowr). And I refound the old/initial ETH account/address whereI had some fractions of ETH....However, I do not have the private key for it....and I need it urgently. Also, that old ETH address does not have an account (Account 1, account 2 , account 3 etc) corresponding to it, so that the new ETH address has I need to import the old ETH address/wallet and I need its private key...So, Can you help me with this to know what to do ?


texts: Array lenght and data miss match while storing data of events

texts:
Can someone help me in finding what is wrong here a why the length of task info is 0 even the taskInfo has some data. I'm using events to fill the taskinfo array.
I'm stuck at this place for almost 2 days and cant seem to find what is wrong here
any kind of help is appreciated[


texts: Can I edit or delete the deployed contract to Binance smart chain?

texts:
I have created a token and deployed it to Binance smart chain. I wonder how to edit and fix some bugs and deploy it again? I edited the existing source code and deployed it again, but it again created a new contract with the same token name! how about the previously deployed contract? right now I have two contract for one token. How to delete the previously created token and its corresponding contract or if I can edit its source code. Where the source code deploy and can I access it?
I am using https://remix.ethereum.org/ web site for development and deployment.


texts: Naming conventions for ERC-20 instancies

texts:
Given a contract that implements ERC-20. Is there a naming convention for new instancies such as its symbol? We are used to 3 chars but that range will run out at some time in future.

I am asking because I suspect that market places and wallets for tokens cannot deal with long symbols.


texts: How can I distribute funds to present stakers efficiently?

texts:
I am building a smart contract which keep the token holder's eths for a while and give them rewards when they withdraw. The reward is given from the ethers collected by early withdraw of people. If someone made withdraw before the time period expires then he has to pay penalty fee and that penalty fee will be distributed to the token holders who have their deposits in contract currently at the moment when penalty fee was paid.

My question is that, how shall I do it efficiently to distribute penalty fee? The reason to ask this question is:

if penalty fee is so small then dividing it at that moment among all token holders will make each share even more smaller and i am afraid if the solidity doesn't write 0 instead of 0.9 weis (may be)

The second point i am thinking of is that how to efficiently allocate the rewards to stakers currently present in contract? If the people who have their deposit in contract (stakers) is above hundred or thousands, then alloting the reward to each one of them will need me to iterate over the complete array or something, this will require more gas and I am not sure if it will always be successful even for million stakers?

I need to keep a record that which penalty fee is deserved by which stakers.

I am looking towards the best efficient and low gas consumption implementation.


texts: How to split potentially large transactions

texts:
I am trying to implement a simple lottery as a pet project and to get into solidity coding.

I am running into an issue and I wonder what is the best way to solve it. Basically during a timeframe of a draw x participants take part. X could potentially be very big, lets say 10k. At the end of the draw winning numbers are being generated and I need to go through all participations and check whether they have won and how much. Both would be public methods accessible only to the owner.

Problem
What can I do to not run into out of gas issues, especially hitting the maximum gas per block limit when the number of participants gets too large?

Now I see two ways to solve this:

method 1:

have a method that returns the amount of participants
have a central service that paginates through that amount by lets say 50 each and calls a "determine winners" method
have a method that then calls the payouts
do the same paginated method calling for the payouts

method 2:

have a determineWinners method that iterates through lets 50 of the total participants to check for winning numbers
when done and there are still unchecked participants left, store the last iteration variable (eg 50 or 100 aso) and create an event that lets a central service know, to call that method again until done
do the same for payouts

In general I don't like the heavy dependency on the centralised control authority of the contract.
Also both methods would be very slow. Determining winners out of a pool of 10k in steps of 50 and a block time of 20 sec would already take more than an hour. 200k users would not work anymore if I run the lottery on a daily basis.

Is there some sort of best practice on how this can be done?

Do the methods presented make sense? Which one is preferable?

Are there other ways?

Thanks a lot for your help.
Gordon


texts: Issue with contract verification on Etherscan

texts:
I have successfully deployed a new token contract on Etherscan Ropsten Network using metamask. I see my contract listed as "Unverified" so I followed the process given on https://ropsten.etherscan.io/verifyContract to get it verified but was unsuccessful with a message as follows:

There are no changes done to the code. Kindly, suggest me what i'm missing here?

Other Information:

Contract Address: 0x0890fe640F27a74665E1Fdb5A0c532e154B7020e
Token Name: CWF Currency
Token Symbol: CWF


texts: Quorum - Track State Variable Changes in Struct (Data Lineage)

texts:
I am unable to get my bytes32 variable state transition within a struct in Quorum. What I did is to I build a dashboard to loop through the blockchain to search for a particular then list out the block number, from, to, etc.

Though I am only able to get the transaction input that changed the state variable, I am not able to get the bytes32 variable change transition itself. E.g., NEW -> SUBMITTED --> CLOSED

I read on this forum many approaches -- using events, add to another array. I believe all these to be workarounds.

Are there any elegant solution to achieve this within Quorum? To track the state variable change, instead of just getting the transaction input that changed the variable state? Data Lineage is a key attribute of distributed ledger.

Thank you.


texts: Correct way to verify address server-side with Web3

texts:
I'm trying to use web3 1.0 to authenticate users on a web server. Instead of having unauthenticated users submit a username and password, I want them to send their address (public key). I'll respond with a random message for them to sign, then use web3.eth.personal.ecRecover (server-side) to verify the signature came from the same address before returning a cookie for the session.

Two questions:

Does this approach make sense? Am I reinventing the wheel?
Is web3.eth.personal.[sign|ecRecover] the pair of functions I should actually use? There are also web3.eth.sign, web3.eth.accounts.sign and web3.eth.accounts.recover. Looking at the web3 source code, web3.eth.accounts.recover might be an even better option to use on the server-side because it doesn't need to contact an ethereum node.


texts:
I'm new to Ethereum and solidity, I'm developing a simple decentralized application using Truffle where I have an abstract contract Storage and another contract Reader which uses storage.

contract Storage {
    function getWeight() public view returns(uint8);
    function setWeight(uint8 weight) public view returns(bool);
}

contract Reader {
    Storage private storage;
    constructor(address storageAddress) {
        storage = Storage(storageAddress);
    }
}

I'm trying to write unit test for contract Reader, is there anyway to mock the behavior of the abstract contract? If not, then what is the best practices for that situation?


texts: find the bytecode of a contract during compilation

texts:
Is there a solution to recover the complete bytecode (init + runtime) of a contract imported in solidity.
For example "bytes code = getBytecode (Escrow.sol)" and this would be replaced by bytecode during compilation?
thanks a lot for your help


texts: Trigger a smart contract token transfer by a third party

texts:
I've created an Ethereum token that could be transfered from user to user.
As a next step I would like to write a smart contract that transfers an amount of tokens from user A to user B when a specific state has been reached.

Example:

User A has 10 tokens.
User B has 1 token.
Third party company registers actions of the users on their website / app
All users trust a third party company.

User A agreed with the 3rd party that it is allowed to transfer 1 token to user B when condition 1 is met. For example if user B clicks 100x times on a specific button.
Interaction between User B and the third party company should trigger the transfer. User A allows the 3rd party to transfer tokens.

How can I put such logic in a smart contract?
I've found smart contract examples online where a smart contract is linked to another smart contract (3rd party) which tells if the condition is met or not. This does mean that all the clicks need to be registered on the blockchain?
The condition will be different for each other user, for example a different interaction or different number of tokens.


texts:
Happy new year to everyone.
Watching my contract events is quite time consuming (more than 15 sec to find the first event).
I'm using this kind of command in my geth console :

mEvents = myContract.myEvent({}, {fromBlock: myBlockContract, toBlock: 'latest'});

Do you have any advice to help me to speed up the event filtering ?
(my geth node is running on a small vm : 1 vCPU, 3,75 Go RAM)

Edit : my geth node was synchronized with --fast. Fast mode should download the event log according the doc, but maybe not ...


texts: ethers.js (node.js) call solidity function that is payable

texts:
I understand that you can send ethereum to a smart contract, although when you do this with sendTransaction it doesn't seem that you specify a function on the smart contract when you do this. I don't quite understand how this is useful.
However what I can't find out how to do, is to send ethereum to a function that is set as payable.
I'm using ethers.js and can create a contract, and call functions that are viewable (read only) no problem, but I cant work out how to send ethereum with the transaction to a specific function

export const testContract = async (address, abi) => {
  const wei = Utils.parseEther("0.1")
  const url = "http://localhost:8545"
  const provider = new Providers.JsonRpcProvider(url)
    // Load the wallet to deploy the contract with
  const privateKey =
    "0x123"
  const wallet = new Wallet(privateKey, provider)

  var contract = new Contract(address, abi, wallet)

  const price = await contract.retrievePrice()
  console.log("price " + price) //logs the price set in the constructor when the contract was made (WORKS)
  const testAddress = await contract.isUser(
    "0x456"
  )
  console.log("testAddress ", testAddress) //checks if the given address is a user on the contract (WORKS)

  const gasPrice = await provider.getGasPrice()
  console.log("gas price: ", gasPrice.toString()) //returns the price of gas from the network (WORKS)
  try {
    const addToUsers = await contract.requestAccess({ //call function to request access, from the current wallet (REVERTS)
      value: wei
    })
    console.log("result of sending transaction ", addToUsers)
  } catch (error) {
    console.log("error.... ", error) //fires as the contract reverted the payment
  }
}

Any help as to why calling contract.requestAccess is reverting on me? I can't quite work out how to call a specific function and send Ether.
Thanks!

Response to comment

Ok right, so the function in the solidity contract looks like:

  function requestAccess() payable {
    require(msg.value == price, "Incorrect sum sent to contract");
    _addUser(msg.sender);
  }

I commented out the require, to try that but still reverts. _addUser is from a contract mine inherits from, and looks like

  function _addUser(address account) internal {
    users.add(account);
    emit UserAdded(account);
  }

users is Roles.Role private users; and sits in the parent contract

contract Users {
  using Roles for Roles.Role;

which imports from openzeppelin "openzeppelin-solidity/contracts/access/Roles.sol"


texts: Is using Ethereum to trade in betting markets legal in US?

texts:
Right now the betting market in US is regulated by CFTC and some sites like PredictIt have $850 limit per contract to be compliant with CFTC.

I have seen some  prediction markets like Augur that use Ethereum for betting. Is it legal for betting in US using Ethereum ?


texts:
When we develop and run a non-decentralized application it causes costs for using cloud server.

How much does it cost to develop and run dApp on Ethereum or Hyperledger fabric? Which one is cheaper?


texts:
Is there a way to get the account balance of any given address (address which is not belongs to me) using geth or by using a script which reading leveldb?

Similar to how etherscan (https://rinkeby.etherscan.io/accounts) showing balances.


texts:
I know that the latest Solidity supports error messages in require/revert (require(stuff, "problem")).

Are there any clients that can get this message? Will I be able to see it if I execute the transaction in Parity, or Truffle, or Remix? Will it be visible on Etherscan?

EDIT: a similar question has been asked before (Custom error message in require() not showing up?). That one was about web3 not displaying the message. I know web3 doesn't support it yet, my question was about which other clients (Parity, Remix, or, maybe, just plain RPC) support it, so I believe it's not a duplicate.


texts: How to create a test contract that takes parameters?

texts:
I have a contract like so:

pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;

Contract Ballot {

constructor(string[] memory proposalNames) public {

    }
}

How do I create a test-instance of it in solidity?
I tried:
pragma solidity >=0.4.25 <0.6.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";

import "../contracts/voting.sol";
contract TestVoting {

    function testCounter() public {
     Ballot meta = Ballot(DeployedAddresses.Ballot());

    }

}

but i get an error:
 1) TestVoting
       testCounter:
     Error: Returned error: VM Exception while processing transaction: revert
      at Context.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/testing/SolidityTest.js:94:1)
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

How do I pass it its constructor arguments?
Based on this issue, it doesn't seem like it's possible to create a  parameterized test contract -- is this really the case?


texts: Can't deploy a contract that calls another contract

texts:
When I run the below code when connected to geth --dev --mine, the output is:

A transmitted, waiting for mining...
aAddress: 0xbaxxxxx4ae42d
B transmitted, waiting for mining...
bAddress: 0x47xxxxxfe8aa
53

When I run it on the live network when connected via geth, the output is:

A transmitted, waiting for mining...
aAddress: 0x04xxx76
B transmitted, waiting for mining...
[Error: The contract code couldn't be stored, please check your gas amount.]

When I replace the a.a() with 7 in the b() function, the output is:

A transmitted, waiting for mining...
aAddress: 0xbaxxxxxae42d
B transmitted, waiting for mining...
bAddress: 0x472xxxfe8aa
53

I'm running the following code with node:

var Web3 = require('web3');
var web3 = new Web3();

web3.setProvider(new web3.providers.HttpProvider('http://0.0.0.0:8545'));
web3.eth.defaultAccount = web3.eth.coinbase;

var aSource = 'contract A { function a() constant returns (uint) { return 7; } }';
var aCompiled = web3.eth.compile.solidity(aSource);
var aCode = aCompiled.A.code;
var aAbi = aCompiled.A.info.abiDefinition;

web3.eth.contract(aAbi).new({data: aCode}, function (err, contract) {
    if (err) {
        console.error(err);
        return;
    } else if(contract.address){
        var aAddress = contract.address;
        console.log('aAddress: ' + aAddress);
        deployB(aAddress);
    } else {
        console.log("A transmitted, waiting for mining...");
    }
});

function deployB(aAddress) {
    var bSource = 'contract A { function a() constant returns (uint); }'+
    'contract B { A a; function B(A _a) { a = _a; } function b() returns (uint) { uint c = 46 + a.a(); return c; } }';
    var bCompiled = web3.eth.compile.solidity(bSource);
    var bCode = bCompiled.B.code;
    var bAbi = bCompiled.B.info.abiDefinition;
    var bContract = web3.eth.contract(bAbi);

    bContract.new(aAddress,{data: bCode}, function (err, contract) {
        if (err) {
            console.error(err);
            return;

        } else if(contract.address) {
            var bAddress = contract.address
            console.log('bAddress: ' + bAddress);
            var res = bContract.at(bAddress).b.call();
            console.log(res.toString());
        } else {
            console.log("B transmitted, waiting for mining...");
        }
    });
}


texts: Why is there 2 methods abi.encode and abi.encodePacked for argument encoding

texts:
When we call a function on an external contract, the evm computes a bytes buffer which contains the function signature and arguments.
There are 2 ways to serialize arguments: abi.encode and abi.encodePacked.
The difference between this 2 methods are well documented  and i have understood them.
What i want to understand is why there are this 2 methods ? Nobody says when we should use the first and when we should use the second.
How can i see which method is used when i make this calls:
Call 1:
(success, ) = address(c).call(abi.encodeWithSignature("myfunction(uint256,uint256)", 400,500));

Call 2:
(success, ) = address(c).call(abi.encodeWithSelector(bytes4(keccak256("myfunction(uint256,uint256)")), 400,500)  )

Call 3:
(success, ) = address(c).call(  bytes4(keccak256("myfunction(uint256,uint256)")),    400, 500);

Call 4:
contract_instance.myfunction(400,500);

Thanks a lot


texts:
I am running a private blockchain and I have parity nodes that seem to be connecting just fine.  I've gotten though some geth issues that I was having before but geth still won't connect.

HOWEVER when I connect from the same computer with Parity, it seems to connect just fine.

Here is how I invoke geth the first time (not really port 9090 but that's for example):

./geth --datadir /path/to/custom --networkid 9090 --port 9090 init CustomGenesis.json

The CustomGenesis.json file has values that were manually taken from my Parity .json file, and I have successfully connected with Parity.  So I believe those values are correct. I have used the items listed here, with the parity values:
https://github.com/ethereum/go-ethereum/wiki/Private-network

I also have a file called /path/to/custom/static-nodes.json that lists the "enodes" of two existing Parity nodes.

ALSO, I have (sometimes separately and sometimes in addition to the static-nodes.json file) used the --bootnodes flag and listed the enodes of the parity nodes on the command line.

./geth --datadir /path/to/custom --networkid 9090 --port 9090 --ipcpath ~/.ethCustom/geth.ipc

However, these things happen/don't happen:

1) My other nodes do NOT show that a new node has entered the network

2) when I attach to the console at /path/to/custom/geth.ipc, and I run "admin.peers" I simply get "[]"

3) EXCEPT that once in a while I do get a peer, but it is not one of the peers on the custom network, but some seemingly random node with a port of 30303!!  So weird!  Why would 30303 be infiltrating my custom setup?

But when I type

  admin.nodeInfo

I get a very satisfying output that shows the correct local enode; the same (correct) port for "listenAddr, listener, and discovery; the correct network id, and the corect difficulty.

What am I missing?  Please let me know if there is other information I can supply.  Thank you.


texts: Contract Oriented Language Fundamentals, "God" Contracts and managing large token storages?

texts:
Just going through some of the 0x Contract Code trying to improve my understanding of solidity and Smart Contract oriented language programming.

Stumbled on the TokenRegistry.sol contract and trying to get a bit of a deeper understanding of it. In 0x there is an exchange and token registry holding all the tokens available for sale by buyers and sellers.

Are these values held in the contract, if so how can this be efficient and feasible in terms of mining and computation?

This makes the TokenRegistry contract feel like a "God" type of contract which maps all token values to addresses. Is this a usual design pattern?

pragma solidity 0.4.11;

import "./base/Ownable.sol";

contract TokenRegistry is Ownable {

mapping (address => TokenMetadata) public tokens;
mapping (string => address) tokenBySymbol;
mapping (string => address) tokenByName;

address[] public tokenAddresses;

struct TokenMetadata {
    address token;
    string name;
    string symbol;
    uint8 decimals;
    bytes ipfsHash;
    bytes swarmHash;
}
//..
function addToken(
    address _token,
    string _name,
    string _symbol,
    uint8 _decimals,
    bytes _ipfsHash,
    bytes _swarmHash)
    public
    onlyOwner
    tokenDoesNotExist(_token)
    addressNotNull(_token)
    symbolDoesNotExist(_symbol)
    nameDoesNotExist(_name)
{
    tokens[_token] = TokenMetadata({
        token: _token,
        name: _name,
        symbol: _symbol,
        decimals: _decimals,
        ipfsHash: _ipfsHash,
        swarmHash: _swarmHash
    });
    tokenAddresses.push(_token);
    tokenBySymbol[_symbol] = _token;
    tokenByName[_name] = _token;

}
//..

}


texts: How do I implement simple JS code to deploy a compiled smart contract to ganache-cli?

texts:
Everything I've tried results in strange errors, and it's been difficult to get this working. I've been struggling with this for a while, especially having problems determining which versions of web3 and ganache will work together. The code is these libraries is evolving quickly and they are constantly in flux. This results in many version combinations having broken functionality that's difficult to diagnose.

In particular, there seems to be promise handling async problems with web3 versions later than 1.0.0-beta.37, which makes them not work at all with ganache. What happens is web3.eth.getAccounts() will fail, with no known workaround.


texts:
I am new to blockchain and Ethereum. Below are queries I had when I started learning and going through different posts on Ethereum sites:

In Ethereum network, how one node will understand 51 percentage confirmed the new block creation. (is each node will have statistics i.e number of nodes active in the network)
How the transaction are getting distributed to other peers in the network. Is the transaction are replicated to nearby nodes.
How the network latency is handled across the peers (different parts of the world)
How the transaction time managed in different geography
How mining is get effected if one miner is having date setting is not updated


texts: What's a normal price for deploying a smart contract? How to make sure I don't overpay it?

texts:
I deployed a contract on the testnet and it costed about $1.

I tried in on the mainnet, it required about $50. Is this normal?

Gas Limit: 1719577

Gas Price: 40

Fee: 0.068 ether

How can I make sure to choose the right fees?


texts:
Sorry if this seems dumb, I'm just getting started w/ Solidity. These are concepts I've never dealt with. I'm trying to save space by using bytes arrays, but I'm quickly getting lost. Please help.

Source

pragma solidity ^0.4.24;

contract TestConstructorAssigns {

    mapping(uint8 => bytes32[5]) questions;

    constructor() public payable {
        questions[1] = ["first part of question", "second", "third", "and so ", "on"];
    }
}

Compiler

browser/dass42-test.sol:51:24: TypeError: Type string memory[5] memory is not implicitly convertible to expected type bytes32[] storage ref.
        questions[1] = ["first part of question", "second", "third", "and so ", "on"];
                       ^------------------------------------------------------------^


texts: Fundamental limitations between Solidity and Serpent

texts:
Solidity can be considered a "higher level" language than Serpent.
Are there any "low level" features in Serpent or that could be implemented in Serpent, that are either impossible or infeasible to do with Solidity?

If there are, an order from what's impossible, to what's infeasible or unlikely to be implemented in Solidity, would help us determine if one must be used over the other.


texts: Articles about short address attack: https://vessenes.com/the-erc20-short-address-attack-explained/ and https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95. The patch only exists in web3 and node API level? Is it possible for an attacker to bypass that and issue raw transactions to exploit any multi-sig wallet?


texts: How to ensure security on private consortium?

texts:
When you have a private/permissioned ethereum consortium, you are somehow trusting the members of the network.

How do you prevent a single user for tampering part of or the full chain, given that it is faster to get transactions approved?


texts: Adding element to mapping (solidity) is not working, even if the method is actually called in the transaction

texts:
I'm currently working (as a begineer) at a project involving ethereum blockchain and solidity.
In my contract I have a mapping with addresses as key and the value of an array of a FileDetails structure. Anyway when I try to add elements to the array and to the mapping it doesn't get updated even if the method is correctly called (see the transaction details below). I am currently using a React application with the truffle suite. (Ganache for running a test blockchain).
I have the following contract:
contract Files {
    struct FileDetails {
        string fileHash; // The IPFS file hash
        string fileName; // The file name
        string transactionDate; // The date in which file infos was stored
        string fileExtension; // The type of file (its extension)
    }

    mapping(address => FileDetails[]) filesList;

    function addFile(string memory fileHash, string memory fileName, string memory fileType, string memory date) public {
        FileDetails memory fileDetail = FileDetails({
            fileHash: fileHash,
            fileName: fileName,
            fileExtension: fileType,
            transactionDate: date
        });
        filesList[msg.sender].push(fileDetail);
    }
}

Now I'm calling the function addFile(...) from javascript with the following:
await contract.methods.addFile("aaaa", "bbbb", "cccc", "dddd").send({ from: accounts[0] });

As you can see I put into parameters random strings just for testing.
Now, when I call it I actually get something:

The contract is called and even the function with parameters is correctly called in the transaction.
Beside that, I don't get any updates in the mapping structure that I can see in the contract from Ganache (0 items):

I don't know if it can be useful, but when I try to make a transaction to the contract to give it some funds, but I get the following error:
VM Exception while processing transaction: out of gas
Do you know what could be the problem? Why even if the method is correctly called it doesn't update the mapping structure?
Thank you in advance.
EDIT
Here there is a transaction receipt form the javscript console log:

I also tried adding the following function to the solidity contract:
function getFilesCount() public view returns (uint256) {
    return filesList[msg.sender].length;
}

But when I call it from javascript I get always 0.


texts: What is the easiest way in dapple to call a contract function from different addresses (set the address which triggers the transaction)?


texts: Inconsistent responses with 'eth_getTransactionByHash' through RPC API. Can anyone help?

texts:
I have been using the requests library with python to query the geth/rpc api in order to get ETH transaction data. I connected to geth via "geth --rpc --unlock TESTINGADDRESSWITHNOVALUE --allow-insecure-unlock".

Sometimes when I query a transaction hash (it seems to be only very old transactions) I get the appropriate response ex: tx_hash = 0xff2c55c1f2be6cb89f5d2486a6d56f2856664eddf65b3ddd7b4ee1c06b01f66f. Yielding the response:

{'blockHash': '0x44a6c685d3cf6764a0c7f9fd5f6fadddf7db73fb6cdefcf428674fd354e57753', 'blockNumber': '0x425709', 'from': '0xc32ee26a67b9084773bc16a1ae81b8660a39a40f', 'gas': '0x61a80', 'gasPrice': '0x2540be400', 'hash': '0x6424958d16a6b687d29ef7ef1289d9fbaf96c9b0c7ef7c618b2a58ed580145af', 'input': '0x', 'nonce': '0x3', 'to': '0xb72a0fa1e537c956dfca72711c468efd81270468', 'transactionIndex': '0x5b', 'value': '0x35e285658ff2480000', 'v': '0x25', 'r': '0xdc01e389077bcba1812eee246174e28a12ba1b2b793c87f00e231ee269c01ed9', 's': '0x265d600e38a837f3ae4e3377fc6a5eac14c75bbb15c0fca8fe5829a3cccb62ce'}

Other times the response I get from newer transactions is simply "None". For example, the recent transaction: "0x453ce623c545c6d3294595e9e0640ffdb49be3a6b9e4ced13a657d2cedac85c6". Does anybody know why this may be the case? Please let me know if there is more information I can provide. Thanks!


texts:
I wrote a contract into bare assembly (no solidity or Vhyper syntax and with all address being static).

How to convert it into bytecode? If possible using the new http://remix.ethereum.org or another web service where nothing has to be compiled.


texts:
Take these two contracts, both deployed on Kovan and with the source code verified:

DSProxy: 0xa92Bed719071A4d33B0B348513E7e866a6ff6B3F
TargetContract: 0xE3CD2e7a628b57d3e50c5f7B921182f676721bDF

And take this transaction:

0x04c5e3b87dfeaae07ea73242663c69bd7e412686ffc0fcc25016fc6179455e56

Which has been reverted and I don't understand why.
I want to call the execute(address,bytes) function of the DSProxy and pass in the following arguments:

0xE3CD2e7a628b57d3e50c5f7B921182f676721bDF
0xb081b4eb (the signature for the "wrapEth" function)
Also send some amount of ETH

Effectively calling the wrapEth payable function defined in TargetContract, but via the DSProxy DELEGATECALL functionality.
With help from ethers.js, I generated the calldata for this multi-contract call, and it looks like this:
0x1cff79cd000000000000000000000000e3cd2e7a628b57d3e50c5f7b921182f676721bdf00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000004b081b4eb00000000000000000000000000000000000000000000000000000000

Unfortunately, when I relay this calldata to the Kovan testnet via MetaMask, MyCrypto or any other wallet, I am getting reverted transactions. Although I feel that the above calldata is correct, I tried tweaking the last part of the bytes (the function signature) in case there is a bug in Ethers, but with no luck.
Can you see the error here?


texts: "Consider using `transfer` in place of 'call.value()`" is a false error message by ethlint

texts:
I am getting following message when I use solium or ethlint, which is actually not correct and confusing developers. I have opened a issue related to that:
Solium returns error for using call.value().
error: Consider using `transfer` in place of `call.value()`. security/no-call-value

!!! As for the solidity version 0.6.0, it is recommended to use call.value() from now on and using transfer is not recommended. !!!

Please see Stop Using Solidity’s transfer() Now, its medium link.
=> I just want to bring this issue up since ethlint is misguiding the developers and verify by asking that should we stick by using transfer or call.value?


texts: Unable to deploy smart conrtact using node js (not truffle)

texts:
here is the code as explained in web3 doc(node:13887)

 web3.eth.estimateGas({data: '0x' + bytecode}).then(value=>{
 console.log('gasEstimate = ' + value);
 let MyContract = new web3.eth.Contract(abi,{
          from: publicKey,//user wallet
          gasPrice: '10000000000000',
          gas: value
         });
 console.log('deploying contract...');
 MyContract.deploy().send(function(error, transactionHash){
  }).on('error', function(error){ })
    .on('transactionHash', function(transactionHash){ })
    .on('receipt', function(receipt){
     console.log(receipt.contractAddress) // contains the new contract address   })
    .on('confirmation', function(confirmationNumber, receipt){  })
    .then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
   });
});

here is error message

UnhandledPromiseRejectionWarning: Error: Request failed with status code 522
at createError (/home/project/node_modules/axios/lib/core/createError.js:16:15)
at settle (/home/project/node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd (/home/project/node_modules/axios/lib/adapters/http.js:201:11)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:13887) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:13887) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

EDIT

Thanks to all this is working code

  web3.eth.estimateGas({data: '0x' + bytecode}).then(value=>{
  let MyContract = new web3.eth.Contract(abi,{
     from: publicKey,
     gasPrice: 1000000,
     gas: value
   });
  MyContract.deploy({
       data:  '0x' +   bytecode
       }).send({
               from: publicKey,
               gasPrice: 1000000,
               gas: value
      },function(error, transactionHash){})
        .on('error', function(error){ })
        .on('transactionHash', function(transactionHash){ })
        .on('receipt', function(receipt){})
        .on('confirmation', function(confirmationNumber, receipt){  })
        .then(function(newContractInstance){ });
        });


texts: What is the difference between web3 and window.web3

texts:
I'm very used to using web3 = new Web3(web3.currentProvider) and I saw here that MetaMask sample code is using window.web3 = new Web3(web3.currentProvider)

What's the difference between using and not using the window keyword?


texts: Can't locate local key file asked by parity to sign a transaction

texts:
When I use NODE-RED enviroment to send transaction using Parity, the signer doesn't ask only for the password as usual but also for the local key file, which I can't locate in my laptop (I'm looking in the directory /home/.local/share/io.parity.ethereum).

Why does this happen? Where can I find this file?

Thanks in advance,

Simone


texts: tm.ipc: no such file or directory (socket file to use for the private API / IPC)

texts:
I am following this tutorial to setup a Quorum cluster:
https://medium.com/@shizekun/how-to-set-up-a-quorum-private-chain-with-raft-consensus-and-dynamic-membership-bf826f3927e5

But unfortunately I get the following error at almost the last step, when starting the instances:

nohup: appending output to 'nohup.out'
panic: MustNew: Failed to connect to Constellation (tm.conf): Get http+unix://c/upcheck: dial unix qdata/tm.ipc: connect: no such file or directory

I don't get when the file qdata/tm.ipc was generated at all. I can't find it in the scripts neither: https://github.com/Szkered/quorum-raft-cluster

Can anybody help with this?


texts:
I am new to the world of Zero Knowledge Range Proofs. I read the following on GitHub: https://github.com/ing-bank/zkproofs

The Zero Knowledge Range Proof allows the blockchain network to validate that a secret number is within known limits without disclosing the secret number. This is useful to reach consensus in a variety of use cases:

Validate that someone's age is between 18 and 65 without disclosing the age.
Validate that someone is in Europe without disclosing the exact location.

The Zero Knowledge Range Proof requires a commitment on a number by a trusted party (for instance a government committing on someone's age), an Ethereum user can use this commitment to generate a range proof. The Ethereum network will verify this proof.

Any idea about the provided example that of the commitment can be verified on etherum or any link to a technical paper that describes how a user TP commit to a user age, then the blockchain can verify that commitment ?


texts: indexer for Ethereum wallet-contract transactions history?

texts:
I Would like to have my own server with a indexer for a ethereum full node using this repo https://github.com/Adamant-im/ETH-transactions-storage script, to have all wallet,contract balance and it's transactions, history I don't know if there a better and faster alternative or config to do that?

it's better have the indexer in the same server as the ethereum node, or use it as a separate each other?

thanks a lot.


texts: Why does etherscan.io API response with wrong balance?

texts:
Let's take the following company. The current ETH Balance is 268,691.327038426 Ether:

But API response 268698327038426745609145:

As you can see API response does't contain floating point so the balance value is very big.

Is it bug?


texts:
What is the function syntax to add more ether to an existing contract?

My contract exists, with Ether, and I want to add more Ether via a function call to the contract. How do I do this?

Can it only be deducted from the sender/owner wallet?

Can I specify which wallet it is deducted from?

Thanks


texts:
As per the ERC721 requirements, I have to implement onERC721Recieved. This is how I did it:

function onERC721Received(
    address _operator,
    address _from,
    uint256 _tokenId,
    bytes calldata _data
)external returns(bytes4) {
    return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}

This seems to be in line with what is required of the function. However, this raises two questions:

If this does not actually use any of the parameters, why pass the parameters to the function at all? It is now throwing errors every time I test the contract.
What is the reason behind this function?


texts: Why is there a difference between the gas consumed by deploying contracts on mainnet and locally?

texts:
I've noticed a discrepancy between the gas cost to deploy our contracts locally and on mainnet. I would have guessed that they should cost exactly the same.

Does anyone know why this happens?


texts: Hardhat Can't resolve 'console' on react project

texts:
I have a react project and initialized hardhat config then installed the necessary packages but I am
getting error when I require hardhat on my project
const hre = require("hardhat");
This is error message when the project is compiling
./node_modules/@sentry/node/esm/integrations/console.js
Module not found: Can't resolve 'console' in 'C:\Users\sss\OneDrive\Desktop\my-react\node_modules\@sentry\node\esm\integrations'

How do I resolve this issue?


texts: Deleting a value from address to address mapping in solidity?

texts:
mapping(address => address) public userpatient;

I want to delete a the key value pair from above map,when the patient is discharged.How can i do it.I saw similar question here but it mentioned 'delete' identifier which is not working


texts:
If not all of the msg.value is used, does it get returned to msg.sender or do I need to write a function that returns unused msg.value back to msg.sender?

I want to allow users to buy a token for x value and I'm wondering if the value passed in is more than the price, what should I do with the remaining msg.value?

function buyToken() payable returns (bool) {
    require(tokens[owner] >= 1 && msg.value >= price);

    // transfer the price of token to the owner, to be withdrawn later
    owner.transfer(msg.value.sub(price));

    tokens[owner] = tokens[owner].sub(1);
    tokens[msg.sender] = tokens[msg.sender].add(1);

    return true;
}


texts: Console application for generating addresses and private keys

texts: Is there a Windows console application that can generate addresses and private keys as output to the console window?


texts: Can a transfer made into the wrong address wallet be reversed? I transferred funds from USDT to my USDC wallet. What can I do to get this funds back? PLEASE HELP ME.


texts: How to determine the gas price mathematically

texts: The mathematical equation to define the gas price is gasprice = 1 gwei / gasused. The mathematical equation to define the tax to be paid for each transaction is tax = gasprice x gasused. Are these equations not redundant? If I use 41 000 gas, the gasprice will be approximately 2.43e-5, if I multiply that value by 41 000 the tax to be paid will be 1 Gwei. Would not that be redundant?


texts: A contract works in remix but not when used with truffle

texts:
Below is the contract:

uint32 firstTimeUserPoints=10;
    struct struUser{
        string orginalName;
        string originalKshoplink;
        string orginalDocumentConvention;
        bool validated;
        uint32 Points;
        uint32 totalPoints;
    }
    struct struUserTotalPoints{
        string orginalName;
        uint32 totalPoints;
    }
    mapping(string=>struUser)MappingToken;
    mapping(bytes32=>struUser)SampleMappingToken;
    struUser[] struUsers;
    struUserTotalPoints[] struArrayUserTotalPoints;
    string[] docConventionMappers;
    string[] orginalName;

//TO INSERT A RECORD WITH SOME DATA

function AddUser(string name,string link,string docConvention) public
{
        var user=MappingToken[docConvention];
        var existingTotalPoints=userTotalPoints(name);

        user.orginalName=name;
        user.originalKshoplink=link;
        user.validated=false;
        user.Points=firstTimeUserPoints;
        user.totalPoints=existingTotalPoints+firstTimeUserPoints;
        updateUserTotalPoints(name,user.totalPoints);
        user.orginalDocumentConvention=docConvention;
        docConventionMappers.push(docConvention);

        struUsers.push(struUser({orginalName:name,originalKshoplink:link,
        validated:user.validated,Points:user.Points,totalPoints:user.totalPoints,
        orginalDocumentConvention:docConvention}));

    }

//IS THE BELOW FUNCTION FINE?, THIS IS ONE OF THE PLACE I BELIEVE IT IS GETTING MESSED.

//FOR FETCHING TOTAL POINTS OF A USER

 function userTotalPoints(string name) public returns(uint32){

         bool isUserTotalPointsCalculated=false;

            for(uint j=0;j<struArrayUserTotalPoints.length;j++){
                if(keccak256(struArrayUserTotalPoints[j].orginalName)==keccak256(name)){
                    isUserTotalPointsCalculated=true;
                    return struArrayUserTotalPoints[j].totalPoints;
                }
            }
            if(!isUserTotalPointsCalculated){
                struArrayUserTotalPoints.push(struUserTotalPoints({orginalName:name,totalPoints:firstTimeUserPoints}));
                return 0;
            }
    }
//WHEN I CALL THE BELOW METHOD IT IS RUNNING FINE IN REMIX BUT NOT WHEN I USED WITH TRUFFLE - IN TRUFFLE THE STRING IS  RETURNED AS " " AND THE TOTAL POINTS

    function viewuser(string docConvention)public returns(string,uint32,uint32)
{
        return (MappingToken[docConvention].orginalName,MappingToken[docConvention].Points,
        userTotalPoints(MappingToken[docConvention].orginalName));
    }

    function updateUserTotalPoints(string name,uint32 totalPoints) public{
        for(uint j=0;j<struArrayUserTotalPoints.length;j++){
                if(keccak256(struArrayUserTotalPoints[j].orginalName)==keccak256(name)){
                    struArrayUserTotalPoints[j].totalPoints=totalPoints;
                }
            }
    }

I have tried for different inputs and it is working fine.

Remix inputs:

Remix outputs:

HTML:

<input id="txtViewUser" type="text" placeholder="Enter name of document convention" />
<button id="btnViewUser" onclick="App.viewUser()">View User</button>

Truffle code:

viewUser:function () {
    var docConvention=document.getElementById("txtViewUser");
    sampleinstance.deployed().then(function (instance) {
        return instance.viewuser.call(docConvention).then(function (v) {
        console.log(v);
        $("#tdEmailName").text(v[0].toString());
        $("#tdPoints").text(v[1].toNumber());
        $("#tdTotalPoints").text(v[2].toNumber());
      })
    })
  },

Truffle Output:

the 0 array will return the name of the user

I have inserted different users five times so it is giving 50 where I have tried to view user for one person.

Kindly help me out in analyzing where I am going wrong please.

Vivek.


texts: How to encrypt file before storing into IPFS network in Javascript?

texts: I want to encrypt file before storing into IPFS network so that only person who is uploading a file should be able to decrypt.


texts: Cost to cancel or change an unfilled Augur order

texts: With the launch of Augur v2, what is the cost to cancel a previously entered order that has not yet been filled? Is this cost the same as the cost to modify the order by changing the bid, ask or quantity?


texts: How does ENS (Ethereum Name System) work?

texts:
The reason of the ENS (Ethereum Name System): Making an address 0x123f681646d4a755815f9cb19e1acc8565a0dddd reachable under a rememberable string like abcdef.ghi.eth.

But what I don't understand:

How is it built? It's not part of the original "Ethereum". So it's just a bunch of smart contracts that resolve abcdef.ghi.eth to its address.

But if I remember correctly: If I want to store an integer on the Ethereum blockchain, I need to allocate the space before I store a number...

So did the ENS-people just allocate a million address-String pairs? And if someone wants to set the entry (adress1 / foo.bar.eth), these values are stored in the next available allocated space??

Or is it possible to do this dynamically?


texts: Need to define all the varibales for an exchage during the contract deployment?

texts:
Creating ERC20 is not that hard.
We can just copy the source code and deploy it on the main network.

But creating an own exchange system for the token is a differnt part.
If we create a standard token now, can we create the exchange later for the token ? or need to define all the variables & methods during the contract deployment? ( variables & methods that are required for the exchange)


texts: Possible ways of verifying the ownership of Ethereum address when user lost its private key?

texts:
I am working on something that relates the ownership of the ethereum account address. I have a situation depicted as follows:

Someone issues a token and issuer KYCed(off-chain) my ethereum account address, So I am able to hold or buy the tokens from the crowdsale. But somehow I lost the private key of my wallet now I am not able to access my account, I quickly contact to my token issuer which has some backdoor mechanism (Not known for now but let's predict issuer has some magic) to transfer those tokens from my previous account to new account but the problem now for token holder is to verify the ownership of its lost account.

So what will be the feasible ways to prove the ownership of the address?.

I know this is something a researched base question but I really want the inputs to formalize the idea.

Any inputs are appreciable.


texts: Ethereum Wallet app Synced, coinbase transaction not appearing

texts:
My ETH wallet app has synced and the new blocks it loads every time I re-open the Wallet starts to sync. The issue is that I sent ETH from Coinbase to My ETH wallet and it is not showing now. Etherscan shows it was validated with my correct address almost 19 hours ago (the sync should have already covered those blocks by now).

Also, every time I open the Wallet App again, and it loads the blocks, once it finishes it seems to reboot and somehow close out all my programs and then send me to my account login screen for Mac. As if I just shut down the computer. Not sure how this affects it but seems to be connected. I am using a 2016 Mac and the most up to date version of ETH Wallet app from Ethereum.org.

I have tried to delete all the chain data and resync which didn't change anything. Again the address matches the Etherscan and it shows it to be validated but the wallet app seems to have the issue.

Thank you in advance!


texts: parsererror source file requires different compiler version (current compiler is how to fix this error

texts: I am new to this and was able to successfully compile and deploy a token onto the BSC mainnet using the following code  but now I am trying to make some adjustments and re deploy but now I am not even seeing the contract at all under the "deployed contract" tab. When trying to compile the exact same code that launched successfully before I am getting this error code  and I have tried solving by changing the complier version to a number of different things but it worked once, and now isnt working again.


texts: How to make sense of the "data" sent to execute a contract?

texts:
I'm trying to understand the technical details of Ethereum and one thing I can't find any info about is the data to be sent to a contract.

For example, I have a very simple coin flip betting contract on the testnet ethereum chain, and when I execute the "Bet and flip" function on the contract I get (in Mist) a prompt with this "data" that will be sent to the contract:

0x25d8dcf2

What exactly is the format of this data, and how do I make sense of what each byte means?


texts: How to pass constructor parameters to a contract using Truffle?

texts:
I am using testrpc and truffle for deploying contracts.I want to pass constructor parameters while deploying.

    contract User {
          string public userName;

          function User(string _name) {
                 userName=_name;
          }

   }

I am using contractname.deployed() for deploying contract.

      var user=User.deployed()

This deployment command won't initializes the userName parameter.

How to pass _name to this contract using truffle?


texts: How will casper maintain time between 2 blocks?

texts:
In current proof-of-work, there is an artificial time delay introduced because of difficulty.
This allows the network to accept transactions that ultimately form the block.
Vlad argues that once Ethereum moves to Casper, the time between 2 blocks can be 4 seconds or even  sub-second.

On what is this time between block dependent in a PoS?
How does the network know that everyone is using a synchronised clock?
What will be the sizes of the blocks if there is a very small time gap between 2 blocks?


texts: Is there a different testnet for ETC and ETH or only one?

texts: Since Ethereum forked, is the testnet forked too or only the main net? Is there a common testnet for forked Ethereum (ETH) and Ethereum classic (ETC), or a testnet for each one?


texts:
I am trying to figure out how to send a transaction to a contract method, retrieve the transaction hash automatically, and then get a receipt callback after the transaction is mined.

I am able to do one or the other but seemingly not both. Any suggestions?

Contract.deployed().then(function(instance) {
    instance.methodName(parameter, {from: this.account, value: price})
        .then(function(receipt) {
          //THIS FIRES AFTER THE TRANSACTION IS MINED,
          //BUT I CANT GET THE TX HASH ANY SOONER
        });
});

Contract.deployed().then(function(instance) {
    instance.methodName.sendTransaction(parameter, {from: this.account, value: price})
        .then(function(hash) {
            //THIS FIRES BEFORE THE TRANSACTION IS MINED,
            //BUT I NOW DON'T HAVE A WAY TO GET A MINED RECEIPT
        });
});


texts: Move my dao from gatcoin to own Mist-wallet

texts:
I have DAO in gatecoin and got note to only can take it out with mist-wallet.
Now I have a Mist.wallet running on my lap-top and dontknow if how to go on?

Do youknow the way to transfer,parts or all of it or any other proposal?
Should I let it stand there for something to expected to happen?


texts: How can I debug a truffle JS unit test with vscode?

texts:
I am using visual studio code and truffle and would like to easily debug my JavaScript tests.

A similar question has been asked here: how can I run a truffle test in a debugger?. This has been wrongly marked as a duplicated and not been released.


texts: Can I safely delete Parity LOG.old.* files?


texts: Is Casper FFG still going to be implemented?

texts: What is the status of Casper FFG within the ETH 2.0 roadmap. Is the plan still that it will be implemented with Phase 0 or Phase 1? Or is the plan to adopt Casper CBC instead, and forgo implementing FFG at all?


texts:
I just finished the Token Level in Zeppelin's Ethernaut and in the end they explained that overflows are very common in solidity. I didn't even think about overflows, I just tried to steal the tokens.

This is the code they show:

Overflows are very common in solidity and must be checked for with control statements such as:

if(a + c > a) {
a = a + c;
}

An easier alternative is to use OpenZeppelin's SafeMath library that automatically checks for overflows in all the mathematical operators. The resulting code looks like this:

 a = a.add(c);

If there is an overflow, the code will revert.

I just can't understand what overflows in solidity are, can someone please give me a newbie explanation about what they are or point me an article where to look at. Thanks!


texts: How to connect with public Ethereum Blockchain on a backend/web server?

texts:
In the backend of a Web application I have to communicate with the public Ethereum Blockchain.

On local development machine, I run ganache as testrpc and connect with such a line of code:

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

I've also found out that I can develop against Rinkeby testnet with:

web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/$thisistheapikey"));

But how can I communicate with the REAL public Blockchain? Do I need to run geth on the Web server and connect to its instance? Or is there any public network available that could be used (if we can trust it)?


texts: How to read blockheaders of Ethereum Blockchain?

texts:
TO be specific, how to read block headers of Rinkeby on Ropsten blockchain?
Since both the blockchains are public test networks, reading data of one blockchain on another should be possible using smart contracts, isn't it?


texts: Issue with output of function while working on ERC721 token

texts:
for (var i = 1; i <= totalSupply; i++) {
    const color = await contract.methods.colors(i - 1).call()
    this.setState({
      colors: [...this.state.colors, color]
    })
  }
  console.log(this.state.colors)

It should ideally come like 0,1,2,3
But result: is 0,0,1,1


texts: exporting blockchain from a specific block number

texts: is there an option for the export command in geth to export from only a specific blocknumber?  For example if I wanted to export the blockchain but only up to before the DAO attack?


texts: Solidity Contract bytecode contains many 'f'

texts:
my contract bytecode which is generated by go-ethereum abigen has something like
0x60806040523480156200001157600080fd5b5060026000620000266200015d60201b60201c565b905060018060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055506000819080600181540180825580915050600190039060005260206000200160009091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508073ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f8be0079c53....

what does it means??


texts: What do the parameter in sha3() in Proof of Work implementation of Ethereum mean

texts:
sha3(nonce, currentChallenge, block.blockhash(block.number-1))

In this line I get it that blockhash is a random number, but why are we taking it from the previous block, any hard and fast rule here ?

sha3(nonce, currentChallenge)

In this line there are only two parameters , is third variable a default one in implementation of sha3 ?


texts: input field is not getting displayed by using ContractForm

texts:
<DrizzleProvider options={drizzleOptions}>
                <LoadingContainer>

Welcome Doctor

Enter your public address:

                        <ContractForm contract="Records" method="loginDoctor" labels ={['Enter your public address']}/>
                        {/* <AccountData accountIndex ={0} units={"ether"} precision={2}/> */}

                </LoadingContainer>

            </DrizzleProvider>


texts: Implementing AMM DEX similar to Uniswap/SushiSwap

texts:
I’m new to blockchain development and have been interested in the Uniswap/sushiswap/pancakeswap/etc. projects for some time.
I’m trying to build my own project as a learning exercise. I’ve deployed the contracts to ropsten and can see that my token has zero supply in my frontend.
My question is, how do I interact with the contracts to mint tokens, create liquidity pools, etc? Do I write a js file that utilizes web3 to call those functions such as mint() and createPair()?


texts: Trying to compile example code from pyethapp tutorial

texts:
I am trying to follow this example:
https://github.com/ethereum/pyethapp/wiki/The_Console

However, at the point where I should compile the code, I get an error:

In [34]: print c
contract NameReg{
    event AddressRegistered(bytes32 indexed name, address indexed account);
    mapping(address => bytes32) toName;

    function register(bytes32 name){
        toName[msg.sender] = name;
        AddressRegistered(name, msg.sender);
    }

    function resolve(address addr) constant returns(bytes32 name){
        return toName[addr];
    }
}

In [35]: solidity.compile(c)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-35-7d9906629614> in <module>()
----> 1 solidity.compile(c)

/home/work/Software/ethereum/pyethapp/.venv/local/lib/python2.7/site-packages/ethereum/_solidity.pyc in compile(cls, code, path, libraries, contract_name)
     51                 sorted_contracts[idx][1]['bin'] = sorted_contracts[idx][1]['bin'].replace(
     52                     "__{}{}".format(lib_name, "_" * (38 - len(lib_name))), lib_address)
---> 53         return sorted_contracts[idx][1]['bin'].decode('hex')
     54
     55     @classmethod

IndexError: list index out of range

I get that there is an argument missing to the 'compile' call, but which one? What's the class that I should provide?


texts:
I have written a web3 implementation. The code below invokes a method of solidity contract that writes some value to blockchain:

var Coursetro = CoursetroContract.at('0x3958c21a7037d4a53c2990834c59ca3dcb00d988');
var fileName = "filename.pdf";
var identifier = uuid.v4();
console.log("uuid is " + identifier);

Coursetro.setFile(identifier,fileName,"hash...",function(error, result){
  if(!error)
  {
    console.log("Transaction submitted" + result);
  }
  else{
    console.log("Error " + error);
  }
});

How can I get a estimated cost for the "setFile" transaction and provide my gas limit and price ?


texts: Execution environment variables Iw and Ie

texts:
According to the yellow paper, one of the Execution Environment variables is:

  Iw, the permission to make modifications to the
  state.

I can't find further information about it, for example how it's set and what values it can get (I guess 1 or 0)

Also I'd like to make sure that the variable

  Ie, the depth of the present message-call or
  contract-creation (i.e. the number of CALLs or
  CREATEs being executed at present).

is only decremented by one for each CALL and CREATE opcodes, but never for a DELEGATECALL or CALLCODE


texts:
How do you delete an array at a certain index in solidity? I'm trying to access the index via key and not the index number.

function deleteAtIndex(address _address) {
    delete sellers[_address];
}

The error I'm receiving is
TypeError: Type address is not implicitly convertible to expected type uint256. I also know that deleting this will leave a 0 at the index. Is there any way around this without shifting the entire array since I know it's expensive?


texts: What can you change and adapt when you create an Erc 20 token?

texts: I saw this list of things that can be modified for your token. I can't find it but it listed all the different uses and things that can be changed about your token such as the max supply etc.


texts:
Not able to connect metamask with ganache-gui. I tried two different app images :
ganache app image : ganache-2.5.4-linux-x86_64 and ganache-2.4.o-linux-x86_64 , neither seem to work .
With ganache-2.5.4-linux-x86_64 I was getting error *

cannot connect to chain id please check rpc URL

, with ganache-2.4.0-linux-x86_64 its unable to connect (never ending loader as shown in image ).

Same errors faced with ganache-cli
Operating System: Ubuntu 20.04.1 LTS
Kernel: Linux 5.8.0-50-generic
Browser Brave
Tried uninstalling and reinstalling both ganache and metamask literally a thousand times .
Would be much grateful if someone is able to answer

Metmask network config :


texts: necessity of mining while doing transaction

texts:
While doing any transaction in private network, is it necessary for one node to keep on mining?.

I was trying to implement to deploy smart contract and transact in ethereum private network with the help of web3j java library. When there was no mining happening, my java transaction code was error out and it was saying transaction exceeds time limit of 600 seconds. But when I started mining and run the program, it was successful. But because of these two process, my system became very slow.

What is the reason behind these scenario? Any suggestion?


texts: PoW, PoS and transaction conflict resolution. How does it work? Isn't PoS at risk here?

texts:
So I am trying to put my head around POS. And I have a question about transaction conflict resolution and whether there is an attack risk here.

If I understand correctly how POS works, if there are two transactions who are fighting for legitimacy, then the people voting will be rewarded by the one who is taken into the blockchain and those who have voted for the losing transaction.

So here is the scenario and I would like to know if I missed something or not.
Here is the idea:
Let's say I send on different machines but at the same time a transaction to send all my ETH from one account to the other. Because it is spread on the globe, some voters will take transaction x, some transaction y and some another transaction. If you have no info on the other transactions yet, you will validate it and bet on it.
So what will happen is that a small portion of the voters will be rewarded with the correct transaction and the others will lose their bet. This could be used as an attack to gain ETH from making the other lose. As a voter attacker, I can easily recognize my transaction (by signing them for example) and make sure I don't participate in the voting of the block containing any of my transactions.

What would happen in that case? How can the system resolve these conflicts without penalizing the voters too much?

My observation is that in the case of PoW, conflict resolution does not cost anything, eventually one block will win and that's the end of it. But In the case of PoS, each conflict resolution will result to a cost for people voting for the wrong block without having anyway of knowing they are doing so.


texts: Remix: Gas estimation errored...The transaction execution will likely fail

texts:
This error seems to get fixed by resolving an obscure exception in one's code. I'm trying to invoke Owner.transfer in Remix, but being thrown the alert: Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
The execution failed due to an exception. Reverted.

The Owner contract just approves the sender for the specified amount, and invokes the Depository to transfer that amount to itself before updating balances.

    pragma solidity ^0.5.11;

    import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/ERC20.sol";

    contract Token is ERC20 {}

    contract Depository {
        mapping(address => uint256) public balances;

        function deposit(uint256 amount) external {
            require(amount > 0);

            Token token = Token(0xFab46E002BbF0b4509813474841E0716E6730136);
            require(token.transferFrom(msg.sender, address(this), amount), "The deposit failed");
            balances[msg.sender] += amount;
        }
    }

    contract Owner {
        function transfer(uint256 amount) external {
            require(amount > 0);

            Token token = Token(0xFab46E002BbF0b4509813474841E0716E6730136);
            // 0xEa917... is the deployed Depository contract address
            token.approve(0xEa917F373afa9F7F4AdB31a01D4c91E763De6502, amount);

            Depository depository = Depository(0xEa917F373afa9F7F4AdB31a01D4c91E763De6502);
            depository.deposit(amount);

        }
    }

Is there a code issue? Can't quite figure out where I'm going wrong.


texts: where does the metamask fits in Dapps architecture?

texts:
i am learning building Dapps. And i got to know to know about metamask.
I've read about metamask is an ethereum wallet which we can use to sign Tx's without running a full node and inject web3 to webpages.
and I know that the architecture of Dapps is like-

web-app --> web3 ---(JSON RPC)--->RPC PORT ---> GETH NODE--->ethereum API
---->ethereum blockchain.

if I am running my own ethereum node. and in my web-app i am using nodejs which can import web3 library.so why do i need metamask? and where does the metamask fits in Dapp architecture?


texts:
There are 2 nodes(10.0.50.90, 10.0.50.91), and they can ping each other well.
There are geth in every node and their genesis json file is same.Then I run geth in evey node. In 90's geth console:

> admin.nodeInfo.enode

"enode://22417b070ba9e8558ef37acc4fa9818735509ff23c0608cdc03d78c7ff3670fad5277806f35343f7dfe7b58eec7f5faafecc10384af26195ac469ea3dcc535ff@[::]:30303"

In 91's geth console:

> admin.nodeInfo.enode
"enode://f08d120a6edbb0f4f4859fc480c7377cf78593e71ad1de2f9a7b92f04f5d97fffa9e065224e93b2142f4489f649720a84b6de5f496e8c12bf98bc6aaf0883e3e@[::]:30303"

then I add 91 in 90's geth console here:

> admin.addPeer("enode://f08d120a6edbb0f4f4859fc480c7377cf78593e71ad1de2f9a7b92f04f5d97fffa9e065224e93b2142f4489f649720a84b6de5f496e8c12bf98bc6aaf0883e3e@10.0.50.91:30303")
true
> admin.peers
[]
> admin.peers
[]
> admin.peers
[]
> admin.peers
[]
> admin.peers
[]
> admin.peers
[{
    caps: ["eth/62", "eth/63"],
    id: "182cf8aaadbe949e9dada0874a990f86fe61043738164757ca1d4c007a81585dfee0d517e4211000fc06034de2c42cdfef90c8b020f4fdabb4abd97d0d81a8cd",
    name: "Geth/azureNode/v1.6.1-stable-021c3c28/linux-amd64/go1.8.1",
    network: {
      localAddress: "10.0.50.90:49936",
      remoteAddress: "13.90.198.214:30303"
    },
    protocols: {
      eth: "handshake"
    }
}, {
    caps: ["eth/62", "eth/63"],
    id: "9067508301728d7ad21871e38d71a2b2949b9f924d4358569b213b27f8a97119a02d490639c0f97a2445191ec78df64e2fd08f0a9479895711d24416884485e8",
    name: "Geth/v3.3.0-1-gdd95f05/linux/go1.7",
    network: {
      localAddress: "10.0.50.90:42046",
      remoteAddress: "46.101.153.17:30303"
    },
    protocols: {
      eth: "handshake"
    }
}]

so you can be clear from above that when I type  admin.peers the first few times, it shows [], but it shows something at the end.But there is no 91's information in the result.
So I can't addpeer in a private chain, why? and why it can show some remote nodes I didn't add before at the last time?(is it the auto discovery mechanism' function?)
how to add 91's node when I type admin.peers it can show 91's information?
Many thanks.


texts:
im working on a ERC1155 token.
as you may know openzeppelin has a presetMinter for it, but i want to mint my token with more complex things.
i see 3 methods to do it:
1- without using presetMinter from openzeppelin. right a minter funtion by myself in MyToken.sol
2- import presetMinter from openzeppelin to MyToken.sol and override that minter funtion with my custom one in MyToken.sol
3- import presetMinter from openzeppelin to MyToken.sol and declare a MyMint function that do all the things and passes the variables to presetMinter from openzeppelin. and try to call MyMint funtion for minting my token.
which is the best method? i mean which is more standard to do?
any other comments for doing this would be appreciated!


texts: How Can I Persist My Local Development Ethereum Blockchain Data?

texts:
I'm using truffle and ganash to host local dev blockchains and neither seem to persist my contracts or state.

This is super painful as it means the contract address changes for my dApp each time i restart my environment and metamask's nonce gets out of sync all the time so i have to reset my account.

How can I resolve this please? Is it me who is wrong in my approach?


texts: Why do my FAILED transactions get charged the max gas price?

texts: I tried buying TEL on EtherDelta and had two failed transactions in a row, both charged at the max gas price, one after like 15 mins and the other instantly. How come I get charged for a failed transaction?


texts: Export all addresses with a balance above a certain number

texts:
Is there a way to find/export all addresses with a balance above a certain number in Ether?

Any service/API provider is available for above requirement?


texts: Is it possible to mine ether with a mobile phone's H or 3G data connection?

texts:
I've seen similar questions and answers but I'm still unsure.

The aim is to mine with about 6 GPUs from a basement that has electricity but no wifi. Only an H or possibly 3G mobile connection shared through hotspot.

Probably mining in a pool though open to mining solo if it makes a difference.

I've read synching with the blockchain consumes a lot of data but mining itself doesn't.

Is synching necessary? Can I rely on a 1GB monthly mobile contract to mine without problems?


texts:
I'm building a simple fund raising smart contract and having problems deploying this through Remix. I'm wanting to set the "goal" and "minimum contribution" values (in wei) during the contract deployment and so have the following code:

pragma solidity ^0.5.0;

contract FundRaiser {
  // Initial storage variables
  uint256 public goal;
  uint256 public minimumContribution;
  address public owner;

  constructor(uint256 _goal, uint256 _minimumContribution) public {
    goal = _goal;
    minimumContribution = _minimumContribution;
    owner = msg.sender;
  }
}

This compiles fine in Remix and then I try to deploy and have the following prompt:

However, if I enter two large values here (1000000000000000000, 10000000000000000 - which equates to a goal of 1ETH with a minimum contribution of 0.01ETH) then I get the error:

creation of FundRaiser errored: Error encoding arguments: Error: invalid number value (arg="", coderType="uint256", value=10000000000000000, version=4.0.32)

If I then click the drop-down arrow next to the Deploy option it then shows the following:

Strangely Remix seems to have converted the first value into a string (surrounded by quotes) but not the second value. If I now update the values so that either both are strings or both are numbers and click "transact" then it deploys fine.

Is this an error on my part in using Remix or a bug??


texts:
On mining pools like Suprnova, one connects to a worker they create, with a username and password.

What I'm wondering is, if you're running a miner should you create a different worker for every mining host you have, or are there no disadvantages to having more than one host (potentially hundreds) logged in to the same worker account while mining?


texts: Syncing problem while interacting with multiple nodes

texts:
I have private network running on two nodes. First node is aws instance and second is on my own computer with graphics card. Second node is much more powerful. When I create contract on first node(aws instance) and send few transactions to this contract, it is mined quite quickly. But when I connect the second node, it overtake the first one and I am unable to confirm any transaction with the first node. When I add second node, I cannot even get data from the contract.

How can I relay transactions received by the first node ( which are not included because first node is not fast enough )?


texts: eth.coinbase gives the wallet address which is not exist in the system

texts:
I'm facing a strange issue, when I execute eth.coinbase command on Geth, it gives me wallet address which is not present in the key directory.

But that isn't in the genesis file

I'm not sure how this has been updated. Can coinbase update from web3js?

Version: 1.9.14-stable
Go Version: go1.14.2
Operating System: linux


texts: Running --no-ancient-blocks on a synced node

texts:
I have an up to date OpenEthereum node that is taking a long time to sync it's ancient blocks, Which has left it syncing a batch of ancient blocks, while falling behind, then syncing up to date. Put simply if I run the node with --no-ancient-blocks will it simply stop syncing the ancient blocks and be usable or will the node have to be resynced entirely.
As a follow up what about --pruning?


texts: Why time values should be used as uint256?

texts:
Is there a reason to use the time value as uint256?
Is not uint128 enough?
UnixTime...


texts: Problem with Connecting to Unknown Private Network on Metamask

texts: When I try to create a custom RPC on http://localhost:3000/ on Metamask, it keeps on trying to connect to it. It has not moved past "Connecting to Unknown Private Network" on the Metamask extension. What am I doing wrong and how to solve this issue?


texts: how to upload file into ipfs from node js without uploading files into node js server

texts:
I need to upload multiple files into ipfs from node js.

Flow:
file(html,angularJS) --> node.js --> IPFS --> ipfs hash save into DB.

I have sent a file from HTML(angularJS) and I got the file in node.js by the help of the multer npm module. With this solutions, the file is uploaded into a node.js server and then from there it is uploaded into IPFS.

Since I'm using azure for my node.js server, I cannot upload files. Is there an alternative approach to upload files into IPFS without uploading them to a node.js server?

html:

<form role="form" ng-submit="uploadComplete(form)" enctype="multipart/form-data" name="form.test">
    <input type="file" id="docName" name="docName" multiple class="form-control"
           accept=".jpg,.png,.jpeg,.doc,.docx,.pdf" file-model="myFiles($files)"
           placeholder="Enter the docName here" required aria-required="true">
</form>

AngularJS:

var formData = new FormData();
$scope.myFiles = function ($files) {
    formData.append('img', $files[0]);
};

// Method for sign up to the kyc system
$scope.uploadComplete = function (form) {
    formData.append('email', $scope.email);
    formData.append('password', $scope.password);
    var promise = uploadFileToUrl(formData, uploadUrl);
}

var uploadFileToUrl = function (formData, uploadUrl) {
    var deffered = $q.defer();
    $http.post(uploadUrl, formData, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    }).success(function (response) {
        deffered.resolve(response);
    }).error(function (response) {
        deffered.reject(response);
    });
    return deffered.promise;
};

Node.js:

var storage = multer.diskStorage({
    destination: './uploads/',
    filename: function (req, file, cb) {
        stData = file.stream;
        cb(null, file.originalname.replace(path.extname(file.originalname), "") + '-' + Date.now() + path.extname(file.originalname))
    },
    stream: function (req, file, cb) {
        cb(null, file.stream);
    }
});

var upload = multer({ storage: storage });

app.post('/api/user/new', upload.single('img'), (req, res) => {
    if (!req.file) {
        return res.status(422).json({
            error: 'File needs to be provided.'
        });
    }

    createNewUser(req,res,stData);
}

var createNewUser = function (req, resp,stData) {
    var filesStreamm = [{
        path: req.file.originalname,
        // content: fs.readFileSync(req.file.path)
        content: ipfs.types.Buffer.from(stData)
        // content: fs.createReadStream(stData) //stData
    }];

    var deferred = Q.defer();
    deferred.notify();
    ipfs.add(filesStreamm, function (err, files) {
        if (err || !files) {
            deferred.reject();
            return console.error('ipfs add error', err);
        }
        return resp.json({ status: 'SUCCESS', message: 'Published Succesfully' });
    }


texts:
I'm working on an ethereum blockchain project where people want to make reservations in a city. I'm in this situatin
I have many users booking, but I want all these bookings to be collected by a single EOA. This EOA sends the transactions to the smart contract.

How does the EOA collect requests from users?
In this scenario I don't understand the role of the wallet. Do I need the wallet to sign the transactions that the single EOA sends?


texts:
Tokens have contract addresses, see https://support.metamask.io/kb/article/24-what-is-a-token-contract-address

But is there some "base" contract that manages the sending of plain vanilla ether?


texts: Why doesn't the EVM revert on integer overflow/underflow?

texts: After writing a few contracts in Solidity, I've noticed a reoccurring theme of always having to think about possible integer overflow/underflow attacks. It seems to me that Solidity should be as secure as possible by default, so that the most naive implentation tends to be secure (without having to actively add protections against common attack vecors).


texts: Where to find Ethereum introduction material?

texts:
I'm from Chile were few people know about Bitcoin and even less about Ethereum.

I finished my studies last year in business engineering and I've been involved with the technology since 2013. Right now I'm working on my own ethereum project but first I need to teach people about it so I can get together a development team... I managed to contact the head of computer sciences in my university and explained everything and he got very interested and asked me to make some presentations.

The idea is to cover Bitcoin and Ethereum, awakening the interest of students and teachers to research more about the technology and it's capabilities to conform a research and development team in the university.

For this I've prepared a nice introduction to Bitcoin and some examples related to financial innovation sites. I want to do the same for Ethereum but it's a little more complex to explain and I've found little material. As examples I'm thinking about Augur and Slockit so far.

The audience will be mainly business and computer science people.

I had confirmation to make a 2nd conference dedicated to deeply cover the bitcoin protocol, so making a 3rd to deeply cover ethereum would't be impossible but lets focus on this one.

What would you suggest? Which topics would be essential but not too deep for an intro conference?


texts: Compiler Issue or Improper State Variable declaration?

texts:
After seeing some unexpected compiler results, I've reduced the issue to this tiny example:

The following compiles under 0.4.10 in Remix:

contract StorageMapping {

    struct S {
        mapping(bytes32 => uint) m;
        bytes32[] b;
        uint x;
    }

    mapping(bytes32 => S) public sStructs;

}

However, the following fails to compile with "Internal Type is not allowed for state variable, referring to the mapping. Spot checked 3.x and 2.x. Result is consistent back to version 0.2.1 (0.2.0 throws internal compiler error).

Only difference in the contracts is the one line commented out.

contract StorageMapping {

    struct S {
        mapping(bytes32 => uint) m;
        bytes32[] b;
        // uint x;
    }

    mapping(bytes32 => S) public sStructs;

}

The important thing seems to be to add a simple value to the struct (even if not needed). This makes me wonder what's really going on.

Does anyone know a reason why the mapped struct seems to need at least one simple value to avoid confusion?


texts:
I'm doing some research about the use of open blockchain in different context. I'm trying to find the best way to evaluate capex and opex for:

hardware requirements (full node vs light node with geth 1.5)
storage requirements (full node vs light node)
data to be downloaded daily (full vs light)
bandwidth requirements (full vs light)

Do you have any insights? Do other researches about this already exist? :)

Thanks for your time like always!


texts:
is there any way to execute functions on a smart contract (as EVM-Bytecode) in a separate program like evm (provided by go-ethereum) without having to run a test-network? I need to find a way to run code multiple times so using Remix is unfortunately no option.

Thanks in advance!


texts:
I am using nodejs to call my smart contract's functions instead of calling within geth-client. Each time, when I run node call.js, it requires additional time Web3 to connect into local ethereum network. When I make many calls, it consumes a lot of time. Also this daemon may help on during development and testing my contract's function calls.

Example code: call.js (using Web3js)

var mylib = require(contract.js);

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

if(!web3.isConnected()){
    console.log("not connected");
    process.exit();
}
var myContractInstance  = web3.eth.contract(mylib.abi).at(mylib.address);
val="input";
myContractInstance.functionCall(val, {from: web3.eth.defaultAccount,gas: 300000 });

Alternative example code: call.py (using Web3py)

#!/usr/bin/env python

from __future__ import print_function
from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider

web3 = Web3(HTTPProvider('http://localhost:8545'))

contractAddress='0x...';
with open('abi.json', 'r') as abi_definition:
    abi = json.load(abi_definition)
myContractInstance = web3.eth.contract(contractAddress, abi=abi);

eBlocBroker.transact().functionCall();

[Q] In order to gain some time (get rid of over and over Web3 connection); it is possible to run a Web3js daemon or Web3py daemon on the background that connects into ethereum network only one time and later, I can use that daemon to make my smart-contract calls or talk with the ethereum network?
If yes, how?


texts: Signing Transaction wtih Metamask (not sending)

texts:
I use the following code to sign and send a transaction in my backend:

var txData = {
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gas: gasHex,
    data: contractData,
    from: ctx.mainAccount,
};

var tx = new EthTx(txData);
tx.sign(new Buffer(pKey, 'hex'));
var txHex = tx.serialize().toString('hex');

web3.eth.sendSignedTransaction(`0x${txHex}`)
    .on('receipt', receipt => { ... });

Now what I'd like to do is instead of using the private key here, I'd like to use Metamask just to sign the transaction (and not send it)

Is it possible? In other words does Metamask has a way to do something similar to tx.sign(new Buffer(pKey, 'hex')); I'd like then my backend to  send the signed transaction, not Metamask.

I tried to use web3.eth.personal like this:

//backend
var tx = new EthTx(txData);
var txHash = tx.hash();
var txUnsignedHex = txHash.toString('hex');

//browser
web3.personal.sign('0x' + txUnsignedHex, ethAccount, (err, result) => {  ... } );

But the result I get does not work when I run web3.eth.sendSignedTransaction


texts:
I use web3js, ethereumjs-tx libraries and infura http provider.
Lets say we have a contract instance
var contract= new w3.eth.Contract(abi,address);
and i want to transact with the functions of that contract using batch requests.
batch.add(contract.methods.TransferTokensTo(
amount1,
address1).send({from: '0x0000000000000000000000000000000000000000'
gasPrice:'',
gas:'',
value:'',
}, callback1));
batch.add(contract.methods.TransferTokensFrom(
amount2,
address2).send({from: '0x0000000000000000000000000000000000000000'
gasPrice:'',
gas:'',
value:'',
}, callback2));
batch.execute();

I cannot understand where and how I can sign a transaction?
I suppose that inside .send() should be more parameters but i dont know how to obtain them


texts: How to access the deployed contract's address from Truffle JS tests?

texts:
I've written a test that involves returning the token balance that the contract itself holds. In the contract source file I would access the balance using the function getBalanceOf(this). However, when I include instance.getBalanceOf(this) in my JS tests, I get a new BigNumber() is not a number error.

I've narrowed it down to my tests not having access to the deployed contract's address. I know you can access it in Solidity tests using the DeployedAddresses.sol library, but is there any way to do it in JS tests?

Cheers,
Pryce


texts: I’m new to ethereum, I just wonder  what is a good Python api to trade Eth  ?


texts: How to generate_executionScript and forward it to the Aragon for voting


texts: How does MetaMask secure / store unlocked accounts?

texts:
I understand that MetaMask stores the encrypted vault somewhere like

C:\Users\USER_NAME\AppData\Local\Google\Chrome\User Data\Default\Local
Extension Settings\nkbihfbeogaeaoehlefnkodbefgpgknn

However, when a user entered the password into metamask this vault should be decrypted so the user is able to sign transactions with it. How does MetaMask store and secure this decrypted vault / key when being unlocked?


texts: Problem with multiple event listeners, duplicated event triggers

texts:
In my app i have multiple listeners (watchers) on different events of same contract. Nothing complicated.

let songAddedEvent = instance.SongAdded({}, {
        fromBlock: 'latest',
        toBlock: 'latest'
    });

songAddedEvent.watch(function (error, result) {
    if (error) {
        console.error(error);
    }
    console.log(result);
}
-------------
/////////////////////////////////////////
-------------------------
let newVoteEvent = instance.NewVote({}, {
        fromBlock: 'latest',
        toBlock: 'latest'
    });
newVoteEvent.watch(function (error, result) {
    if (error) {
        console.error(error);
    }
    console.log(result);
}

Problem is that same event is caught multiple times, and strange thing is that event is caught exactly number_of_listeners times.

So in this case i have two listener on two different events and triggered listener is triggered 2 times

Tried with 3 listeners, then is triggered 3 times.

(Not all of them are triggered, just one listener multiple times).

I read this article https://github.com/ethereum/web3.js/issues/398 but doesn't explain why there is correlation between number of listeners and multiplication of event triggers.

Forgot to mention, console.log is called from same .js file and same line in that file.

Does somebody have an idea why is this happening??


texts: When upgrading contracts can you change the logic inside functions?

texts:
I am trying to wrap my head around all this and am looking for someone to help clarify.
Lets say I have the following:
contract Test {
    public c = 3;
    function A(uint a) returns(uint){

       uint b = a - c;
       return b;
    }

    function B() returns(uint){
       return b + a;
    }

}

Now I have found a bug in my code and function A should be this:
contract Test {
    public c = 3;
    function A(uint a) returns(uint){

       uint b = a - C();
       return b;
    }

    function B() returns(uint){
       return b + a;
    }

    function C() returns(uint) {
       return c * 2;
    }
}

Would this work in with upgrading proxy?


texts: How to convert string to bytes256 or arbitrary bytes?

texts:
I already know how to convert bytes32ToString and stringToBytes32:

 function bytes32ToString(bytes32 x)
        public
        pure
        returns (string memory)
    {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        uint j = 0;
        for (j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

function stringToBytes32(string memory source)
        public
        pure
        returns (bytes32 result)
    {
        bytes memory tempEmptyStringTest = bytes(source);
        if (tempEmptyStringTest.length == 0) {
            return 0x0;
        }

        assembly {
            result := mload(add(source, 32))
        }
    }

But how to convert string to bytes256 or arbitrary bytes? or convert arbitrary bytes to string?


texts: Programmatically convert log data (hexadecimal) into negative decimal value

texts:
I'm having some trouble converting negative numbers in the log data of an Ethereum transaction. In this transaction, log index 192, topic 3 is listed as "0xffffffffffffffffffffffffffffffffffffffffffffffdb9a1221071741566a".

Ethtx converts that hex value into a decimal of -671.4275583814931.

I'm struggling to replicate the conversion of the hexadecimal value to a negative decimal value. So far:

I can't find any functions in the Ethers.js and Web3.js libraries that convert to the right amount.
Even just using an online tool, the hex value yields an output of 115792089237316195423570985008687907853269984665640564038786156449531636569706, which isn't correct.

Are there any libraries that would convert this hex value into the correct negative decimal?


texts: I created a private ethereum tesnet using geth and it runs well on the system. However, I lose all the ethers in my account everytime I close the application. Is there a way to permanently save the testnet ethers on a wallet when is retained?


texts:
What are the prerequisites to take part in an ethereum hackathon?
I am from europe and there's the ETHBerlin in september. Is it possible to take part even if you're a beginner?

To me it seems like it's a great opportunity to learn from pros.
Thanks.


texts: How to work with inherited contracts in EthereumJ?

texts: In EthereumJ, I have two contracts i deployed them individually,first one was deployed but for the second i got error as in that i was calling function of first one and example i have second is first ,means i am inheriting first one but it showed me error Identifier not found or not unique for first.  (I tried with geth it was working fine.)


texts: how to build a smart contract using c++ in ubuntu

texts:
Can someone please assist me in creating a smart contract using cpp in ubuntu. I have installed the required software for ethereum, but all I can find is assistance on building smart contracts using Solidity. Can someone please help me or direct me on how to build a smart contract using c++ coding language.

Thank you


texts: Is code execution time limited by the block time?

texts: I'm fairly new to Ethereum, and I'm still trying to grasp the potential uses. I keep seeing articles using encrypted instant messaging as a potential application. But, there is a problem with this: from what I understand, a contract will be executed by all of the nodes on the network. The time it takes to mine a new block is ~20 seconds. So doesn't this mean that a message can take up to 20 seconds between the time it's send and received? If this is true, I can see this being a problem for real-time web applications.


texts:
I have the following line of code in Solidity:

var res = result.toSlice();

This slices a string. When trying to compile in Truffle, I am getting
var is deprecated error message. I am confused a bit, since I don't know what is the type of the variable here? Neither of my known types work here.

UPD: When changing the variable into, say, string storage, I am getting Type struct strings.slice memory is not implicitly convertible to expected type string storage pointer.

The .toSlice() function of the strings library:

/*
     * @dev Returns a slice containing the entire string.
     * @param self The string to make a slice from.
     * @return A newly allocated slice containing the entire string.
     */
    function toSlice(string self) internal returns (slice) {
        uint ptr;
        assembly {
            ptr := add(self, 0x20)
        }
        return slice(bytes(self).length, ptr);
    }

slice, apparently, is a struct:

struct slice {
        uint _len;
        uint _ptr;
    }


texts: How calculate mining hash rate from JUST difficulty and change in block creation times?

texts:
How calculate mining hash rate (H) from just difficulty (D) and change in block creation times (ΔT) ?

I think

H = ΔT / D

but I'm having trouble confirming that.

Part of the difficulty is that the values fluctuate so much that if different people take different averages they'll get different answers.

Take block 4,000,000 (4M) as an example...

D  = 1,096,303,811,407,388
ΔT = 4 seconds between block #(4M + 1) and block #4M

So H = 4 / 1,096,303,811,407,388 = 3.6E-15 ?


texts: Why I can not trade coins stored in cold wallet?

texts: There are two kinds of wallet hot wallet and a cold wallet. Ideally, people keep minimum balance for trading in a hot wallet and most of the coins are stored in cold wallet. I am wondering why coins in the cold wallet are not tradable?


texts:
I didn't try yet, but let's suppose the following:

I have an ERC721 contract token with a total Supply of 101
My contract can mint and burn
The first token has id 0 and the last one has id 100
I burned the token with id 50.

Can I mint again the token with id 50?