texts: OZ ERC20 & Chainlink solc compatibility problem

texts:
I apologize for the basic question, but I failed to find an answer via websearch & discord.
I'm trying to inherit from Open Zeppelin ERC20 which uses solc 0.7.
I also need to use Chainlink alarm clock functionality, and the stable release for that uses solc 0.6.
What is the common approach to use OZ ERC20 and Chainlink given current circumstances?

I'm willing to change my contracts from 0.7 to 0.6, but I can't find OZ ERC20 0.6 release.

Using truffle v5.1.49
Thank you.


texts: How to test contract functions with onlyOwner modifier?

texts:
I have a contract that inherits from Ownable, and some of its functions use onlyOwner modifier. I use truffle for local deployments to Ganache and testing.

Say, I have a contract:

contract MyContract is Ownable {
    function DoSomething() public view onlyOwner { return 1; }
}

A unit test for this contract is:

contract TestMyContract {
    MyContract c = MyContract(DeployedAddresses.CertifyingAgencies());
    function testDoSomething() {
        Assert.equal(c.DoSomething(), 1, "Shoudl equal 1");
    }
}

This test fails - onlyOwner modifier throws because msg.sender inside that modifier will be the address of the test contract, not the address of the owner/deployer.

How do I test such functions?


texts: Chain Specification "difficulty" vs. Hash Rate?

texts:
What does "difficulty" refer to in the chain specification, if actual difficulty is determined by hashrate?

I know that "difficulty" went down after the ETH/ETC fork, but why then is difficulty in the chain spec at all?


texts: fallback function, best practices when registering information

texts:
I'm currently working on a smart-contract, and I have this warning in Remix :

Fallback function of contract browser/token.sol requires too much gas
(102480).
If the fallback function requires more than 2300 gas, the contract
cannot receive Ether.

I understand that, when executing the fallback method, I'm in a context of limited available gas. But for a token creation, for instance, I need to write multiple variables to have an accurate accounting of my token distribution.

function() payable {
  require(block.number > icoStartBlock && block.number < icoEndBlock);

  uint256 tokenAmount = msg.value * ((block.number < icoPremiumEndBlock) ? 550 : 500);

  shares[msg.sender] += msg.value;
  balances[msg.sender] += tokenAmount;
  balances[owner] += tokenAmount / 6;

  raised += msg.value;
  created += tokenAmount;
}

If the user that send Ether to my smart-contract know there is a need for more gas, will it be working if he sends more ? Am I doing an anti-pattern ? The the contract cannot receive Ether part of the message on Remix is scaring me a bit.


texts: add fields to ERC721 tokens, still belongs to the standard?

texts:
if starting from the code of an erc721 token, I add fields beside the name, symbol and URI, is it still a token that respects the standard?

Add in the contract, not in the JSON file.

The most general question is actually: what is the standard?

I added a field to this code, declaring the setters and adding it to the interface, it works, now I still have an erc721 token or not?

Thanks!


texts:
Newbie here!

I still not sure if I understood how some structures of Ethereum are physically stored (assuming Geth implementation)

State Trie: only one off-chain Merkle Patricia Tries stored using LevelDB;
Storage Trie: one Merkle Patricia Trie per account; stored off-chain together with the State Trie using LevelDB;
Transaction Tries: not really physically stored; a Merkle Patricia Trie is created on the fly when needed using the block transaction list;
Receipts Trie: not a clue;
Blocks: State trie and Storage tries are stored in .ldb files (LevelDB), but where can I find the block files and which format are they stored?


texts: How to load Solidity source file into geth

texts:
Is it possible to load Solidity source file .sol file to go-ethereum.

I am using the 'loadScript' method by saving a .js file like the following and loads it.

source = "contract test {\n" +
"   /// @notice will multiply `a` by 7.\n" +
"   function multiply(uint a) returns(uint d) {\n" +
"      return a * 7;\n" +
"   }\n" +
"} ";

Is there any better way? I don't want to use browser-solidity


texts: How to get owned tokens contract addresses for particular wallet address

texts:
I want to get all contract address of all assets present in my metamask wallet so that  I can fetch
balance of all tokens using web3


texts: Multiple instances of web3 to talk to multiple chains

texts:
I am building an oracle to watch for an event on one chain and respond by sending a transaction to another chain. Creating multiple instances of Web3 (version 1.0.0-beta.26) is fine but how do I create Contract objects with the correct provider? It seems to depend on the currentProvider of the last instantiated Web3 object rather than the currentProvider of the Web3 object used to build create contract object.

Suppose one chain is accessible on port 8546 and the other on 9546. I create two instances for web3:

web3a = new Web3('ws://localhost:8546');
web3b = new Web3('ws://localhost:9546');

But then if I try and get a contract on the a chain, it will try and talk to the b chain. e.g.

const someContract = new web3a.eth.Contract(...)
console.log(someContract.currentProvider.connection.url)

will log ws://localhost:9546, the b connection url rather than the a connection that I would expect.

Anybody know what I'm doing wrong or what I'm misunderstanding?


texts:
Following is my code:

pragma solidity >=0.4.17;

contract Lottery {
    address public manager;
    address[] public players;

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

    function enter() public payable {
        require(msg.value > 0.01 ether);
        players.push(msg.sender);
    }

    function random() private view returns (uint256) {
        returns unit(keccak256(abi.encodePacked(block.difficulty, now, players)));
    }

}

And I am getting following error:

browser/ballot.sol:17:9: ParserError: Expected primary expression.
        returns unit(keccak256(abi.encodePacked(block.difficulty, now, players)));
        ^-----^

Current version is 0.5.1+commit.c8a2cb62.Emscripten.clang

How to resolve this error?


texts:
When a token goes through the process of an ICO, there are various buyers, and those buyers would then receive the tokens in their Ethereum wallets.

QUESTION:

How are tokens distributed during an ITO (Initial Token Offering)? Does the token owner(s) send them with the transfer function, or are there other methods that spend less gas? Ideally speaking, knowing what the common practices are and the benefits to each option is what I would like to know

WHAT I KNOW / THINK ALREADY:

ITOs usually require you to send Ethereum to a specific account, and then have a mechanism of sending to coins to either the account that sent Ethereum during the ICO, or a website that gets the input of which account should receive it, with some method of verifying you're the person sending the money to them. There are probably other methods, like sending the token to an exchange and people buying directly from there.

What I am not sure of is how these ICO's send the money to the buyers. Do they send them individually using the transfer function (like the one that exists with ERC20 tokens)?  What are the most common practices and their benefits?


texts: Is there any concern for the significant number of nodes being hosted on AWS/ cloud providers?

texts:
Just curious if there is any downside that many nodes are being hosted on cloud providers?

For example Infura, which supports many nodes and provides a large portion of connections to Ethereum nodes, is all hosted on AWS.

AWS has been proven to be secure and reliable, but are there any downsides in the long-run for the health of the network?


texts: Out of Gas invoking precompiled contracts on private blockchains

texts:
Why do precompiled contracts lead to Out of Gas on private blockchains?

Some tidbits are provided in the Solidity docs but can it be explained more?

  It might be that you run into Out-of-Gas for sha256, ripemd160 or
  ecrecover on a private blockchain. The reason for this is that those
  are implemented as so-called precompiled contracts and these contracts
  only really exist after they received the first message (although
  their contract code is hardcoded). Messages to non-existing contracts
  are more expensive and thus the execution runs into an Out-of-Gas
  error. A workaround for this problem is to first send e.g. 1 Wei to
  each of the contracts before you use them in your actual contracts.
  This is not an issue on the official or test net.

What is happening that "these contracts only really exist after they received the first message (although their contract code is hardcoded)"?

How does sending 1 Wei make these contracts "really exist"?

Will allocating 1 wei in the genesis block of a private blockchain, for each of these contracts, avoid the Out of Gas?


texts: How to use the hashimoto light algorithm in pyethash?

texts:
I have a problem with using the hashimoto light algorithm in pyethash.

I am using pyethash version 23.1 and comparing the results with ethash.run (ethashjs 0.0.7).

Using the same inputs the result should be the same but I am getting different outputs on OSX 10.10.

pyethash:

import pyethash

blocknr = 229
headerHash = "123deb946d8dd98c79b527d3da0a19210a7193fd6a9c1f496b2c26c9ca4a7933"
nonceStr = "a8c2231491f43da2"

cacheSize = pyethash.get_cache_size(blocknr)
seed = pyethash.get_seedhash(blocknr)

cache = pyethash.mkcache_bytes(
        cacheSize,
        seed).encode('hex')

nonce = long(nonceStr, 16)
fullSize = pyethash.get_full_size(blocknr)

light_result = pyethash.hashimoto_light(fullSize, cache, headerHash.decode("hex"), nonce)
print "result: " + ''.join(x.encode('hex') for x in light_result['result'])

ethashjs:

const Ethash = require('ethashjs');
const levelup = require('levelup');
const memdown = require('memdown');
const BN = require('bn.js');

var block = 229;
var headerHash="123deb946d8dd98c79b527d3da0a19210a7193fd6a9c1f496b2c26c9ca4a7933"
var nonce="a8c2231491f43da2"

var cacheDB = levelup('', {
    db: memdown
});
var ethash = new Ethash(cacheDB);

ethash.loadEpoc(block, function(){

    var result = ethash.run(new Buffer(headerHash, 'hex'), new Buffer(nonce, 'hex'));
    console.log("result " + (new BN(result.hash)).toString(16));

});

The implementation in ethashjs should be correct (It was used to validate a hash for mining a block in my test net). Maybe somebody got a pointer for me!


texts: Solidity: How to verify Keccak-256 value?

texts:
I want to pass a Keccak-256 hashed value from the front-end, say a string "experiment". I store the value in Solidity, and, when passing the same value for the second time, a Solidity function needs to compare the values, and give true, if those values are identical.

I have been unsuccessful of comparing the values so far. I am trying this online tool: Link , and then generate the value in Solidity via keccak256('experiment'). The results do not seem to match.

Any advice on how to achieve that?


texts: Using web3.eth.estimateGas cause "gas required exceeds allowance or always failing transaction"

texts:
In solidity code I have function addPhase and it works well. The code  below also works well

for (let j = 0; j < companies[i].phases.length; j++) {
    transactions.push(
        this.contract.addPhase(
            companies[i].phases[j].start_time,
            companies[i].phases[j].prices_in_wei,
            companies[i].phases[j].prices_in_wei_ends,
            companies[i].phases[j].tokens_count,
            companies[i].phases[j].min_tokens_to_sell,
            Web3Helpers.sender_envelope(sender,10000000000)));
}

But if I try to estimate gas consumption

for (let j = 0; j < companies[i].phases.length; j++) {
    let call_data_phase = this.contract.addPhase.getData(
        companies[i].phases[j].start_time,
        companies[i].phases[j].prices_in_wei,
        companies[i].phases[j].prices_in_wei_ends,
        companies[i].phases[j].tokens_count,
        companies[i].phases[j].min_tokens_to_sell
    );
    let gas_needed_phase = Web3Helpers.web3.eth.estimateGas({
        data: call_data_phase,
        to: this.contract.address,
        from: sender
    });
    console.log("Gas estimation=" + gas_needed_phase);

    transactions.push(
        this.contract.addPhase(
            companies[i].phases[j].start_time,
            companies[i].phases[j].prices_in_wei,
            companies[i].phases[j].prices_in_wei_ends,
            companies[i].phases[j].tokens_count,
            companies[i].phases[j].min_tokens_to_sell,
            Web3Helpers.sender_envelope(sender,10000000000)));
}

I get error gas required exceeds allowance or always failing transaction. I use similar code for other functions and gas estimation works well.

Has anybody seen something like this and what could it be?


texts:
I would like to know if it is possible to create tokens that have a different address or id for each one.

I need to create a series of "objects" with the same structure but with the values of different fields, as objects of an object-oriented language, and access it individually.

it's possible? is there any erc standard that offers these features?

Thanks!


texts: Are ICO's that create a new crypto-token exclusively for companies that are building a DApp?

texts:
Or can one do an ICO that creates a new crypto-token for any normal application that isn't built as a DApp?

I'm asking because there are certain new company ideas that would benefit from utilizing their own new token economy, but where the application that uses the token economy doesn't benefit from being built as a DApp.


texts: Why does Ropsten consume more Gas than Rinkeby?

texts:
I deployed the following smart contract both to Rinkeby and to Ropsten.

    pragma solidity ^0.5.8;

    contract storeHash{

        string private vehicleData;

        function setVehicleData(string memory _vehicleData) public{
           vehicleData = _vehicleData;
        }

    }

A transaction with an IPFS hash (QmRAQB6YaCyidP37UdDnjFY5vQuiBrcqdyoW1CuDgwxkD4) to the contracts consumes 26,719 Gas on Rinkeby (https://rinkeby.etherscan.io/tx/0x9d25520ba42f35e23943e9226a031c9fd287d3b9acb1ea0f0b0d9fbe40064991) and 41,119 on Ropsten (https://ropsten.etherscan.io/tx/0xed4863b705986353abda658661c00e682cadb446c36af7c7217f4e51ff050eef)
why is that the case?


texts:
I am now working on the smart contract for secondary market, which is the stock negotiation. For example, user A wants to buy a stock, user sets the acceptable price and the amount. The order will be put into the "Buy array", waiting for the match price. If user A wants to sell a stock, just as the procedure of buying a stock, user sets the price and the amount to sell. What I am thinking now is creating a struct Order as follow:

struct Order {
        uint256 orderno;
        uint256 time;
        address from;
        uint256 price;
        uint256 amount;
    }

Using struct, we can have the instance of Buy and Sell strcut

Order[] public Buy
Order[] public Sell

and we can create function of Buy and Sell.  //user put buy order

  function buy(address _from,uint256 _price, uint256 _amount) onlyOwner public {

        uint256 dealamount;
        uint256 dealprice;

        for(uint256 count = 0;count <s.length;count++)
        {
            if(_amount==0) {
                break;
            }
            if(_price>=s[count].price)
            {
                dealprice = s[count].price;
                if(_amount >= s[count].amount){
                    dealamount = s[count].amount;
                }
                else {
                    dealamount = _amount;
                }
                s[count].amount-= dealamount;
                _amount-=dealamount;
                sectransfer(this,_from,dealamount,dealprice);
                deal(this,s[count].from,_from,now,dealamount,dealprice);//event
                sellmatch[s[count].price]-=dealamount;
            }
        }
        removezerosell();
        //no deal, push into buy struct
        if (_amount > 0)
        {
            insertbuy(Order(orderno,now, _from, _price, _amount));
            //b.push(Order(orderno,now, _from, _price, _amount));
            //sortbuy();
            buymatch[_price] += _amount;
            orderno++;
        }
    }

function sell(address _from,uint256 _price, uint256 _amount) onlyOwner public{

    //if(msg.sender != owner) return;
    //check user have enough token
    if(balanceOf[_from] < _amount ) return;
    temptransfer(_from,this,_amount);

    uint256 dealamount;
    uint256 dealprice;

    for(uint256 count=0;count<b.length;count++)
    {
        if(_amount==0){
            break;
        }
        if(_price <= b[count].price){
            dealprice = _price;
            if(_amount >= b[count].amount){
                dealamount = b[count].amount;
            }
            else {
                dealamount = _amount;
            }
            b[count].amount -= dealamount;
            _amount -= dealamount;
            sectransfer(this,b[count].from,dealamount,dealprice);
            deal(this,_from,b[count].from,now,dealamount,dealprice);
            buymatch[b[count].price]-=dealamount;
        }
    }
    removezerobuy();
    if (_amount > 0)
    {
        insertsell(Order(orderno,now, _from, _price, _amount));
        //s.push(Order(orderno,now, _from, _price, _amount));
        sellmatch[_price] += _amount;
        orderno++;
    }
}

Is there a better way of doing the concept of trading stock and the secondary market? Or what can I improve the buy and sell function?


texts:
I've created an Account on Ropsten Testnet with MetaMask, and I've on some test-ether and developed some smartcontracts.
Now I want to export my account on Ethereum Wallet, so I've exported the private key with metamask and imported on geth with command:

geth account import C:\MYFILEWITHPRIVETEKEYONIT.txt

But when I open the Ethereum Wallet and set it on Testnet, i see my account address but with no ether on it.
I've noticed that in Etehereum Wallet the account imported has in the name (Etherbase).
So i think that it has not been correctly imported.

What's wrong with? Thanks


texts: Deployed Contract Instance Isn't Detected in Testrpc via MetaMask

texts:
When MetaMask tries to access my local testrpc, I'm getting the following error in the browser:

contract.js:424 Uncaught (in promise) Error: UnitManager has not been deployed to detected network (1509577107908)

Here is my 2_deploy_contracts.js:

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

module.exports = function(deployer) {
  // deployer.deploy(UnitManager)
  let hash = ''
  deployer
  .then( () => {
    return UnitManager.new()
  })
  .then( instance => {
    instance.setRole(web3.eth.accounts[1], 3, {from: web3.eth.accounts[0]})
    return instance
  })
  // ...

I've tried to set the network id explicitly (you can see that in my error) in truffle.js and in the command $ testrpc -i 1509577107908.

module.exports = {
  migrations_directory: "./migrations",
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      // network_id: "*" // Match any network id
      network_id: "1509577107908" // Match any network id
    }
  }
};

Notice that I'm not using the standard deployer.deploy() command.  I'm using new() because I need the instance object to run subsequent commands in deployment.

What am I missing here?


texts:
Here is a basic hash test.  I am trying to reproduce the output with: http://emn178.github.io/online-tools/sha3_256.html

Is sha3-256 correct?

The output for '1' as the value input is b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6 but I cannot reproduce this with the calculator.

contract HashTest {

bytes32 public hashOutput;
uint public valueOut;

function hash(uint _values) {
    var value = _values;
    valueOut = value;
    hashOutput = sha3(value);
}

function refund() {
   msg.sender.send(this.balance);
}
}

Also I am using "var" because that is how it was provided in the blind auction example and once I can get the hash to match I will create a more complex function using var if possible.


texts: Interactions between contracts regarding multiple transactions

texts:
What approach should be taken when a given contract requires from another to perform multiple transactions in a single call?

Should it be separated semantically, like any "normal" piece of code?

ContractA {

    changeState1() {

    }

    changeState2() {

    }
}

ContractB {

    changeState1ContractA() {
        ContractA contractA = ContractA(address);
        contractA.changeState1();
    }

    changeState2ContractA() {
        ContractA contractA = ContractA(address);
        contractA.changeState2();
    }

    changeState1changeState2ContractA() {
        ContractA contractA = ContractA(address);
        contractA.changeState1();
        contractA.changeState2();
    }
}

Or instead should it be exposed as a new method -wrapping the 2 calls into 1, to be exposed as a single transaction? Losing that way the semantics, but favoring gass and latency economics.

ContractA {

    //Omitted

    changeState1changeState2() {
        changeState1();
        changeState2();
    }
}

ContractB {

    //Omitted

    changeState1changeState2ContractA() {
        ContractA contractA = ContractA(address);
        contractA.changeState1changeState2();
    }
}

Which, utlimately, it leads me to my final question. How does ethereum internally compute several transactions when they have been called sequentially from another contract?

changeState1changeState2ContractA() {
    ContractA contractA = ContractA(address);
    contractA.changeState1();
    contractA.changeState2();
}

Thanks.


texts: "Error: exceeds block gas limit" from truffle console

texts:
I successfully deployed my contract on ropsten network. But when I try to call any functions in the contract, I got Error: exceeds block gas limit error.
I set gas limit 4700000 in my truffle.js file. How can I check and change the gas limit on truffle console? What is wrong with it?


texts:
I want to sign every transaction server side from the same address/wallet through web3.

What's the best way to tackle this?
Do I need to:

first use web3.eth.sendTransaction
Use web3.eth.sign to sign the transaction?

Cheers and happe new year!


texts: how do I make users sign different strings with their private key separatelly

texts:
Here is the the scenario.

Users come to my website and register(by using email and password). Then they login. After that, They add a new item(which has name and quantity fields). After Clicking submit, What happens is in a front-end or back-end, I generate the same amount of UUID-s that the quantity he specified. For example, if he added a new item ("Toy123", 15), I generate 15 UUID-s on that page. Then what I need to do is this user to sign these UUIDS with his private key. The thing is, I could make all 15 UUIDS into one and let user sign this final one with his private key, But I don't like this option because I need different kind of signatures for each uuids because each uuids means each item and each item is different. So what I need him to do is to sign these uuids seperatelly. I tried metamask, but It's not great, because to sign separatelly, metamask pops up a confirmation dialog for each uuids. Imagine if an user specified 150 uuids, 150 confirmation dialog? Doesn't seem great. That's why I don't want to use metamask. The second option is to ask an user for his private key and then sign each uuids programatically, but if I ask an user his private key, he is gonna be afraid.

I tried to explain the whole situation I'm facing.
The question is: What do I do to sign an user's uuids separatelly with his private key without asking his private key? Is it possible with metamask?


texts: Is there a good reason to implement ERC721 standards?

texts:
I am working on a non-fungible token implementation and like everyone else, I started with the ERC721 standards. However, my use case is not exactly fitting in the standards defined by ERC721. For instance, I want multiple person to own one token (non divisible) and there are other issues as well because of which I am unable to implement all those functions.

My question is: Is it really necessary to implement those standards if my web client is the only client that is going to interact with my contract?

I do understand that the standards provide a generic interface for existing wallets to interact with the contract. What if I don't want this functionality? Can I skip the standards and implement a non fungible token without ERC721?


texts:
This is bugging me so much time and spent hours and hours on this, I'd really appreciate your help so much....
 // this costs 21394
 function test2() external  {

 }

 // this costs 21507
 function test2() external  {
    uint[1] memory t;
 }

The difference is 21507 - 21394 = 113. Note this number: I really want to get 113 by calculating it by myself. So, Here it is what I do.
I look the additional assembly that line produces and count the gas for each opcode and sum them up.  Here it is: https://www.diffchecker.com/XSJC4EJb .  So everything in red should be calculated. I follow the gas cost for each opcode on the whitepaper or on this link: Link
So, by my calculation, if we sum up all the gas costs for all red opcode, we will get 104 gas.
Now, we need to calculate the expansion cost.
uint[1] memory t causes 2 extra slots to be created(0x60, 0x80). So, by following the expansion cost formula:

We got the following: (53 + 5^2/512) - (33 + 3^2/512) = 15-9 = 6. I used 3 and 5 numbers in there, because before starting, the memory was 3 slots only, after calling it, it became 5 slots.  Now, since we got 6, if we sum this up with 104 which we got by summing up opcode gas costs, we get 110. But the compiler difference was 113.
How do I get 113 instead of 110 ?  I really want to know since I already spent so much time and hopefully, you can give it a shot. I guess, This is for you, Ismael most probably.


texts: input argument in remix of a value sub 1

texts:
How to input/format a value such as 0.2 in the remix browser as percentage?

e.g. function transfer(address _to, uint256 _value, uint256 percentage) public returns (bool);

(don't mind the function it's for demonstrative purpose)


texts: How do you implement PubSub without running out of gas (attack vector)?

texts:
A simple PubSub pattern involves an array of subscribers. Anyone can subscribe. A publish function will do something for each subscriber. Can you spot the attack vector...?

contract PubSub
{
    address[] subscribers;

    function PubSub() {
    }

    function Subscribe() {
        subscribers.push(msg.sender);
    }

    function Publish(uint value) {

        // if a malicious user spams Subscribe then
        // this loop will never complete, rendering
        // this function unusable
        for(uint i=0; i<subscribers.length; i++) {
            // do something with subscribers[i]...
        }
    }
}

An attacker can call Subscribe from numerous addresses until the subscribers array is so large that Publish will become unusable, always hitting an out-of-gas error.

What is a good way around this, while retaining publish subscription capabilities? I am thinking that some kind of fee-based priority queue might be a solution, but I want to check here first to see if anyone else has encountered this problem or has a good solution in mind. Thanks!


texts: Should I use the 'external' modifier to return a large array?

texts:
If I need to access a large array from my contract... say for my front end. Should I be using external to make it cheaper for myself?

A comment by William Entriken on this question is what got me thinking about this:
https://ethereum.stackexchange.com/a/19391/40675

What might be the limitations with this if it is a good idea in terms of fixed vs dynamic array?


texts: How to run the example of `web3.eth.contract`?

texts:
I first start ganache. Then, I run the following commands. But I got the following error. Does anybody know what is wrong? Thanks.

$ geth attach http://localhost:8545
Welcome to the Geth JavaScript console!

instance: EthereumJS TestRPC/v2.1.0/ethereum-js
coinbase: 0x61ee7ad67c57759a03f84d29c5de219ef359016a
at block: 0 (Tue, 10 Apr 2018 16:38:25 CST)
 modules: eth:1.0 evm:1.0 net:1.0 personal:1.0 rpc:1.0 web3:1.0

> var abi = [{
...      name: 'myConstantMethod',
...      type: 'function',
...      constant: true,
...      inputs: [{ name: 'a', type: 'string' }],
...      outputs: [{name: 'd', type: 'string' }]
... }, {
...      name: 'myStateChangingMethod',
...      type: 'function',
...      constant: false,
...      inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }],
...      outputs: []
... }, {
...      name: 'myEvent',
...      type: 'event',
...      inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]
... }];
undefined
> var MyContract = web3.eth.contract(abi);
undefined
> var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');
undefined
> var result = myContractInstance.myConstantMethod("myParam");
Error: Attempting to run transaction which calls a contract function, but recipient address 0xc4abd0339eb8d57087278718986382264244252f is not a contract address
    at web3.js:3143:20
    at web3.js:6347:15
    at web3.js:5081:36
    at web3.js:4102:22
    at apply (<native code>)
    at web3.js:4227:12
    at <anonymous>:1:14


texts:
I am trying to compile this code:
contract C {
    struct s {
        string chan;
        string content;
    }
    s[] x = new s[](0);
}

And it lands me with a confusing compiler error:
Unimplemented feature:
/solidity/libsolidity/codegen/ArrayUtils.cpp(237): Throw in function solidity::frontend::ArrayUtils::copyArrayToStorage(const solidity::frontend::ArrayType&, const solidity::frontend::ArrayType&) const::<lambda(solidity::frontend::CompilerContext&)>
Dynamic exception type: boost::wrapexcept<solidity::langutil::UnimplementedFeatureError>
std::exception::what: Copying of type struct BlueSimple.s memory[] memory to storage not yet supported.
[solidity::util::tag_comment*] = Copying of type struct BlueSimple.s memory[] memory to storage not yet supported.


texts: Using create migration primitive with truffle

texts:
I am following this guide doing custom migrations with truffle.

When I run truffle create migration deploy_hello_world it creates this path migrations/1501429988_deploy_hello_world.js/migration.js. Once I configure the deployer and rename the migration.js file and remove the parent folder I run truffle migrate --reset and receive this error:

truffle migrate --reset
Using network 'development'.

Running migration: 1_initial_migration.js
/usr/local/lib/node_modules/truffle/build/cli.bundled.js:36916
  throw new Error("Could not find artifacts for " + import_path + " from any sources");
  ^

Error: Could not find artifacts for ./Migrations.sol from any sources
    at Resolver.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:36916:9)
    at ResolverIntercept.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:219315:32)
    at /Users/mokn1/Development/Ethereum/hello-world/migrations/1_initial_migration.js:1:28
    at ContextifyScript.Script.runInContext (vm.js:32:29)
    at ContextifyScript.Script.runInNewContext (vm.js:38:15)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:83185:14
    at tryToString (fs.js:449:3)

Not sure what I need to do to get past this step as it seems to be an issue with running the primitive itself. Thank you for any help.


texts: Uniswap Price Feed.- Get price of a Token in a Solidity contract

texts:
I am looking to retrieve the current price of a token from Uniswap. I have successfully used the ChainLink oracle api to get the price of BTC/USD, but I want to now integrate Uniswap price feeds.
I cannot seem to find one that just retrieves the current price of a token in ETH. Has anybody ever attempted this before?


texts: Calling overloaded function from geth client

texts:
Attaching a geth client to a ganache-cli instance:

$ geth attach http://localhost:8550
Welcome to the Geth JavaScript console!

instance: EthereumJS TestRPC/v2.0.2/ethereum-js
coinbase: 0x322ecad098ba9125e5f5b35a390051af1592ab91
at block: 27 (Thu, 05 Apr 2018 15:51:09 BST)
 modules: eth:1.0 evm:1.0 net:1.0 personal:1.0 rpc:1.0 web3:1.0

I am attempting to call a contract function that has overloaded functions:

function transfer(address _to, uint256 _value, bytes _data)
function transfer(address _to, uint256 _value) //This one is called

After creating an interface on geth to access the contract functions, calling transfer results in a call to the second function definition.

How can I call a specific overloaded version of a contract function?

There doesn't seem to be a way to use encodeFunctionCall as shown with truffle here via geth.


texts:
we set up our own ethereum instance using geth and the "clique" consensus mechanism. We have now 20 nodes and only 1 of them is a miner.
My problem is: It seems like, that only the miner node is able to process transaction receipts (read event logs and so on) and all the other nodes fail. Why is that? Could it be because we used "fast" as syncmode?

Edit: ok, it seems like we are able to process receipts from other nodes. But: Transactions coming from other nodes, but the miner node, are pending for a very long time. Even though the gas limit is set to 20.000.000 and a transaction on averages uses only 300.000. It seems like we never get more than 1 or 2 transactions in one block

Edit: We were able to solve the problem. Our genesis file contained the parameter "MinGasLimit". Not sure why, but we removed this parameter and everything works fine now.


texts:
I found only one semi-automatic solution to transfer tokens from one wallet to another.

But i want to do that by web3js way on ruby stack. Could you guys explain me, how exatly to get data for eth_sendTransaction data field with no using web3js (contract.transfer.getData("0xCb...", 10, {from: "0x26..."})).

UPD.

I got the point about components of data.

For example let's get transaction 0xd21fa94958692c0aa3523ae9e8984067976483ec57642554a1dda0417e3337e2

Input data:

  MethodID: 0xa9059cbb
  [0]:  000000000000000000000000c1816acca0a3a120fc980c58cb485d41f2b30e8e
  1:  0000000000000000000000000000000000000000000000000000000000007530

So, MethodID is encrypted function by keccak256. By than i am trying to get this result by same logic:

  Digest::SHA3.new(256).digest('transfer(address,uint256)')
  => "\xA9\x05\x9C\xBB*\xB0\x9E\xB2\x19X?JY\xA5\xD0b:\xDE4m\x96+\xCDNF\xB1\x1D\xA0G\xC9\x04\x9B"

Why do I get different resultsЮ

Second parameter is address (000000000000000000000000c1816AcCA0a3A120fc980c58CB485D41F2B30E8e). Original one is 0xc1816AcCA0a3A120fc980c58CB485D41F2B30E8e. Next we trim few hex chars and what we should do next to generate same result?
And last param is amount. What should we do to convert 3 tokens to 0000000000000000000000000000000000000000000000000000000000007530.


texts: Transaction pending on Etherscan but not showing on Metamask

texts:
I tried to speed up and cancel from Metamask but it disappeared from the there and still showing on Etherscan like pending https://etherscan.io/tx/0x178a435501bfe9e4eda4dc3dc47708a3756148c2aac76e340534c18e728f25f9
Tried to send a tx offline with the same Nonce but it keeps giving an error.
Is there anything else I can do to cancel the txs?
Cheers!


texts: Approving Addresses & Preventing Direct Access To Storage Contract

texts:
I am looking into creating a DAPP that can be upgraded via new contracts, to do this I am looking at separating the storage out into a separate contract.

My only concern is security, it was put to me that the storage contract could allow for only certain external contract addresses to interact with them. If we take the following example:

contract Storage {

    address approvedAddress;

    function update(address _sendingAddress, __MORE_HERE__) public {
        if(_sendingAddress == approvedAddress){
          // Do Stuff
        }
    }
}

From my calling contract I call update and pass in the calling contracts address to _sendingAddress the address is then checked to see if it matches the approved address. If it does I can update the storage.

However what is stopping someone from calling the update function directly without going through the calling contract and guessing at the address?


texts: How to hide data and reveal it in a smart contract

texts:
I know the topic has already been discussed but I did not find any satisfying answer. Do you know a way to put some private data in the blockchain and release / reveal it to a designated personn.

I know about zk proof but from my understanding its purpose is to prove something without revealing it. I want to hide data (a password) and revealing layer when a condition is met.

Thank you very much for your help


texts: The Real Cost to Foward Transaction to EOA via Smart Contract?

texts:
I'm creating a smart contract that does the following:

Checks that a userID parameter is included as data field OR
that the last 4 zeros of the amount being sent is not equal to zero (i.e, 0.1230000000000001234 is OK. 0.1230000000000000000 or 0.1230000000000001004 are not OK)

...
 function accept() public payable {
        require(msg.value == 0.00000000000000XXXX);
        // X means non zero
    }

If neither of the above rules are satisfied the contract "rejects" the transaction. If either of the above is satisfied the total amount is forwarded to a EOA (assume to an address with a non zero balance)
I'm trying to calculate the estimated gas costs in each of the following scenarios:
When the Transaction Succeeds:
In this case, the gas costs can be calculated as follows:

21,000 base gas cost

the fee to invoke the smart contract which evaluates whether userID/wei marker are present (which I believe is < 500 gwei according to this document)

the fee for each byte of data that is included in the transaction (such as a userID) which is approx. 68 gwei per byte (we could assume max of 1 byte for the userID)

the fee for the smart contract to transfer/forward funds to the EOA for invoking send or transfer or call.value().gas function. According to this thread the fee is fixed at 2,300

In addition, as the creator of the contract I would pay a one time fee for deployment

So 21,000 + (approx.) 500 + 68 + 2,300 = 28,068.
When the Transaction Fails:
If neither of the two conditions are satisfied, the transaction would be rejected by the contract (so the funds would not be forwarded) but the sender would still need to pay:

a fee for invoking above function (approx. 500)

(??) the base fee of 21,000?

In addition, as the creator of the contract I would pay a one time fee for deployment

Does the sender still pay 21,000 base fee when the transaction is aborted?
Do I have the correct approach in calculating the fee in each of the above scenarios?
Thanks!


texts: Proper way to save a public key as bytes in a contract

texts:
I need to save public keys in many contracts.
Despite that this choice costs, I store them as bytes (I know that the best way is to split the key and store it to different bytes32 constants, but that is not the case right now).

I use web3 and EthCrypto.

So, I create the key pair and compress the public key.

keypair = EthCrypto.createIdentity()
compressedPublicKey = EthCrypto.publicKey.compress(keyPair.publicKey)

The output of the above is this:

Public Key: 766cbaa7e623704f93852e162cc0e3fc9cae211819218e00b5e486376724bd7dbd3c64eb7465ab754cb0ecfbbe7ae65d4ecc8df91b74b65948d1254a0eb389c3

Compressed Public Key: 03766cbaa7e623704f93852e162cc0e3fc9cae211819218e00b5e486376724bd7d

Private Key: ...

If I just concatenate '0x' to the beginning of the public key, I am able to store it in the contract. Without concatenating '0x', it gives me the error that "Public Key is not bytes".

Now, there is the other option.
I can use web3's toHex:

web3.utils.toHex(compressedPublicKey)

This outputs: 0x303339633665306635653264633537626231383332623333613537316230383830343563343031323835356136313935313630333663663839356565343737373136

And, of course, I can save this as well to the contract.

But, there's some questioning.
Concatenating '0x' and storing it to the smart contract, is not proper (but it works).

Converting to hex and then passing it to the smart contract, I think that is the proper way, but it "requires" 67 more digits to be saved.

Compressed Public Key (68 digits with '0x'): 0x039c6e0f5e2dc57bb1832b33a571b088045c4012855a619516036cf895ee477716

Conversion to hex (135 digits): 0x303339633665306635653264633537626231383332623333613537316230383830343563343031323835356136313935313630333663663839356565343737373136

What is your opinion on this?


texts: Fetch the mapping variable history from Ethereum blockchain

texts:
I am using ganache and truffle for building DApp,

In my smart contract, I have declared one mapping variable, now in function I am assigning some value to that mapping variable. Every time I am assigning different values to that mapping variable.

Now, I want that what are the different values which has been assigned to that mapping variable till now means fetching the history of that mapping variable. So how to that, is there any way to fetch all the details of state variables (mapping in my case) ?


texts: SOLVED - sendRawTransaction (no) errors, valid tx, not found when scanned

texts:
I have a method that is supposed to create a transaction, send some wei and validate. When looking around I red that you can use infura.io. I also checked that you need to use raw transactions because infura doesn't handle it and it doesn't handle events anymore. But when trying to commit a tx it blocks at the data level. I am not sure if i am just calling my method wrong or if something is missing. I have tested with a method of type view and it returns true / false but transactions are not going through.
I am using ethereumjs-tx and web3 0.x.x (0.20.3)

var web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/XXXXXXXX'));
var contract = web3.eth.contract(abi);
var contractInstance = contract.at('contract address');

// ERROR here / JSON RPC Error
    var data = contractInstance.myMethodInContract(100, {from: 'client address', value: payment_amount});

var rawTx = {
      from: 'client address',
      to: 'contract address',
      value: payment_amount,
      data: data
    }

    var privateKey = new Buffer('private key here', 'hex')

    var tx = new Tx(rawTx);
    tx.sign(privateKey);

    var serializedTx = tx.serialize();

    web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
        if (!err)
            console.log(hash);
        else
            console.error(err);
    });

Update
Following the comments about adding nonce and fixing the data fields. I did so as follow.

var nonce = web3.eth.getTransactionCount('client adress') + 1;
var data = dataPass.contractInstance.getData(100);

var rawTx = {
    ...
    nonce: web3.toHex(nonce),
    ...
}

I got a transaction hash and it returns a tx hash but i have an error transaction underpriced, please note that i red the docs and checked it mutliple times therefore in my work / code i only included what i needed to skip what would be calculated by itself.

I have added the gasPrice and gasLimit to get rid of the transaction underpriced and intristic gas too low errors.

var gasPrice = web3.eth.gasPrice.toNumber() * 1.40
var rawTx = {
     ...
     gasPrice: web3.toHex(gasPrice),
     gasLimit: web3.toHex(100000),
     ....
}

I get a hash but i get nothing when i check the status on https://ropsten.etherscan.io i am told Sorry, we are unable to locate this Transaction Hash.

0x0a7605689071e...e

When reading around (not sure if true or not) the chainId for the rawTx was needed but to get the network Id you need web3 1.0 as i checked 0.20 doesn't have it implement (might be wrong) and even to hardcore the chainId doesn't seem good but for a started i ll get it but i am unable to find a way to get the chainId from transactions (viewing detail of any tx on the blockchain). When trying static numbers like in examples i saw i get a Error: invalid sender.
Following this Can not send eth on Ropsten using Infura node I have added the proper chainId but i am not seeing the transaction on the https://ropsten.etherscan.io Sorry, we are unable to locate this Transaction Hash.

I was adding  a + 1 to my nonce value which apparently made it not go through. To who wonders I added a + 1 because someone encountered an issue around where his tx wasn't going through and the proposed solution was the + 1 to nonce due to a potential pending tx already attempting to go through.

var nonce = web3.eth.getTransactionCount('client adress');


texts: What should I call the object returned from a Truffle contract function-call

texts:
When I perform a contract function-call via Truffle, and then resolve the returned promise, I get something like this:

{
    "tx": "0x...",
    "receipt": {
        "transactionHash": "0x...",
        "transactionIndex": 0,
        "blockHash": "0x...",
        "blockNumber": 24,
        "gasUsed": 42860,
        "cumulativeGasUsed": 42860,
        "contractAddress": null,
        "logs": [
            {
                "logIndex": 0,
                "transactionIndex": 0,
                "transactionHash": "0x...",
                "blockHash": "0x...",
                "blockNumber": 24,
                "address": "0x...",
                "data": "0x...",
                "topics": [
                    "0x...",
                    "0x...",
                    "0x..."
                ],
                "type": "mined"
            }
        ],
        "status": "0x1",
        "logsBloom": "0x..."
    },
    "logs": [
        {
            "logIndex": 0,
            "transactionIndex": 0,
            "transactionHash": "0x...",
            "blockHash": "0x...",
            "blockNumber": 24,
            "address": "0x...",
            "type": "mined",
            "event": "Transfer",
            "args": {
                "from": "0x...",
                "to": "0x...",
                "value": "0"
            }
        }
    ]
}

I'm not really sure how exactly Truffle wraps web3.js in order to invoke contract functions, so I'm not really sure where to look in the web3.js documentation. But I am using Truffle v4.1.14, which relies on web3.js v0.18.4, and the docs for web3.js v0.x are kinda hard to read, so I searched in the docs for web3.js v1.x instead.

Now, I guess I should be looking into web3.eth.sendSignedTransaction, which returns:

  A promise combined event emitter. Will be resolved when the transaction receipt is available.

So it seems that Truffle takes this receipt, and embeds it into a JSON object which contains the following additional fields:

tx, which is the transaction hash, I suppose
logs, which contains some or all of the receipt.logs, but decoded

So what exactly is going on here?

This new object is certainly not the receipt described in the docs.

Is there an official terminology for this, or is it just a "Truffle hack" designated to make my life easier decoding events?

Thank you.


texts: How to get string from hex on Smart Contracts results

texts:
On a Smart Contract called "mem" there is a function called "get()" that returns a bytes32 that is supposed to be a string. How can I decode the string? The result is an hex value. I have tried toString() on geth console, but I am probably doing something wrong...

  mem.get();
  "0x4d61726b65745061792e696f206973206465706c6f79696e6720536d61727420"
  mem.get().toString();
  "0x4d61726b65745061792e696f206973206465706c6f79696e6720536d61727420"
  mem.get().toString('hex');
  "0x4d61726b65745061792e696f206973206465706c6f79696e6720536d61727420"


texts: How can my Rig slow down that much in short period?

texts: I wonder why my Rig used to mine 1Ether in 24h and now it takes up to 38h for 1. I have moved the Rig to another place, could that be the reason? Thanks


texts: Constructor parameters not being deployed on the blockchain issue #1118

texts:
this issue has been closed however I still see this in my code, contract deplyes, but the constructor does not see the args, I have tried this with both, version 1.0.0-beta-30 as well as 1.0.0-beta-36

here is my code, would appreciate any help...abi and bytecode are too long to paste here, but I can provide those if needed

`

let bContract =  new web3.eth.Contract(abi);
let hexdata = bContract.deploy({
    data: bytecode,
    arguments: ["testbet", ["one", "two", "three" ], 123, 200],
});

let rawTx = {
    nonce: web3.utils.toHex(9),
    gasPrice: web3.utils.toHex(web3.eth.gasPrice),
    gasLimit: web3.utils.toHex(1000000),
    data: "0x" + hexdata,
    from: runENV.acctAddr,
}

let tx = new Tx(rawTx);
tx.sign(runENV.privateKeyBuffer);

let serialzedTx = tx.serialize();

web3.eth.sendSignedTransaction('0x' + serialzedTx.toString("hex"))
    .on('receipt', console.log);


texts: In current Ethereum, smart contracts are executed by the CPU/RAM of nodes who are rewarded the gas from the transaction. Will this be the same in Casper? Are there any pools for this specific purpose currently?


texts: Gas cost of setting a state-variable to the same value

texts:
According to this spec, setting a state-variable to the same value consumes 200 gas.
However, I conducted a test over ganache-core v2.10.2, and the result was closer to 800 gas:
Solidity Contract:
pragma solidity 0.6.12;

contract MyContract {
    uint256 public gasUsed;
    uint256 public storageSlot;
    function func(uint256 x) public {
        storageSlot = x;
        uint256 gasLeft = gasleft();
        storageSlot = x;
        gasUsed = gasLeft - gasleft();
    }
}

Truffle 5.x Test:
const MyContract = artifacts.require("MyContract");

contract("MyContract", () => {
    it("test", async () => {
        const myContract = await MyContract.new();
        for (let x = 0; x < 10; x++) {
            await myContract.func(x);
            const gasUsed = await myContract.gasUsed();
            console.log(gasUsed.toString());
        }
    });
});

The printout is 816 for every iteration, and assuming that the gasleft() operation in the last line of the contract function costs 16 gas, storing the same value appears to cost 800 gas.
I suspect that gas cost in the spec applies to older EVM versions (prior Istanbul or something like that), where SLOAD used to cost 200 gas.
In the current EVM version, SLOAD has changed to 800 gas, so I believe that the case of SSTORE of the same value may have changed to 800 gas as well.
Does anyone have any idea about this discrepancy?


texts: What happened to an ETH transaction that shows up pending for a period of time and then disappears?

texts: I sent ETH to an address and it showed pending for a period of time on etherscan and then disappears. Is it dead or canceled or lost or what? If I send a duplicate transaction what happens to the first one?


texts: Cannot connect to ethereum private network

texts: When I do /Applications/Mist.app/Contents/MacOs/Mist --rpc /Users/mushahid/Library/Ethereum/geth.ipc I get connected to Ropsten instead of my private network.


texts: How can I maintain a sorted list in my smart contract?

texts:
Is it crazy to feel the need to sort solidity arrays?

Imagine implementing a market (double action) you need to sort the orders. I could imagine other usecases where sort is useful. But as we all know even a for loop is dangerous in terms of gas exhaustion. What are best practices in this regard?

The search "Solidity Quicksort" returns nearly no results.

I came up with the idea of letting someone sort and upload the data back to the smart contract, then smart contract can just check if the data is right + sorted, which should be much easier than sorting. O(nlogn) versus O(n). The problem here is that the transaction size grows by O(n) now, which, I feel, could be problematic.

Any guidelines, experiences?


texts: Is it possible to tell which node broadcast a transaction?

texts:
If I host my own node and send my transactions through this node, can somebody see that my address sends transactions through my pseudo-anonymous node?

If yes, can someone set up a watcher that tracks all transactions through this node?

If no, can you spin up two node (one physical close to and one physically far away from the node in question), and estimate where the node is based on when these two nodes receive a transaction? This would be similar to pinging a website from one side of the country vs the other to check latency and determine where the servers are.

Edit:

In this presentation (at ~14:00), the speaker talks about the GeoIP information as well as "cycling their eNodes for privacy...I don't want somebody to be detecting where tx are originating from" (at 15:30). This makes me think that the answer above is yes.

Looking at this site, it appears that you can actually get a location (based of IP, I assume).


texts: How to send ether from one account to another in a smart contract deployed on testrpc

texts:
I'm interested in writing a smart contract using solidity that sends ether from one account to another. What would the syntax be? If possible, could you point me to a solidity contract that sends ether from one party to another?

For example, say two parties enter into a smart contract, they both wager some ether on a coin flip. In the case of the coin flipping heads, the person who called heads should get the money both people wagered.


texts: How to connect Remix desktop to connect to MetaMask?

texts:
I downloaded the desktop version of Remix, and am trying to connect it to the main network. I can do this in the web version of Remix easily, opening up MetaMask on my browser. However, in the desktop version, when I toggle 'injected Web3' for the environment, I get the error: 'No injected web3 provider found. Make sure your provider (eg MetaMask) is active and running'.

How do I connect MetaMask to the Remix Ethereum IDE for Windows desktop?


texts: Can we use any address and set web3.eth.defaultAccount?

texts:
I have a method in solidity and wants to return the sent string only for the owner address.

function greet(string str) returns(string) {
    if (msg.sender == owner) {
    return str;
    } else {
        return "Sorry I respond only to my owner";
    }
}

In Rinkeby testnet, I am able to set the address directly without unlock or signing with private key
web3.eth.defaultAccount = '0xC2107dFbCf6a70865f30fc439b1850bE434231c9';

and when i greet.call('Hello').... method I get the passed string returned perfectly and gets back 'Hello'

So my question is can anyone use my public address in web3.eth.defaultAccount and call the greet method ? I want only owner with private key can pass the test (msg.sender == owner). How can others without private key get through it ?


texts: Are contracts deployed to the same address on different chains susceptible to replay or other attacks?

texts:
A contract can be deployed on different chains at the same address by using the same private key with the same nonce on each chain.

Given that forking a chain opens up possible replay attacks on acounts, does deploying parallel contracts also open up similar attacks upon the users of those contracts?


texts: how to be notified about incoming transactions instantly?

texts:
I'm creating a platform which users are able to receive ETH on their own wallets (addresses). They will give the addresses to others, but the question is how can I be notified that new transactions happened on that addresses automatically?
One way is to check the history of addresses periodically, but by having many users, this mechanism will consume a huge amount of resources. Is there any appropriate way to know about valid incoming transactions instantly?


texts:
I've been trying for weeks to recover password for my ETH from a year ago. No luck.
How does this python recover thing work? Is it something you have to download? Or where do you type things?
Can anyone step-by-step explain this, I'm a complete newbie when it comes to this.

Much appreciated.

Peter


texts: Private ethereum network account related query

texts:
Please help with below queries:

how to reset the paraphrase for an account on private ethereum network
Is there a way to delete an account on private ethereum network
How to enable the etherscan url for Private Ethereum network

I appreciate your help!!


texts:
I'm using the crowdsale contract from the ethereum site but I have made a few changes. I added a tokenWithdraw function, if the beneficiary runs it you can withdraw a set amount of tokens from the contract. I have tested and it works fine.

However the safeWithdraw function which should do the same thing except withdraw ETH rather than the Token does not work when I run it as the beneficiary. The ETH just stays in the contract for some reason and I have no idea why.

pragma solidity ^0.4.2;
contract token { function transfer(address receiver, uint amount); }

contract Crowdsale {
    address public beneficiary;
    uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price; uint public tokenW; uint public ethW; token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool fundingGoalReached = false;
    event GoalReached(address beneficiary, uint amountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);
    bool crowdsaleClosed = false;

/* data structure to hold information about campaign contributors */

/*  at initialization, setup the owner */
function Crowdsale(
    address ifSuccessfulSendTo,
    uint fundingGoalInEthers,
    uint durationInMinutes,
    token addressOfTokenUsedAsReward
) {
    beneficiary = ifSuccessfulSendTo;
    fundingGoal = fundingGoalInEthers * 1 ether;
    deadline = now + durationInMinutes * 1 minutes;
    price = 25;
    tokenReward = token(addressOfTokenUsedAsReward);
}

function () payable {
    if (crowdsaleClosed) throw;
    uint amount = msg.value;
    balanceOf[msg.sender] = amount;
    amountRaised += amount;
    tokenReward.transfer(msg.sender, amount * price);
    FundTransfer(msg.sender, amount, true);
}

modifier afterDeadline() { if (now >= deadline) _; }

function checkGoalReached() afterDeadline {
    fundingGoalReached = true;
    GoalReached(beneficiary, amountRaised);
}

function closeCrowdSale()  {
  if (beneficiary == msg.sender) {
  crowdsaleClosed = true;
  }
}

function withdrawTokens(uint tokenW) {
  if (beneficiary == msg.sender) {
    tokenReward.transfer(msg.sender, tokenW);
  }
}

function safeWithdrawal(uint ethW) {
    if (beneficiary == msg.sender) {
      FundTransfer(beneficiary, ethW, false);
    }
 }
}


texts:
I am new to Solidity and I am reading Cryptozombies tutorial. I am stuck with mapping part, I understand how it works mapping(key => value) mappingName but I don't understand what is the output of that or where should it be used, I checked videos and articles and still confused. So my question is not about how it works, it is about the purpose of using it.

I am JS coder but is there is a way mapping relevant to .map in JS?


texts:
i'm new to solidity and trying to understand the better storage option for the factory contract. i want:

to be able to get all deployed contracts.
to be able to get all deployed contracts by creator

The option i see is to create an array to track all contracts and mapping to reference the creators, ex:

contract CampaignFactory {

    Campaign[] campaigns;
    mapping(address => Campaign[]) campaignsByOwner;

    function createCampaign(uint min_contrib) public {
        Campaign newCampaign = new Campaign(min_contrib, msg.sender);
        campaignsByOwner[msg.sender].push(newCampaign);
        campaigns.push(newCampaign);
    }

    function getAllCampaigns() public view returns (Campaign[] memory) {
        return campaigns;
    }

    function getCampaignByAddress(address creator) public view returns (Campaign[] memory) {
        return campaignsByOwner[creator];
    }
}

alternatively, i could use a struct like:

struct CampaignDeployed() {
    address creator;
    address[] campaigns;
}

but in that case as i understand, to get a campaigns by owner i will have to iterate over all in for cycle, which is something possibly too expensive (?).

So, the questions is, what is the typical approach to tackle such problem? does the solution with array + mapping acceptable?


texts:
I'm making a simple dApp that sends funds from one account to another using Truffle + MetaMask on testrpc. In my app.js, I have a pay() function that calls

web3.eth.sendTransaction({from: account1, to: account2, value: web3.toWei(amount,"ether")}

When the function is triggered via the HTML page and the transaction pops up on MetaMask, the funds get deducted from account1 but do not show up on account2. I think it might be because the contract hasn't been properly mined or MetaMask is slow? The chrome extension shows the contract as "Published", not "Pending" though.

If I perform the same command via the truffle console, the transaction gets processed appropriately, and I can verify that the value has been transferred from account1 to account2. How can I fix this? I've tried restarting chrome.

Link to my app.js file: https://gist.github.com/jw122/bda506dc831e200ac5eb397b36cb2db5

Link to solidity contract:
https://gist.github.com/jw122/c561c8059ca239df6623db9080805634

I deploy the contract in 2_deploy_contract.js with:

deployer.deploy(Purchase, web3.eth.accounts[1], web3.eth.accounts[2], {from: web3.eth.accounts[0], gas: 4000000});


texts: What possibly could go wrong if I leave my private blockchain node 30303 port open to public?

texts:
I have the following setup:

All the nodes inside my cluster are talking to each other via 30303 port. When I want to talk to them, I'm using a Geth light client via HTTP JSON RPC port 8545.

Only the Geth light client here opens HTTP JSON RPC. All my nodes in the cluster doesn't open HTTP JSON RPC port. They only open 30303 port.

All nodes in my cluster and my Geth light client node shared the same genesis.json file. The enode address of all the nodes in the cluster are keep private and has not leaked to public yet.

So my question here is, what possible could go wrong with this setup in terms of security?

Could someone (a bad guy) do anything bad to my private blockchain cluster if I keep the 30303 port open to public?

Could they guess the content of the genesis.json file and the enode addresses?


texts: Can it be shown that `num > 0 && num < denom` is always the same as 0% < num / denom < 100%?

texts:
In Solidity, I want to check that the numerator and denominator passed to my function evaluate to 0% < num / denom < 100%.

I tried the most direct approach: num / denom > 0 && num / denom < 1 but e.g. 1% (1 / 100 > 0 && 1 / 100 < 1) evaluates to false, because Solidity doesn't have decimals.

My other idea is num > 0 && num < denom. Can it be formally proven that that is always the same as 0% < num / denom < 100%?


texts: Why did an Event Fire even though Etherscan suggests it failed?

texts:
I am attempting to count the number of DepositEvents in the Medalla Beacon Contract. At first, I attempted to do this by counting the number of Deposit Events, however, I noticed a Deposit Event that was triggered even though Etherscan suggests it failed.
Why is there a red x on Beacon Chain Deposit even though a deposit event was logged?


texts: What is the zero value of an Emum when initialized inside a struct of a mapping ?


texts: Suggest solution and/or literature on secure distributed voting

texts:
I'm a complete noob when it comes to blockchains and cryptocurrencies, but I am quite skilled with math and CS, so hopefully I am able to ask the correct questions and understand the answers
For a while I was troubled by secure online voting.  Here is the (hopefully) minimal example of the problem: Let's say kids vote if they want to have a cat in the kindergarten. If they do, they say so to the teacher, and she should write their names on the board. Everybody may look at the board at any time. It is known that teacher is a bit dishonest, and may ignore some requests, or add a few people to the list that did not vote for the cat. Also, some kids are dishonest, and will claim that they voted differently than they actually did. Under the assumption that most kids are honest, can one design a protocol where, for every conflict between a kid and the teacher, the majority of the kids could correctly identify who of them was dishonest.
That is the easy version. The hard version is where privacy is also required, so that nobody (including the teacher) knows whose names are on the list, but can still have a good estimate if the list is inconsistent, and to what extent.
Please tell me

For easy and hard version, if this is possible
If it is possible, explain briefly how it works
Link to a good resource where I can learn more about this stuff


texts:
Using Parity, sometimes I see something like:

2017-09-25 00:19:21     1/25 peers

and sometimes it's

2017-09-24 16:19:13     0/ 2/25 peers

What is that first number?

Why does it only appear sometimes?

Why does it mean that it's zero?

Thank you.


texts: Stack too deep, try removing local variables with 13 variables

texts:
i am getting this error because i added so many arguments, i know it has a limit of 16 argument but i don't have 16 or more, yet i stil get the sam error. even when i used an array ( like some answers said to ) i still get the error.

here is the function that the error points to  :

CODE :

  enum Gender { Male, Female }
  enum Status {New,Pending,Validated,ToRevalid}

function getPerson(bytes32 personAddress)
    public

    constant
    returns(bytes32,
    bytes32 email,
    bytes32 fname,
    bytes32 lname,
    uint index,
    bool deleted,
    Gender gender,
    string image,
    Status status,
    bytes32[13] details
    )
  {
    if(!isPerson(personAddress)) return;
    else{
      if(persons[personAddress].deleted == true) return;
      else{

      details[0]=persons[personAddress].RIM;
      details[1]=persons[personAddress].BirthCity;
      details[2]=persons[personAddress].BirthCountry;
      details[3]=persons[personAddress].FatherName;
      details[4]=persons[personAddress].MotherName;
      details[5]=persons[personAddress].Citizenship;
      details[6]=persons[personAddress].Residency;
      details[7]=persons[personAddress].Grade;
      details[8]=persons[personAddress].CorpCountryCode;
      details[9]= persons[personAddress].IntroducedBy;
      details[10]=persons[personAddress].HowIntroduced;
      details[11]=persons[personAddress].website;
      details[12]=persons[personAddress].DeceasedDate;
        return(
          personAddress,
          persons[personAddress].email,
          persons[personAddress].fname,
          persons[personAddress].lname,
          persons[personAddress].index,
          persons[personAddress].deleted,
          persons[personAddress].gender,
          persons[personAddress].image,
          persons[personAddress].status,
          details
        );
      }
    }

  }


texts: Mist Wallet unable to sync due to connection error

texts:
Clearly, my internet is working. It didn't have a problem before. Then I got off geth and started using testnet, to which it ceased to sync. Fine.

Then I got back on geth, everything is back to normal, except I get the following error repeatedly with every new chain segment import:

What can I do to eliminate this and sync my wallet again?


texts: Error: Truffle Box at URL https://github.com/truffle-box/bare-box.git doesn't exist. Even after updating truffle

texts: I am getting the Error: Truffle Box at URL https://github.com/truffle-box/bare-box.git doesn't exist. If you believe this is an error, please contact Truffle support. Even after updating of truffle to 5.1.49.


texts:
Hi I have this error :

transact to Roulette.betSingle errored: Error: gas required exceeds allowance or always failing transaction

My programm :

contract Roulette {

uint public lastRoundTimestamp;
uint public nextRoundTimestamp;

address _creator;
uint _interval;

enum BetType { Single, Odd, Even }

struct Bet {
    BetType betType;
    address player;
    uint number;
    uint value;
}

Bet[] public bets;

function getBetsCountAndValue() public constant returns(uint, uint) {
    uint value = 0;
    for (uint i = 0; i < bets.length; i++) {
        value += bets[i].value;
    }
    return (bets.length, value);
}

event Finished(uint number, uint nextRoundTimestamp);

modifier transactionMustContainEther() {
    if (msg.value == 0) throw;
    _;
}

modifier bankMustBeAbleToPayForBetType(BetType betType) {
    uint necessaryBalance = 0;
    for (uint i = 0; i < bets.length; i++) {
        necessaryBalance += getPayoutForType(bets[i].betType) * bets[i].value;
    }
    necessaryBalance += getPayoutForType(betType) * msg.value;
    if (necessaryBalance > this.balance) throw;
    _;
}

function getPayoutForType(BetType betType) constant returns(uint) {
    if (betType == BetType.Single) return 35;
    if (betType == BetType.Even || betType == BetType.Odd) return 2;
    return 0;
}

function Roulette(uint interval) {
    _interval = interval;
    _creator = msg.sender;
    nextRoundTimestamp = 1517784279 + _interval;
}

function betSingle(uint number) public payable transactionMustContainEther() bankMustBeAbleToPayForBetType(BetType.Single) {
    if (number > 36) throw;
    bets.push(Bet({
        betType: BetType.Single,
        player: msg.sender,
        number: number,
        value: msg.value
    }));
}

function betEven() public payable transactionMustContainEther() bankMustBeAbleToPayForBetType(BetType.Even) {
    bets.push(Bet({
        betType: BetType.Even,
        player: msg.sender,
        number: 0,
        value: msg.value
    }));
}

function betOdd() public payable transactionMustContainEther() bankMustBeAbleToPayForBetType(BetType.Odd) {
    bets.push(Bet({
        betType: BetType.Odd,
        player: msg.sender,
        number: 0,
        value: msg.value
    }));
}

function launch() public {
    if (now < nextRoundTimestamp) throw;

    uint number = uint(block.blockhash(block.number - 1)) % 37;

    for (uint i = 0; i < bets.length; i++) {
        bool won = false;
        uint payout = 0;
        if (bets[i].betType == BetType.Single) {
            if (bets[i].number == number) {
                won = true;
            }
        } else if (bets[i].betType == BetType.Even) {
            if (number > 0 && number % 2 == 0) {
                won = true;
            }
        } else if (bets[i].betType == BetType.Odd) {
            if (number > 0 && number % 2 == 1) {
                won = true;
            }
        }
        if (won) {
            if (bets[i].player.send(bets[i].value * getPayoutForType(bets[i].betType)))
            throw;
        }
    }

    uint thisRoundTimestamp = nextRoundTimestamp;
    nextRoundTimestamp = thisRoundTimestamp + _interval;
    lastRoundTimestamp = thisRoundTimestamp;

    bets.length = 0;

    Finished(number, nextRoundTimestamp);
}

}

HELP ME PLEASE ! :)


texts: Inheritance and Function Overwriting: Who can call the parent function?

texts:
I want to know who is still able to call an original overwritten function in case of inheritance.

Let's assume I have the following setup:

contract A{
   address public owner;

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

   function doSomething(){
       // does something
   }
}

contract B is A{

   function doSomething(){
       require(msg.sender == owner);
       // do something like A but restrict this function execution to owner
       super.doSomething();
   }

}

If I deploy contract B can some external account that is not the owner still call doSomething of parent contract A? Or could some malicious contract execute the following:

contract EvilDoer{

    function doSomethingEvil{
         A contractB = A(addressOfdeployedB);

         contractB.doSomething();
    }

}

Or are overwritten functions shielded from external use?

EDIT: Overloading

Maybe it would be interesting and helpful to me and others to elaborate on the following as well: What happens in case of function overloading, i.e. if the signature in the child class is different from its parent (e.g. assume function doSomething(uint256 someNumber){...} in contract B)?


texts: What happened to the average blocktime during this period?

texts:
What happened to Ethereums blocktime from April to October last year (2017)?

In the whitepaper, Vitalik said the difficulty should adjust at a maximum rate of 0.1% per block (around 100% per 12 hours). Is this not the case nowadays?


texts: How to retrieve elements from a mapping to an array of structs

texts:
I have recently started playing around with SmartContracts and I have run into a problem which I can not find a solution to.

I have the following struct and mapping in my Smart Contract:

struct Object{
    string objId;
    uint256 rank;
}

mapping(address => Object[]) public userObjects;

Using the truffle console I'm trying to retrieve the objects within the userObjects in the mapping like so:

truffle(development)> object = myContract.userObjects(accounts[0], 0)

truffle(development)> object
Result { '0': '1', '1': <BN: a>, objId: '1', rank: <BN: a> }

Looking at the Result I can see that the objId and the rank are correct. Now I would like to access these fields but I cannot figure out how I can do that. I have tried the following:

truffle(development)> object.objId
undefined
truffle(development)> object.rank
undefined

Am I referencing the attributes incorrectly?
Is it possible to do that in the first place?

I am using truffle version 5.0.32

Sorry if I am missing something obvious.


texts:
I am a new learner. I am confusing on how to get the web3.js work on a shared hosting. The user who uses the function must have Metamask installed.

As I am using shared hosting, I can't install the node or geth on the shared hosting.

I downloaded the web3.js from https://github.com/ethereum/web3.js/ and uploaded the files to the shared hosting then linked to the HTML file.

I follow the guide on this post
Is it possible to use web3.js API methods to interact with a contract deployed on Rinkeby?

and add the code to the  tag

I am using a domain with https://

I am using Google Chrome browser.

I installed Metamask and logged in, connected to the Rinkeby Test Network.

I upload the following HTML file to the shared hosting server and run it but got the error

Below is the full HTML code I used for testing.

<!doctype>

<meta charset="UTF-8">
<title>Hello Project</title>

Hello Project

The HTML web3.js cannot detect the Rinkeby Test Network as the provider.

What have I miss? Advises are much appreciated. Thanks


texts: Does Geth Clique will get affected when difficulty increases to its maximum?

texts:
I have started own private network with clique consensus algorithm in GETH. Regardless of miners now sealer will do the job and I have period:5. Difficulty is set 0 initially but over time it is going to be increased.
So when it reaches to around 100's of billion , does that going to affect the performance? At that level of difficulty will the miners keep appearing every 5 sec?


texts: Web3.providers.HttpProvider is deprecated? How to transition to WebsocketProvider

texts:
As per https://web3js.readthedocs.io/en/1.0/web3.html#value the HttpProvider is deprecated. Using the web3 beta 1.0.

It seems funny to me that it would be being deprecated. But I am curious as to how I would transition to something else like websockets in the future using a service like Infura.

My current code is something like:

import Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined'){
    //We are in the browser and Metamask is running
    web3 = new Web3(window.web3.currentProvider);
} else {
    //We are on the server *OR* the user is not running Metamask
    const provider = new Web3.providers.HttpProvider(
    'https://rinkeby.infura.io/v3/API_KEY'
    );
    web3 = new Web3(provider);
}

export default web3;

Edit: From @Ismael how to currently implement the Infura Websocket provider Infura web3 provider for Events (.get & .watch) see answer by Maheshmurthy. As far as I know it's not production ready and
doesn't require an API key yet : https://github.com/INFURA/infura/issues/97 .

Maybe a better question is: Is there a short explanation about why httpProviders are deprecated other than: no subscriptions and they are better. And for a beginner developing with web3 -- If I just switch providers to wss what differences can I expect? Infura specific not necessary.


texts: Cannot read property 'type' of undefined - abi-coder

texts:
I'm creating a simple voting contract.
It is deployed with truffle and infura.

This is the contract code:

pragma solidity >=0.4.21 <0.6.0;

contract Voter {
    struct OptionPos {
        uint pos;
        bool exists;
    }

    uint[] public votes;
    string[] public options;
    mapping (address => bool) hasVoted;
    mapping (string => OptionPos) posOfOption;
    bool votingStarted;

    function addOption(string memory option) public {
        require(!votingStarted);
        options.push(option);
    }

    function startVoting() public {
        require(!votingStarted);
        votes.length = options.length;

        for (uint i = 0; i< options.length; i++) {
            OptionPos memory optionPos = OptionPos(i, true);
            posOfOption[options[i]] = optionPos;
        }
        votingStarted = true;
    }

    function vote(uint option) public {
        require(0<=option && option< options.length, "Invalid option");
        require(!hasVoted[msg.sender], "Account has already voted");

        votes[option] = votes[option]+1;
        hasVoted[msg.sender] = true;
    }

    function vote(string memory optionName) public {
        require(!hasVoted[msg.sender], "Account has already voted");
        OptionPos memory optionPos = posOfOption[optionName];
        require(optionPos.exists, "Option does not exist");

        votes[optionPos.pos] = votes[optionPos.pos]+1;
        hasVoted[msg.sender] = true;
    }

    function getVotes() public view returns (uint[] memory) {
        return votes;
    }
}

Then I'm trying to run this node.js script:

import fs from 'fs';
import path from 'path';
import Web3 from 'web3';
import 'dotenv/config';
import HDWalletProvider from 'truffle-hdwallet-provider';

const { ACCOUNT, VOTER_CONTRACT_ADDRESS } = process.env;

async function sendTransaction() {
  const ethprovider = new HDWalletProvider(
    process.env.MNEMONIC,
    process.env.PROVIDER
  );
  let web3 = new Web3('https://');
  web3.setProvider(ethprovider);
  let { abi } = JSON.parse(fs.readFileSync(path.join(__dirname, './build/contracts/Voter.json')));

  let voter = new web3.eth.Contract(abi, VOTER_CONTRACT_ADDRESS);

  console.log('Adding option tea');
  let res = await voter.methods.addOption('tea').call({ from: ACCOUNT });
  console.log(res);
  console.log('Adding option coffee');
  res = await voter.methods.addOption('coffee').call({ from: ACCOUNT });
  console.log(res);

  console.log('Start voting');
  await voter.methods.startVoting().call({ from: ACCOUNT, gas: 4500000 });

  console.log('Voting');
  res = await voter.methods['vote(uint256)'](1).call({ from: ACCOUNT, gas: 4500000 });
  console.log(res);

  console.log('getVotes');
  res = await voter.methods.getVotes().call({ from: ACCOUNT, gas: 4500000 })
  console.log(res);
}

(async () => {
  try {
    await sendTransaction();
    console.log('successfully voted');
  } catch (e) {
    console.log('Error:');
    console.log(e);
  }
})();

But I get the error:

Adding option tea
null
Adding option coffee
null
Start voting
Voting
Error:
TypeError: Cannot read property 'type' of undefined
        at getParamCoder (/Users/username/solidity-project/node_modules/ethers/utils/abi-coder.js:866:39)

I'm using web3 1.0.0-beta.55 and truffle 5.0.26.
I managed to avoid this issue by adding a return type uint to vote function and returning an integer. But I'm trying to fix it without adding return type.
Any ideas?


texts:
Consider Three Erc20 Tokens : A, B and C
Say A and B are public tokens already deployed by someone else in the world and C is a new token that i am building myself.
Now, i want to create a swap contract say SwC.
What it aims to achieve is this :-
If an user U1 wants to swap x amount of (A and B) into x amount of C, the contract should send a approve request to U1's wallet (take meta mask for example) asking to approve a transaction for sending x amount of A and x amount of B from U1's wallet to our swap contract itself (i.e. SwC).
If the transaction is approved and mined successfully, then SwC should send x amount of C to U1's addy.
How can this be achieved ?
(Do note that i am trying to make user transfer 2 different tokens in one transaction to our Swc in order to recieve one single token C).


texts: How can I check if the tokens that I have in a certain wallet are valid

texts:
With the rise of so many ICOs and ERC20 tokens, I decided to join one of them out of curiosity but their token sale had finished and I decided to purchase some from an exchange, but the company behind the token says we don't recommend buying from any exchanges at this moment and your purchases are at your own risk.

This later on raised the question in my head that how can we check the authenticity of a certain wallet address against a, let's say ERC20 token?

I have also heard that Ether wallets are capable of receiving any ERC20 token, if that's true, how does the wallet and/or Ethereum platform keeps track of what represents what?


texts: Is it possible to store same USD-equivalent value of ether in a Contract?

texts:
Let's say my DApp requires a seamless way to transfer USD between users, given that some contract requirements are fulfilled first. Person A transfers USD to person B, the latter only gets a deposit once a condition is satisfied. I will assume some time has passed between the time the transaction initiated and the time the money is deposited into the receiver's account. All the while this is done with Ethereum Network under the hood. So, users don't know they are technically using the Blockchain.

The question is: When the money is sent to the Smart Contract, is it at all possible to retain the original USD value? If not, how would you deal with this type of problem?

If the application is responsible to ensure the money transferred is the same, there is risk. In particular, when the price of ETH goes down relative to USD, the developer will inevitably pay the difference. This solution isn't good.

Any ideas on how to deal with this scenario?


texts: My android Ethereum wallet no longer works. Have I lost them all my ETH coins?

texts:
I had installed the android application Peerther (Personal Wallet) to manage my ethereum.
It was an investment, I have not really looked at it for several months now.

I just checked right now, and the application just no longer works.
It says error and only asks me to upgrade to another application Copay, which at first look only seems to manage Bitcoins. I have to check that point though. I don't know if there are related.

The error message is:

  Could not update Wallet: Please upgrade Copay to perform this action

I'm wondering if I have lost control over all my ETH coins ?
Has anyone been in the same position as me ? Someone else using an android wallet that went no longer working ?

Do you think there's anywhere I could get my ETH coins back ?

I still have my Ox.... address for my account. It's all.

EDIT: the application name was Peerther, and not Peether as I thought I was reading on the little screen of my galaxy trend lite phone.
I have emailed the author of the application, but I got no answers yet.


texts: How to setup a high performance parity RPC service?

texts:
I'd like to provide the RPC service from a parity daemon hosted in EC2. There're multiple options regarding the instance type, if it's for production, should I choose "compute optimized" or "storage optimized"?

Is there anything system settings to tune to optimize the performance?

Any suggestions and insights are appreciated!


texts: How to post to the blockchain without a third party API like infura

texts: I have been using web3 nodejs and infura.io to build apps that interact w/ the Ethereum Blockchain and it is all great but I don't like the idea of a failure point my my apps because they rely on a third party (I.e. infura.io). How does one interact w/ the blockchain without use of a third party, obviously this is possible since infura themselves must be doing it


texts: How to prevent NFT or Enjin Token copying?

texts:
So lets say someone mints an Enjin token pointing to a 3D model asset for a game.
What prevents someone from downloading that same exact 3D model, and minting a new token that points to it?
Are the contents of an NFT hidden to others until they purchase them? I was looking at ethereum chain explorer for an NFT here:
https://etherscan.io/address/0x495f947276749ce646f68ac8c248420045cb7b5e
I do not see any links to a jpeg file. Is there a way to actually see that information?


texts:
How to return the struct data

struct Transaction  {
  address from;
  address payable to;
  uint amount;
}

I am returning like this

function transactionDetails() external view
        returns(address, address, uint) {
    address from;
    address to;
    uint amount;
    return (from, to, amount);
}

But it showing

0: address: 0x0000000000000000000000000000000000000000
1: address: 0x0000000000000000000000000000000000000000
2: uint256: 0


texts:
How can I purchase some Ethereum so that I can award it to our users for winning quiz. I am thinking of making a system where we can invoke RPC calls like this:

curl -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params": [{"from":"0xcd3b9926a4415fe1ac1090b6e2c61ff33a7be5e7", "to":"0xB708D7dF86180d1D6a486ecbc49683bb2633abE2", "value": 2e18}], "id":1}' -X POST http://localhost:8545/

The call will transfer the Ether from our totalSupply of Ether to one of our users account who wins the Quiz.

Also is it possible to create Ether accounts linked with Users using Curl request ? I want to map users in our database with the Ether account. How will we convey the Ethereum account credentials to users so that they can access it and sell Ether for real cash ?


texts:
I am a newbee to Ethereum and doing some research. I have installed the Ethereum Wallet app and synchronized the testnet.

However, to deploy my first contract in testnet, it requires some Ether, so can someone guide how to get that? I have tried to mine in testnet but unable to earn anything yet. So, are there any other ways?


texts: Signed Message Using EIP712 Specification Does Not Return Correct Address

texts:
I sign the typed data value with types data structure for domain using the EIP-712 specification by study and following https://docs.ethers.io/v5/api/signer/ and in my solidity code, I followed the method used both on the Metamask blog here https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26 and on the Compound Contract which is a live project, although the Compound Contract uses solidity version 0.5 and I am trying to achieve this using 0.7 which has major breaking changes, I have been careful to make appropriate changes.
Below is my Javascript code:
const signPayment = (recipient, amount, nonce, verifyingContract) => {
    const domain = {
        name: "Micro Payment",
        version: "1.0",
        chainId: chainId,
        verifyingContract: verifyingContract,
    };

    const types = {
        Cheque: [
            { name: "recipient", type: "address"},
            { name: "amount", type: "uint256" },
            { name: "nonce", type: "uint256" },
        ]
    };

    const value = {
        recipient: recipient,
        amount: amount,
        nonce: nonce,
    };

    signer._signTypedData(domain, types, value)
        .then((signature) => {
            $('[name=signature]').val(signature);
        })
        .catch((error) => {
            console.log(error);
        });
};

I am on Rinkeby and likewise deployed the solidity code below on Remix to the Rinkeby network.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >0.6.99 <0.8.0;
pragma abicoder v2;

contract ReceiverPays {

address public _verifyingContract;

uint constant chainId = 4;

bytes32 public sigR;

bytes32 public sigS;

uint8  public sigV;

constructor() {
    _verifyingContract = address(this);
}

struct Cheque {
    address recipient;
    uint256 amount;
    uint256 nonce;
    address verifyingContract;
}

/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(abi.encodePacked("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"));

/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant CHEQUE_TYPEHASH = keccak256(abi.encodePacked("Cheque(address recipient,uint256 amount,uint256 nonce,address verifyingContract)"));

function claimPayment(address recipient, uint256 _amount,uint256 _nonce,bytes memory _signature) public returns (address payer) {

    bytes32 domainSeparator = keccak256(
        abi.encode(
            DOMAIN_TYPEHASH,
            keccak256(abi.encodePacked(
                bytes("Micro Payment"),bytes("1.0"),chainId,address(this)
            ))
        )
    );

    bytes32 structHash = keccak256(abi.encode(CHEQUE_TYPEHASH, recipient, _amount, _nonce));
    bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));

    (sigR, sigS, sigV) = splitSignature(_signature);

    return ecrecover(digest, sigV, sigR, sigS);
}

function splitSignature(bytes memory sig) public pure returns (bytes32 r, bytes32 s, uint8 v)
{
    require(sig.length == 65, "invalid signature length");

    assembly {
    /*
    First 32 bytes stores the length of the signature

    add(sig, 32) = pointer of sig + 32
    effectively, skips first 32 bytes of signature

    mload(p) loads next 32 bytes starting at the memory address p into memory
    */

    // first 32 bytes, after the length prefix
        r := mload(add(sig, 32))
    // second 32 bytes
        s := mload(add(sig, 64))
    // final byte (first byte of the next 32 bytes)
        v := byte(0, mload(add(sig, 96)))
    }

    return (r, s, v);
}

}

I can't say for sure where exactly, I am getting this wrong. I would really appreciate all the help I can get!


texts: Encryption in Solidity - and yes of course the plaintext will be visible

texts:
I am using Solidity to write an Ethereum smart contract.

I have a specific use case that requires a piece of data to be encrypted on the chain, despite the fact that both the plaintext and the ciphertext will be visible to everyone.

So far all the answers I have read have simply pointed out, correctly, that encryption on the chain is not a good idea. As mentioned, this is a very specific use case.

Are there any libaries or functions that could make this work?


texts: ethers formatEther(wei) with max 4 decimal places

texts: I want to display a human readable balance with less decimal places like metamask does it. The function formatEther(wei) returns a string, so for proper rounding I need to parse it etc. And I wanted to ask if there is an easier method or best practice how it's done.


texts: Could more than one mapping's key point to the same memory space?

texts:
Since memory is already allocated on (array[0] = value;), I just want to change its pointing key value. Such as array[1] will allow me to access value now.

Is it possible to change the key of already mapped memory?

mapping(uint => uint) array;
uint value   = 10;

array[0] = value;              //memory is allocated, pointed by [0].

array[1] = array[0]'s_address; //I do want [1] to point same memory location as [0] without creating new memory space.
//or
uint value_addr;
assembly { value_addr := value }
array[1] -> value_addr; //if possible, at this stage array[1] should also point to the value's memory space.

array[0] -> NULL; //`array[0]` should point empty memory space.

As a result, when I make a change on array[1] it should also make change on the array[0].

Thank you for your valuable time and help.


texts: Parity - scheduled TX on local time zone

texts:
Looks like the Parity Browser doesn't show the local time zone for a "send after Date & Time' functionality.

Questions:

What is the time zone for a scheduled TX on Parity?
If the scheduled time is based on local time zone - how is this time zone calculated? Local computer time or IP?


texts: How to deploy Ethereum smart contract that requires more than 4.7M of gas on Ropsten network?

texts:
My smart contract is really huge - it requires 5.6M of gas on deploy.
I was able to deploy it once but smth has changed and i can't do it anymore.

I've tried to run miner with higher block gas limit with geth but still getting exceeds block gas limit:
https://stackoverflow.com/questions/51437227/geth-targetgaslimit-not-working

How can i do it on Ropsten network (testnet)?


texts: Geth/Ropsten light node can't find suitable peers even after adding peers

texts:
I am trying to deploy a test contract on Ropsten test net. I have started a light node using the command:

geth --testnet --datadir=./.ropsten --syncmode=light --rpc --rpcapi="personal,eth,network,web3,net"--rpcaddr localhost --rpcport 8545

When I try to deploy my test contracts using truffle, I am getting the error "no suitable peers available". From what I understand from similar questions, I am aware that we are able to add peers from this gist: https://gist.github.com/rfikki. However, even after successfully adding the peers (all returning true) and the node is up-to-date, I am not able to deploy the contract or call functions like getBalance() due to the "no peers" error.

Does this mean that the peers in the gist are not running now, and I am not able to connect with any of those peers? Also, other than adding the peers, or adding bootnodes, is this the only solution for the "no suitable peers" error when running a light node?


texts: Two way BTC payments for Ethereum smart contract

texts:
Are there any good ways to make two way payments by BTC to Ethereum smart contract?

Simply put, I want to make a button "Pay by BTC" for DAPP, but it could make a return payment to the return address. Are there really working tools/services for this?

This is fine if the «bridge» will take small fee or use not the best exchange rate. I understand it.


texts:
environment: Web3 0.20.7,Infura,node.js(backend)
Deploy contract with Web3 0.20.7

pragma solidity ^0.5.1;

contract Bang{
    address holder;
    address proxy;
    constructor (address _holder, address _proxy) public {
        holder=_holder;
        proxy=_proxy;
    }
    function getholder() public view returns(address){
        return holder;
    }
}

var Tx = require('ethereumjs-tx');
var Web3 = require('web3');
const testnet = 'https://ropsten.infura.io/';
const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var wallet_address = "0x4b2194Fa5a.....";
var count = web3.eth.getTransactionCount(wallet_address);
var data = "0x608............"//from remix detail
var holder = "0xF2C44b7f10533....";
var proxy = "0xf21BF631C5382....";
var rawTransaction = {
  "from": wallet_address,
  "nonce": web3.toHex(count),
  "gasPrice": web3.toHex(5000000000),
  "gasLimit": web3.toHex(5000000),
  "data": data
};

var privateKey = new Buffer('CEA8070A7EC5........', 'hex');
var tx = new Tx(rawTransaction);

tx.sign(privateKey);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'),
  function(err, hash) {
    if (!err)
        console.log(hash);
    else
        console.log(err);
});

These codes would deploy that contract,but the constructor argument cannot be into the contract. How to insert the constructor argument in web3 0.20.7 with infura?


texts:
i have a question :

how i can create a app to buy ether ?, i know how to create a Token sale but i dont know what api or what i need to buy ether directly

i see websites like coinbase to buy ether , but i really wanna know how that websites buy ether, i wanna deploy a dapp with buy ether directly from there, but i dont know what i need to do that , somebody can help me ? :(

thanks for read <3


texts:
Trying to send a transaction with web3 on ropsten. The code runs on Remix, but now I'm trying to send it via the node console. It connects fine too(web3 works), but for some reason the transaction never gets sent.  I'd love some feedback on my code

const Web3 = require("web3");
const solc = require("solc");
const Tx = require('ethereumjs-tx')
const web3 = new Web3(new
    Web3.providers.HttpProvider("https://ropsten.infura.io"));

    var account1= "0xE5078b80b08bD7036fc0f7973f667b6aa9B4ddBE";
    var key1 = new Buffer('xxxx_validprivatekey_xxxx', 'hex')

var abi = huge_abi
var bytecode = huge_bytecode

var Contract = web3.eth.contract(abi)

const gasPrice = web3.eth.gasPrice;
const gasPriceHex = web3.toHex(gasPrice);
const gasLimitHex = web3.toHex(3000000);

var nonceval = '0x' + new Date().getTime();

var fTx = {
    nonce: nonceval,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: bytecode,
    from: account1
};

var txx = new Tx(fTx);
txx.sign(key1);

var sTx =txx.serialize();

web3.eth.sendRawTransaction('0x' + sTx.toString('hex'), (err, hash) => {
    if (err) { console.log(err); return; }

    // Log the tx, you can explore status manually with eth.getTransaction()
    console.log('contract creation tx: ' + hash);
});


texts: The  geth account new and web3.eth.accounts.create. That both function/command are same are different.To create new account.


texts: Is there a Javascript client for Ethereum, like Geth?

texts: Ethereum's Github has ethereumjs-lib.  It appears to be a collection of modules, but is it also a client like Geth?  If so, how can one run this Javascript client?


texts: Extract all blocks data from etherchain into a csv file

texts: i want to extract data from etherscan into a csv file or format. wanted to extract all blocks mined yet and transactions done till yet


texts: What Continuous Integration services support running Truffle Solidity tests?

texts: What are the best practices for running a CI server that runs Truffle Solidity tests?


texts: web3.eth.accounts/web3.eth.getAccounts returns only the first account

texts:
After initiating testrpc,

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

it is displaying 10 accounts, but when accessing web3.eth.accounts/web3.eth.getAccounts, it returns only the first account. What went wrong?