texts:
I have this code to create hash.

function getUniqueHash(address _hashunique) public view returns (address)
    {
        bytes20 b = bytes20(keccak256(msg.sender, block.timestamp));
        uint addr = 0;
        for (uint index = b.length-1; index+1 > 0; index--) {
            addr += uint(b[index]) * ( 16 ** ((b.length - index - 1) * 2));
        }
        return address(addr);
    }

But I do not want to give me only one, but to give me a list of hashes when requested by the user.

For example, user asks for 1000 hashes, he has to give me 1000 unique and different hashes, and assign an ID to that batch of 1000 hashes.


texts: How do I implement buffer/readable stream in order to add a file to IPFS?

texts:
I'm trying to upload a file from my directory to IPFS.

Below is what they require from API:

const files = [
  {
    path: '/tmp/myfile.txt',
    content: (Buffer or Readable stream)
  }
]

ipfs.files.add(files, function (err, files) {
  // 'files' will be an array of objects containing paths and the multihashes of the files added
})

I don't understand what they mean by "Buffer or Readable stream." More specifically, I'm not sure how to implement it correctly because I haven't done it before.

What is the difference between "path" and "content"? Why do they need to be separated?

Source: https://github.com/ipfs/js-ipfs/tree/master/examples/ipfs-101


texts:
I cloned the safemoon smart contract and deploy on BSC testnet.
I am testing some of the functions just to understand how it works.
How do I implement in the smart contract so that the developer wallet gets like 1% of the liquidity fee?


texts: password no longer working (but others do)

texts: I've been using mist 7-4, windows, but it does the same thing in other versions.  my crowdsale password has been working fine til today.  other passwords from other accounts still work fine.  what could cause this to happen?


texts: How to check if a particular address is already present in an array

texts:
I know a similar question has been asked before but I want to understand where am I going wrong in terms of logic for the code below. I am building a lottery contract where if an address has been added once then that address can no longer play again. I am using a for loop to check if the address is present.
When I deploy the contract and run the addPlayer function I get an error stating: transact to lottery.addPlayer errored: VM error: invalid opcode. invalid opcode The execution might have thrown. Debug the transaction to get more information.
contract lottery
{
        //Defining the Owner
            address Owner;
            constructor() public
            {
                 Owner = msg.sender;

            }

        // Defining players

            struct person
            {
                string name;
                uint age;
            }

        // One to one mapping of player and its address
            mapping (address => person) players;
            mapping(string => bool) userExists;

        // creating a list/array of players
        address[] playersAddressList;

        // Tracking balance;
            uint public balance=0;

        //Function to add a player to the lottery
        bool public flag=false;

        function addPlayer(string memory a, uint b) public payable
        {
               //Checking if the player already exists in the list

                for(uint i=0; i<=playersAddressList.length; i++)
                {
                    if(playersAddressList[i] == msg.sender)
                    {
                       flag=true;
                       break;
                    }
                }

                require (flag==false);

                address creator = msg.sender;
                playersAddressList.push(creator);

                balance = balance + msg.value;
                require (msg.value >= 1 ether);

                person memory newPerson;

                newPerson.name = a;
                newPerson.age = b;

                players[creator] = newPerson;
        }
     // Function to get the player details'
      function getPlayerDetails(uint a) public view returns(string memory, uint)
        {
            address playersAddress = playersAddressList[a];
            return (players[playersAddress].name, players[playersAddress].age);
       }
}


texts: I have been running Ethereum Wallet for some time now and have used drag and drop to enter contract address for the ERC20 tokens that I watch. However, I have downloaded the Mist app. and have tried to drag and drop the contract address for the watch tokens and it keeps changing to the Ethereum Webpage instead of remaining on the token contract page. Therefore, it is impossible to drag and drop. I also copied the contract address and it will not allow me to paste a copy on the token watch page. How are you guys doing this so I can play too?


texts: Using truffle migrations for seeding lots of data inside a smart contract?

texts:
I have been developing a smart contract (ERC-721 compliant) which needs to be populated with lots of various pieces of data.

Approximately 300 ERC721 tokens need to be minted inside the contract at the point of deployment.

I have a json data structure which details all the required initial tokens and their data attributes to be minted inside the contract.

I have currently created a new migrations script e.g. 4_populated_tokens.js which truffle run when deploying to each network.

This always succeeds locally with ganache but when running against any testnet I this always seems to eventually fail, occasionally with 80% or more of the content, usually for the following reason:

Error encountered, bailing. Network state unknown. Review successful transactions manually.

I have tried adjusting the migration with some success by doing the following:

Only minting a single token at once i.e. serially instead of firing lots of inserts at once
Increasing the gas per transaction

There has been some success with this.

My question :

Is it correct to use truffle migrate to populate such large amounts of data, if not what is the preferred solution?
Do other people also have this problem using truffle to run in large amounts of data as part of a migration?

All help appreciated, thanks.


texts: Is the May 2017 contract creation attack still possible?

texts:
In May 2017, an "attacker" created a contract that attempts to create many other contracts(using many JUMPDEST operations in the creation bytecode) until it runs out of gas.
I see the gas improvemnts of EIP-150, but don't see where this attack would be mitigated today.
Is this "attack" still possible?
One of the txs
Reddit thread


texts: Parity getting started tutorial not working

texts:
I'm trying to do the getting started tutorial from Parity but it isn't working. When running the following command:

parity --chain=kovan

i get the following error message

Cannot read manifest file at: "/Users/benjamin/Library/Application Support/io.parity.ethereum/dapps/mydappTest/manifest.json". Error: "Error { repr: Os { code: 2, message: \"No such file or directory\" } }"

I'm using the standard manifest.json file, and when i go to localhost i can see the name of the dapp but when i click on it i get a 404 page not found.

Somebody knows how to fix this?

thanks in advance


texts: Parity account in OS windows 10 dissapeared

texts:
would my lost wallet parity key still be in the location: : $home\AppData\Roaming\Parity\Ethereum\keys\ethereum    even after I have uninstallled and then reinstalled Parity? If so will this allow me restore my lost Parity wallet?  thanx a million for your help!

my twitter is @sduncan621. and I have messenger so my Facebook is https://www.facebook.com/JuliusStevenDuncan …  .need help folks! I still  have my 12 word phrase and parity  password but parity wallet dissapeared and using the "restore procedure" and my 12 word restore phrase only flashes the correct  previous parity wallet address but not the account itself with token content...yesterday I even reinstalled parity using win-installer exe. from parity.io and resynched but still no wallet..can someone please help me? thanx a million!


texts: Creating an ERC20 Token on Rinkeby - Can't get the right supply

texts:
I'm creating an ERC20 token on Remix and using EIP20.sol from Consensys.
I'm using this video tutorial as a guide - https://www.youtube.com/watch?v=d5EipPVafsA

It's been helpful, however I have one issue.
When it comes to deploy I get far less tokens than I intended the total supply to be.

I want 8,000,000 tokens with a 18 decimal places.

I used in: 8000000,"TOKENNAME",18,"TOKENTICKER"

and the total supply is... 0.000000000008

Why is this and how should I change the numbers to make it 8 million supply with 18 decimals?


texts: How do you test your contracts, and how long do you spend testing?

texts:
I want to improve how I test to increase my effectiveness and efficiency, so would like to hear from others.
How do you test your smart contracts i.e. do you have a particular methodology for what tests you actually create?
The way I've been doing it: I've been going through each function, testing each one's require() statements and access management (onlyOwner), then generally try thinking of anything else that could be tested in Truffle as I go over each function.
Also, how long do you tend to spend on testing? I've found testing to be a big timesink and end up spending much more time compared to writing the contracts, so concerned I might be overdoing it.


texts: Building a deterministic wallet without random seed phrase instead multiple static inputs

texts:
If I want to be able to create a private key given inputs x,y,z and these inputs are constant, if I add enough entropy as a salt would it be secure to create a key this way (in terms of brute force attacks or reverse engineering) and be able to re constitute it given the same inputs where the salt also never changes, pseudo code
where x,y,z are

val salt = "4D6250655368566D597133743677397A"
val output = SHA256(salt + x + y + z)

and recursively hash the output 100,000x sort of like using 3 passwords


texts: Is there any way to fund a new account privately via a randomising pool?

texts:
It isn't currently possible to create a new HD wallet account and privately fund it, is it?

I'm aware of this thread, but I'm not asking about SNARKs. Instead, I'm curious if there's any way to send funds to a smart contract or service which subsequently funds the new account anonymously? Not sure if this would require some sort of randomness beacon similar to Dfinity's.

Centralised exchanges make this possible as a non-intended byproduct, but there's an overhead cost in signing up and paying for withdrawal fees.


texts: What do availableVolume and availableVolumeBase mean on etherdelta.com?

texts:
Etherdelta API allows to see existing orders.
There are some fields in the order the meaning of which I don't understand. Could anyone explain me such fields as availableVolume, ethAvailableVolume, availableVolumeBase, ethAvailableVolumeBase, amountFilled? Do these fields changed in time? If yes, how does it happend?

Etherdelta API doc: https://github.com/etherdelta/etherdelta.github.io/blob/master/docs/API.md

{
  "id": "4e17ce3e16b0ab215c8224245c91f5bd6fbcb8e99a5612dc787f2d200a6673d4_sell",
  "amount": "-8.1803308489365e+22",
  "price": "0.000007697",
  "tokenGet": "0x0000000000000000000000000000000000000000",
  "amountGet": "629640065442642300",
  "tokenGive": "0xd96b9fd7586d9ea24c950d24399be4fb65372fdd",
  "amountGive": "8.1803308489365e+22",
  "expires": "4820340",
  "nonce": "33307137838216790",
  "v": 28,
  "r": "0xe0e1e1451ca72d5d8c948edba25f931c99570bac7c0a111b595dd480c69690c1",
  "s": "0x56ce5c279b658e738467c83b33b841b6738ff68c6282de3c1850c2f87db2ef38",
  "user": "0x38FcE8aa65Ea74219BD2c07A882570B96DfE6a40",
  "updated": "2017-12-29T21:10:31.441Z",
  "availableVolume": "8.180330848936498635832142393140184487462648e+22",
  "ethAvailableVolume": "81803.30848936498",
  "availableVolumeBase": "629640065442642300",
  "ethAvailableVolumeBase": "0.6296400654426423",
  "amountFilled": null
}


texts: Downgrade Geth from 1.6 to 1.59 to have solc integrated in Geth

texts: I have this project on ropsten testnt that don't want to keep developing but keep on running. Since they took solc out of Geth on v1.6, I get the error method eth_compilesolidity does not exist. Is there an easy way around it? If I downgrade Geth to v1.5 would my project work without the need to change anything and will I need to delete the testnet blockchain I already have? Also what is the correct way to downgrade geth to v1.5 on linux?


texts:
I noticed that Parity disabled the option to create a vanilla address. The only option available in my account is to create vaults, new accounts or multisig-wallets.

After seing Parity's art of contracting not being bullet proof I prefer to still use simple addresses.

Anybody know how I can do this?


texts: Whats the best way to find the execution cost of a function

texts:
I am interested to analyze the execution cost of the function by considering the best practice to adopt, because of that I used bytes32 rather than String which decrease the execution cost of the function from infinite to finite.

I am eager to know whats the best way to find the accurate gas execution cost. I compile the same code 2-3 times in remix and sometimes it gives me the different execution gas cost. Like for below function sometimes it gives me

    Execution cost: 624gas

and sometimes

    Execution cost: 454 gas.

The function is below which simply return the length of an array.

    function totalLoans() public view returns (uint){
    return(allLoansData.length);
    }

1) Does the difficulty parameter also impact the execution gas cost?
2) Is there any way that we find the ideal gas cost?


texts: Difference between a Protocol Token and a Dapp Token?

texts:
I've seen tokens referred to as "protocol tokens" and "dapp tokens", as far as I can tell they are on in the same. Maybe a protocol token is simply a dapp token with a published ABI?

There's even this page that claims to differentiate them in the title, but isn't clear to me after reading it a few times.

(bonus question)
I've seen a few people refer to "overlay networks". Is a side-chain the same as an overlay network? As far as I can tell, no one has created a blockchain overlay network, and I'm not even sure what one would look like.

Wikipedia defines an overlay network as:
"a computer network that is built on top of another network. Nodes in the overlay network can be thought of as being connected by virtual or logical links, each of which corresponds to a path, perhaps through many physical links, in the underlying network."

A don't see a sidechain satisfying this. A sidechain isn't on top of another blockchain, it has it's own nodes.


texts: Declaring variables inside functions in solidity not working

texts:
I have the following code in solidity:

pragma solidity ^0.4.18;

contract testcontract {
    function testme () returns (string){
        string mystring = "foo2";
        return "foo";
    }
}

And I get the following TypeError:

browser/dummy2.sol:5:9: TypeError: Type literal_string "foo2" is not implicitly convertible to expected type string storage pointer.
    string mystring = "foo2";
    ^----------------------^

If I just do string mystring;, I don't get the error, and as the TypeError describes, there is an issue with the assigning of the "foo2" value to the string mystring, but I can't figure out why this is happening. Does this mean that variables can't be declared and initiated inside functions? I don't have the issue when it's outside of the function and within the contract.


texts:
Can we say following proposition is correct?

"every Smart Contract is a Dapp, but a Dapp may not be a Smart Contract."


texts: Ether balance on Metamask doesn't change after selling tokens

texts:
I create a smart contract successfully using Remix IDE , Metamask and Ropsten for testing.

I want to sell some tokens using Sell function, so I specified the value "20" for Sell function ,my initial balance was 600 after that I checked the balanceOf , the new value is 580,but my Ether Balance on Metamask didn't change.
My sell function code is  :

 function sell(uint amount)public returns (uint revenue){
        require(balanceOf[msg.sender] >= amount);
        balanceOf[this] += amount;
        balanceOf[msg.sender] -= amount;
        revenue = amount / sellPrice;
        msg.sender.transfer(revenue);
        emit Transfer(msg.sender, this, amount);
        result = amount;
        return revenue;
    }


texts: How to use Chainlink with Truffle/Ganache?

texts:
How to use Chainlink with Truffle/Ganache without unboxing a new app? (I have an app already, I don't want to unbox a new one)
I'm trying to get the Chainlink price feeds working in local development using Ganache / Truffle.
How is something like accomplished?


texts: Is a 'sign on the dotted line' attack (confirm incorrect address) possible on the Ledger Nano S?

texts:
I'll describe a physical case of what I'm asking about -- we might call it the 'Just sign on the dotted line' attack. I'm asking if it's technically possible since one is required to open the hardware to input signals from the MEW website.

Blockchain technology works by signing transactions with our private key. This key is what our Ledger backup seed restores to the device. Once we sign the transaction, it's sent to and confirmed by the network.

Suppose someone is handed a check to sign with someone's name on it. The see the correct name on the check so they sign it. However, that correct name was actually a sticker and the criminal peels it off, revealing a different name on the check that now has the necessary signature on it. In this way one is tricked into signing a transaction with undesired information that appeared correct.

I am asking if the same thing can be done via the signals sent from the MEW site to the Ledger, i.e. such that the address displayed by the Ledger is in fact not the address involved in the transaction being signed.

If it is not possible, why not? If possible, can you cite the pertinent code demonstrating the impossibility?


texts: Error syncing new node on private network:no peers available or all tried for download

texts:
I am currently trying to run a test node, which recently failed. I have deleted the directory and copied another node's AND tried a reset of the directory but at some point it freezes with this log and doesn't sync anything.
WARN [09-28|13:44:35.921] Header broke chain ancestry              peer=b0ac3a6413bad392 number=160226 hash="9b9eef…43ffb3"
INFO [09-28|13:44:35.931] Downloader queue stats                   receiptTasks=0 blockTasks=0 itemSize=0.00B throttle=8192
WARN [09-28|13:44:35.931] Synchronisation failed, dropping peer    peer=b0ac3a6413bad392 err="retrieved hash chain is invalid: no peers available or all tried for download"

I have tried to recompile Geth but it didn't solve my problem. For reference here is my command:
./build/bin/geth --datadir chain/ --networkid 15 --http.addr 0.0.0.0 --http.api "eth, net, web3" --http --http.port 6786 --miner.gasprice 10000000000 --syncmode full --bootnodes enode://<long number>@127.0.0.1:35665 --gcmode archive


texts:
I've developed a very simple smart contract and I'm trying to invoke a function using eth_call. The contract is deployed on the revived Ropsten testnet.

If I invoke the function getSTR() sending the rpc to the local instance of geth I'm able to get back the correct response. The python code is like this:

contractAddress = "0xd02e5779398cd9b05ea7fcd7ed8868524df06313"
urlGeth_rpc = "http://localhost:MYPORT/json_rpc"
functionSignature = "getSTR()"
function_encoded = keccak256_Geth(functionSignature)[:10]

rpc_getSTR = {
    "jsonrpc": "2.0",
    "method": "eth_call",
    "params": [
        {
            "to": contractAddress,
            "data": function_encoded,
        },
        "latest"
    ],
    "id": "1"
}
response = requests.post(urlGeth_rpc, data=json.dumps(rpc_getSTR), headers=headers)
r = json.loads(json.dumps(response.json()))

When I try to invoke the same function using a remote INFURA node I use this code (practically the same with a different rpc access point)

contractAddress = "0xd02e5779398cd9b05ea7fcd7ed8868524df06313"
urlRopsten_rpc = "https://ropsten.infura.io/MYTOKEN"
functionSignature = "getSTR()"
function_encoded = keccak256_Geth(functionSignature)[:10]

rpc_getSTR = {
    "jsonrpc": "2.0",
    "method": "eth_call",
    "params": [
        {
            "to": contractAddress,
            "data": function_encoded,
        },
        "latest"
    ],
    "id": "1"
}
response = requests.post(urlRopsten_rpc, data=json.dumps(rpc_getSTR), headers=headers)
r = json.loads(json.dumps(response.json()))

With INFURA the response is <Response [400]>, so something is clearly wrong. I am not able to see the error, maybe is something related to INFURA for which I have to formulate differently the rpc request.
I am instead able to use INFURA to call the eth_blockNumber rpc method and get the correct result back.

Thanks for the support

---- UPDATE
As requested by in the comment, here is my python code for calling the keccak-256 hash function of the local geth client (which is implemented with the web3_sha3 method)

def keccak256_Geth(string):
    string = "0x" + binascii.hexlify(string)
    rpc_keccak256 = {
        "jsonrpc": "2.0",
        "method": "web3_sha3",
        "params":  [string],
        "id":  "64"
    }

    r = requests.post(rpc_url, data=json.dumps(rpc_keccak256), headers=headers)
    r = json.loads(json.dumps(r.json()))


texts: What happens if I run Geth --rpc a second time

texts:
I was running Geth --rpc overnight but I think that my computer has restarted following a Windows update.

without thinking I just ran again Geth --rpc a second time, but I am not sure that was the right thing to do. maybe I should have cancelled the action of the first run of Geth.

Does anybody know what happens when you run Geth --rpc twice?

thanks for teaching me!
Hsoda


texts: Is there any existing TCP load balancer product that is enode aware?


texts: Pairing multiple nodes - script for reading enodes?

texts:
I want to pair 20 nodes. But going through each node and its enode information and copying it into my staticNodes.json seems like a lot of work. Is there any way how I can automate this prcocess? Or at least write the enode information to a text file, so that i can collect all the textfiles later and just parse them?

Thank you all!


texts: Solidity function to return a data struct

texts:
When trying to return a struct with Solidity like this:

function getAssetStructById(uint256 assetId) constant returns (asst _asset) {
    return (assetsById[assetId]);
}

This is the compilation error it throws:

Error: Internal type is not allowed for public or external functions.

So, how can I get the data of the struct returned? I tried returning every field of the struct but this is not working anymore once you reach 9 data fields, getting the error:

'Stack too deep' compiler error.

Ref.: Is there any limitation for the number of the return values from Solidity functions?

This is the struct I would like the function to return:

struct asst {
    uint256 assetId;
    uint256 next;
    uint256 prev;
    uint256 timestampCreation;
    address assetOwner;
    address issuer;
    string content;
    uint256 sellPrice;
    assetState state;
}

Any idea how to do that on Solidity? Thx!

Ref.: Return a struct from a Solidity Contract


texts: Is the genesis block the same as the first block?

texts:
I am playing around with a private blockchain, and I realize that I don't understand how the "genesis block" is different fromthe first block.  I assume it has to get mined like any other, yes?  Otherwise, why have a "gasLimit" in the genesis section of a chain spec?

Is it simply the first transaction I manually engage in?  Like, if I fire up a few nodes and transfer some testETH between them, is that exchange the "genesis block"?

I have to ask this because the block does not seem to automatically happen if there are no transactions.  I do have a miner on the network from the moment I start Parity but until I transact something, no blocks are visible in the explorer I am running.


texts: What happens if you transfer ether and no miner is running?

texts: What happen if I transfer ether from account a to account b on a private chain with just one node and that node is not mining?


texts: Why does the mainnet download take a long time? How can I improve this?

texts:
We have been working on integrating a ETH node to our e-wallet to enable ether transactions. We completely build the platform by connecting to a private Ethereum network.
Now everything is ready to go on to the mainnet. I started the download (fast download) last Thursday, any by today it had only downloaded about 108 GB. And the download speed has drastically decreased in the last few days. At this rate I feel like it will take forever to sync the blockchain. After searching for a while I found a article which said to use a VPN to change the location. I tried this out but the download speed didn't improve much.

I'm I doing anything wrong? Are there any other recommendations to improve the download speed?


texts: After EIP 198 introduction, how much gas is required for RSA signature verification in solidity?

texts:
Thanks to the introduction of EIP 198, RSA signature verification is now feasible in Ethereum.

How much gas is required for such a verification?


texts: How to fix an error with Vyper: invalid syntax (, line 168)

texts:
I'm trying to figure out why the following line is giving the error at https://vyper.online/: invalid syntax (, line 168).

Line 168 is self.collator_pool.empty_slots_stack_top] = index).

@internal
def stack_push(index: int128):
    (self.collator_pool.empty_slots_stack[
        self.collator_pool.empty_slots_stack_top] = index)
    self.collator_pool.empty_slots_stack_top += 1

There's also this which is the other relevant part of the file:

collator_pool: public({
    # array of active collator addresses
    collator_pool_arr: address[int128],
    # size of the collator pool
    collator_pool_len: int128,
    # Stack of empty collator slot indices caused by the function
    # degister_collator().
    empty_slots_stack: int128[int128],
    # The top index of the stack in empty_slots_stack.
    empty_slots_stack_top: int128,
})

I don't think you'll need it but the whole file is available at https://github.com/Drops-of-Diamond/sharding/blob/develop/smc/sharding_manager_contract.v.py.


texts: Get public key from signature in a smart contract (note, public key, not address)

texts:
Are there any libraries to get a public key from a signature in a smart contract? The ecrecover method returns an address, not a public key, and to do computations that need to derive a public key from a signature, where the public key is not known and not passed into the contract by other means, while the signature is known, it would be good to have a library that gets the public key from a signature.

Partial libraries would also be helpful here.


texts: Does a selfdestruct affect child contracts?

texts:
Say, I create a smart contract A and this contract creates another smart contract B. If I call selfdestruct on A, will this affect in any way contract B? Or can I still call functions on B after A is killed?

I found this example on Etherscan:

Original contract A: https://etherscan.io/address/0x14fea711dca8fcea6be47e14ea1406384f18c7cc
Contract B created by A: https://etherscan.io/address/0x02820e4bee488c40f7455fdca53125565148708f

Contract A is selfdestructed and therefore has no code anymore. B also has empty code, but it does not have the red SelfDestruct label on Etherscan. So did the SelfDestruct of A lead to a deletion of B's code or is this just coincidence and this contract B never had any code associated with it at all?


texts: Accessing struct fields from assembly block

texts:
Say we have the following structure:

struct MyStruct {
  uint256 x;
  uint256 y;
}

and that it is passed as an argument to some function. Inside that function, we have assembly block from where we try to access x and y:

function myFunc(MyStruct memory data) internal view returns (bool) {
  // (...)
  assembly {
    let args := mload(0x40);
    mstore(args, data.x);
    mstore(args, data.y);
    // (...)
  }
  // (...)

}

And the compilation fails with:

Error: CompileError: ParsedContract.sol:404:28: ParserError: Expected ')' but got '.'
            mstore(args, data.x)

Is it not allowed? Is there any workaround? I want to avoid creating temporary uint256 fields to avoid additional gas expenses.


texts:
I've bought some ETH on bity.com which they delivered in a contract with the address 0x834145878D5e82D21CFaa27BC71ddD60194E8198.

I now want to transfer the ETH of this contract to my personal wallet, but I can't seem to find out how to manage this. I've downloaded the Ethereum Wallet and managed to connect to my contract, so it shows up in contracts tab and I've transferred 2 ETH into my personal wallet for enough gas.

Can anybody help me to get my ETH out of that contract please?


texts: How well do Proof of Authority (PoA) implementations of Geth (Clique) and Parity (Aura) scale?

texts: Has anybody tried to run PoA networks with 100 or more validators? Given a fixed block size, how did the number of validators effect transaction throughput and latency?


texts:
I am using web3 5.14.0 and Infura
I am trying to get all transfer event for link chain token like the following:
from web3 import Web3

ABI_REQUEST_ENDPOINT = 'https://api.etherscan.io/api?module=contract&action=getabi&address='
def etherscan_fetch_abi(addr):
    response = requests.get('%s%s'%(ABI_REQUEST_ENDPOINT, addr))
    response_json = response.json()
    abi = json.loads(response_json['result'])
    return abi

web3 = Web3(Web3.HTTPProvider(url))
address = web3.toChecksumAddress('0x514910771AF9Ca656af840dff83E8264EcF986CA')
abi = etherscan_fetch_abi(address)
contract = web3.eth.contract(address=address, abi=abi)
latest = web3.eth.blockNumber
transferEvents = contract.events.Transfer.createFilter(fromBlock=latest-100, toBlock=latest)
transferEvents.get_all_entries()

This always return an empty list. Any idea how I could get all events please? I am trying to get biggest holders of some coins.
Thanks!


texts: What's the difference in the ways of calling a contract function?

texts:
After I get an instance of a contract, there are 3 ways to call the contract function below:

1.testInstance.testfunc({from:eth.accounts[0]})
2.testInstance.testfunc.sendTransaction({from:eth.accounts[0]})
3.testInstance.testfunc.call({from:eth.accounts[0]})

What's the difference from each other?


texts: ERC20 token with "Gas required exceeds limit: 3000000"

texts:
I have an ERC20 token contract with one more function. But when I run the function, I got

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

Function:

function checkValue() public payable returns (bool) {
      require(msg.value == 10000000000000000);
      return true;
}


texts: Generating genesis.conf for Clique PoA private network via command line

texts:
I'm trying to generate a Clique POA genesis file that specifies the original sealers using automation.  However, puppeth only supports user input at the moment.  There's no support for command line options such as.

puppeth genesis --protocol clique --chainId 123 --period 2 --sealers 0x123...,0x234...,0x345...  --alloc 0x123...,0x234...,0x345...

Are there any alternative tools for generating the extraData value that's needed in the genesis.conf?


texts: Storing data on IPFS using KMS and ethereum

texts:
I am trying to build a blockchain on ethereum but keeping the data related to blocks in some distributed file storage system like IPFS or Storj and storing the hash of data in blocks. But we need our data to be private / shared, so to achieve that we are thinking of using some Key Management Service like NuCypher KMS. But we will have smart contracts on ethereum which can access the data and perform some operations.
My question is, is this the correct approach or is this even possible?


texts:
Recently i'm trying to comunicate to a private Ethereum blockchain via RPC/IPC to create a Transaction but what i'm seeing is that i cannot do it via RPC because:
- i Always need to unlock my account before and i cannot do it via RPC :

curl 127.0.0.1:8545  -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"personal_unlockAccount","params": ["0xWALLET" ,"",null],"id":1}'
{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"The method personal_unlockAccount does not exist/is not available"}}

i see that there is an alternative via IPC so i tried:

echo '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}' | nc -U /path/datadir/geth.ipc 3ef {"jsonrpc":"2.0","id":1,"result":["0xWALLET1","0xWALLET2"]}

Ok so IPC works fine now i try to make a TX:

echo '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{ from: "0xWALLET1", to: "0xWALLET2", value: 1000000000000000000, data: "0x10", gas: 1000000}],"id":1}' | nc -U /path/datadir/geth.ipc
{"jsonrpc":"2.0","error":{"code":-32600,"message":"invalid character 'f' looking for beginning of object key string"}}

I tried to mess around with params and follow the JSON format
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction

But still i can't figure out how to make this transaction correctly.


texts: Cannot send ETH to contract using solc 0.8.4 using truffle console (revert)

texts:
I spend like 6 to 8 hours on this issue, finally asking here on the following problem.
Goal
I want to sent ETH from one of the default Ganache addresses to the deployed contract SportBet.
Versions
Truffle v5.3.4 (core: 5.3.4)
Solidity - 0.8.4 (solc-js)
Node v15.9.0
Web3.js v1.3.5
Ganache v2.5.4

Using
macOS 11.2.3
vsCode 1.56.1

Contract
contract SportBet {

string public name = "SportBet";
address public owner;

event Received(address, uint256);

receive() external payable {
    emit Received(msg.sender, msg.value);
}

fallback() external payable {}
}

Then on truffle console declaring
sportBet = await SportBet.deployed()

Now sending ETH using web3
web3.eth.sendTransaction({to:sportBet.address, from:accounts[0], value: web3.utils.toWei('1'), gas: 100000})

Always ending with
Uncaught Error: Returned error: VM Exception while processing transaction: revert

Get gas price
web3.eth.getGasPrice()

Result
'20000000000'

Update
When I run on truffle console
migrate --reset

I get
2_deploy_contracts.js

=====================
Replacing 'SportBet'
Error:  *** Deployment Failed ***
"SportBet" -- Provided address g is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted..

Thanks in advance!


texts:
I have a simple script:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    conn, err := ethclient.Dial("https://mainnet.infura.io")
    if err != nil {
        log.Fatalf("Unable to Connect to Ethereum network: %v", err)
    }

NewAENToken(common.HexToAddress("0x0BEf619cF38cF0c22967289b8419720fBd1Db9f7"),conn)

    ctx := context.Background()
    tx, pending, _ := conn.TransactionByHash(ctx, common.HexToHash("0x30999361906753dbf60f39b32d3c8fadeb07d2c0f1188a32ba1849daac0385a8"))
    if !pending {
        fmt.Println(tx)
    }
}

When I run the command as such:

go run main.go

It runs, except without a clean layout. but when I execute the following:

go tool compile main.go

I get the following Error:

main.go:8:5: can't find import: "github.com/ethereum/go-ethereum/common"

Things Tried are replacing the

"github.com/ethereum/go-ethereum/common"

with

  "github.com/ethereum/go-ethereum/tree/master/common"

which also failed.


texts:
Let's say I have multiple smart contracts that inherit from one base contract:

Contract Base{
   function doSomething(){};
}

Contract A is Base{
}

Contract B is Base{
}

What I want to do is  call doSomething without knowing which particular contract I'm dealing with, just having the address.

instance = web3.eth.contract(BaseABI).at(givenAddress);
instance.doSomething();

I believe that is polymorphism (correct me if I'm wrong). So, is that possible ? Just to be clear, the givenAddress can be the address of a contract A, B or any other contract that's been deployed and that inherits from Base. I want to be able to retrieve an instance of that contract without giving the specific ABI, just the Base one, since all I want to do in this case is calling the the Base doSomething.

Thank you for your advice.

PS: I did try that (with testrpc) which gives me an invalid op code.


texts: TypeError: Member "equal" not found or not visible after argument-dependent lookup in type(library Assert)

texts:
Truffle v5.0.8 (core: 5.0.8)
Solidity v0.5.0 (solc-js)
Node v10.13.0
Web3.js v1.0.0-beta.37

Assert.equal worked in Truffle 4.x.

pragma solidity >=0.4.21 <0.6.0;

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

uint public initialBalance = 10 ether;
Funding funding;

function () external payable {}

function beforeEach() public {
    funding = new Funding();
}

function testSettingAnOwnerDuringCreation() public {
    Assert.equal(funding.owner(), this, "Owner should be the same as deployer.");
}


texts:
I have activated watching events with Contract.events.events_name(filter, lastBlock), now I need to stop watching this event. I can't find the command in web3 docs. I'm using Web3 version: 1.2.1.
How can I stop watching events?


texts: Uniswap WETH_WBTC price is orders of magnitude off when using constant product market maker formula

texts:
I am trying to calculate the value of an exchange on Uniswap using Web3js and methods from the Uniswap smart contract.
This is the Uniswap contract address for the WETH (Wrapped Ether) : WBTC (Wrapped Bitcoin) pair
0xBb2b8038a1640196FbE3e38816F3e67Cba72D940
Using that contract address and the contract ABI I construct a js-object for the contract like this: const pairContract = new web3.eth.Contract(pair.abi, pair.address);
This works fine and I am able to read the contract methods as well as call methods on the contract (I'm only using read-only methods - I don't need to sign any transactions). So I am able to call the getReserves method like this
const reserves = await pairContract.methods.getReserves().call();

And here is the response (at this _blockTimestampLast)
{
  '0': '296352466321',
  '1': '37712426843492788602200',
  '2': '1621116220',
  _reserve0: '296352466321',
  _reserve1: '37712426843492788602200',
  _blockTimestampLast: '1621116220'
}

_reserve0 are the WBTC reserves and _reserve1 are the WETH reserves
Now here in this implementation is where somehow things are going wrong...
const BigNumber = require('bignumber.js');

const estimateTrade = (
  baseTokenReserves,
  quoteTokenReserves,
  numberOfBaseTokenTradedIn,
  feePercent)=> {

        // x * y = k

        const feeMultiplier = BigNumber(1).minus(feePercent.dividedBy(100));

        const k = baseTokenReserves.times(quoteTokenReserves);

        const baseTokenNewTotal = baseTokenReserves.plus(numberOfBaseTokenTradedIn.times(feeMultiplier));

        const quoteTokenNewTotal = k.dividedBy(baseTokenNewTotal);

        const quoteTokenReceived = quoteTokenReserves.minus(quoteTokenNewTotal);

        return quoteTokenReceived;

}

Calling my estimatedTrade method with these arguments...
const baseTokenReserves = BigNumber(_reserve0);
const quoteTokenReserves = BigNumber(_reserve1);
const numberOfBaseTokenTradedIn = BigNumber(1);
const feePercent = BigNumber(0.03);

const tokensReceived = estimateTrade(baseTokensReserves, quoteTokenReserves, numberOfBaseTokenTradedIn , feePercent)

console.log(`tokensReceived = ${tokensReceived.toFixed()}`) //tokensReceived = 127151098781.56376683928985070517

This obviously is way off. When I check on Uniswap to see how many WETH I would get for 1 WBTC I see roughly 12.677. I've checked for hours and every time my answer is off by 10 decimal places (10,000,000,000 times). This method works well for every other pair I've tried (WETH_SUSHI, WETH_UNI, etc.) except for WETH_WBTC. Can anyone see what the issue is? Thank you!


texts: Geth. How to read the value of a public variable?

texts:
How do I read the value of a public property ("count") in my contract using Geth?

Solidity:

contract Core {

    address public owner;
    uint public count;
    uint public tax;
    event NewMarketLog(address market, address owner);
    mapping (address=>address) public MarketplaceList;

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

    function CreateMarketplace (string _name, string _desc, string _telegram)  returns (address) {
        count++;
        address adr=new Marketplace(_name,_desc,_telegram,msg.sender);
        NewMarketLog(adr, msg.sender);
    return  MarketplaceList[msg.sender]=  adr;
    }
}


texts: Transaction exited with an error (status 0) after consuming all gas

texts:
I developed some smart contracts to be deployed to a private PoA (Proof of Authority) blockchain. I spun up a private blockchain via truffle develop and got the following receipt:

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 0x6691b7

1_initial_migration.js
======================

   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x3d13fe576e83c051ab7814c9c4b221310e55fe49ab4b75e6b0af8905856c9fbf
   > Blocks: 0            Seconds: 0
   > contract address:    0xf00B83D756789D8Ad24a0DceE356B26973279390
   > block number:        1
   > block timestamp:     1559731765
   > account:             0xCe6cd87Dea71E58A020A076dD0a820cC6d3879fB
   > balance:             99.999477214
   > gas used:            261393
   > gas price:           2 gwei
   > value sent:          0 ETH
   > total cost:          0.000522786 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:         0.000522786 ETH

Summary
=======
> Total deployments:   1
> Final cost:          0.000522786 ETH

The Azure solution I am currently using for the private blockchain is the Ethereum on Azure template. This template is set up that nobody has any Ether in their accounts. I configured Truffle as follows:

cloudDev: {
  network_id: "*",
  provider: () =>
    new HDWalletProvider(
      mnemonic,
      "<azure_url>:<azure_port>"
    ),
  gasPrice: 0
}

However, when I execute the deployment to this blockchain, I get the following receipt:

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Starting migrations...
======================
> Network name:    'cloudDev'
> Network id:      5230
> Block gas limit: 0x2faf080

1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x85b99478d90fa12b52b26307ee0fb1d688537a55e4346fdc2fe8a76696f6e2b1
   > Blocks: 0            Seconds: 0
   > contract address:    0x3BE3DeB6910E5493aEbA67141F7FFb560eC80955
   > block number:        24773
   > block timestamp:     1559732366
   > account:             0x4e33D8a245Ad3C28634726607a5F9bb8d7BB295f
   > balance:             0
   > gas used:            261393
   > gas price:           0 gwei
   > value sent:          0 ETH
   > total cost:          0 ETH

   ⠧ Saving migration to chain.Error: Error: StatusError: Transaction: 0xcff0b628f0ae784a33c3fdf4b743c8414cd8031ddd34c6a7efda8bfd9d6e2fdf exited with an error (status 0) after consuming all gas.
     Please check that the transaction:
     - satisfies all conditions set by Solidity `assert` statements.
     - has enough gas to execute the full transaction.
     - does not trigger an invalid opcode by other means (ex: accessing an array out of bounds).
    at Object.run (/home/DevNebulae/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/packages/truffle-migrate/index.js:92:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.0.20 (core: 5.0.20)
Node v10.15.3

What may be the cause of this issue and how can I fix this?


texts:
Fixed question:

I have a mapping:

mapping (bytes32 => mapping (bytes32 => bytes32[])) items;

With some elements in it:

items["fruits"]["apples"].push("first apple");
items["fruits"]["apples"].push("second apple");
items["fruits"]["apples"].push("third apple");
items["fruits"]["plums"].push("first plum");
items["vegetables"]["carrots"].push("first carrot");

I want to delete all fruits. The code below does not work:

delete items["fruits"]

The error I get is:

Error: Unary operator delete cannot be applied to type mapping(bytes32 => bytes32)

Original question:

I have a mapping:

mapping (bytes32 => mapping (bytes32 => bytes32)) items;

With some elements in it:

items["fruits"]["apples"] = "first apple";
items["fruits"]["apples"] = "second apple";
items["fruits"]["apples"] = "third apple";
items["fruits"]["plums"] = "first plum";
items["vegetables"]["carrot"] = "first carrot";

I want to delete all fruits. The code below does not work:

delete items["fruits"]

The error I get is:

Error: Unary operator delete cannot be applied to type mapping(bytes32 => bytes32)


texts: What's the purpose of the following code in the program?

texts:
I was following a tutorial on building a simple Solidity program for Ethereum transactions between a smart contract and account. However, I didn't understand the following code:-
balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;

Here's the full code:-
pragma solidity >=0.5.11 <0.7.0;
contract MappingsStructExample {

     struct Payment {
         uint amount;
         uint timestamps;
     }

     struct Balance {
         uint totalBalance;
         uint numPayments;
         mapping (uint => Payment) payments;
     }

     mapping(address => Balance)public balanceReceived;

     function getBalance() public view returns(uint) {
        return address(this).balance;
     }

     function sendMoney() public payable {
         balanceReceived[msg.sender].totalBalance += msg.value;

         Payment memory payment = Payment(msg.value, now);//this stores

         balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;

         balanceReceived[msg.sender].numPayments++;
     }

     function withdrawMoney(address payable _to, uint _amount) public {
         require(_amount <= balanceReceived[msg.sender].totalBalance, "not enough funds");
         balanceReceived[msg.sender].totalBalance -= _amount;
         _to.transfer(_amount);
        }

     function withdrawAllMoney(address payable _to) public {
        uint balanceToSend = balanceReceived[msg.sender].totalBalance;
        balanceReceived[msg.sender].totalBalance = 0;
        _to.transfer(balanceToSend);
     }

}

If I were to remove the code, the program won't have an impact. The program will still keep track of the payments made from the account as well as keep track of the amount being sent. Therefore, is it important to keep the code?


texts: How to transfer Bep20 token using web3.js

texts:
I want to transfer a Bep20 custom token from a wallet to another using web3.js in Binance Smart Chain.
I can transfer BNB using this code:
// Create transaction
const myTransfer = async () => {
    console.log(
        `Attempting to make transaction from ${addressFrom} to ${addressTo}`
    );

    const createTransaction = await web3.eth.accounts.signTransaction(
        {
            from: addressFrom,
            to: addressTo,
            value: 'value',
            gas: '30000',
        },
        privateKey
    );

    // Deploy transaction
    const createReceipt = await web3.eth.sendSignedTransaction(
        createTransaction.rawTransaction
    );
    console.log(
        `Transaction successful with hash: ${createReceipt.transactionHash}`
    );
};

How can I send a token from the same wallet?


texts:
function () public payable {
        require(currentStage == Stages.icoStart);
        require(msg.value > 0);
        require(remainingTokens > 0);

  Blockquote fallback typos error

        balances[msg.sender] = balances[msg.sender].add(tokens);
        emit Transfer(address(this), msg.sender, tokens);
        totalSupply_ = totalSupply_.add(tokens);
        owner.transfer(weiAmount);// Send money to owner
    }

type error  i got  . kindly help this


texts:
The easiest standard for DELEGATECALL upgrade mechanism is
https://gist.github.com/Arachnid/4ca9da48d51e23e5cfe0f0e14dd6318f

I don't get completely how it works, especially these aspects:

The "eternal" storage which will survive upgrades should go to the Dispatcher, not the implementing/upgradeable contract, is that correct?
Should the upgradeable contract have it's own storage at all or should it be without storage/state like libraries?
Why can the delegated contract not change it's storage layout? Or is this true for the Dispatcher only?
There are other solutions like delegating to a dedicated eternal storage contract (https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88) what are the advantages/disadvantages of these solutions


texts: Storing Struct inside an array. Help Please

texts:
I am designing an EHR System that will store patient records (with a unique ID) and separated by the date and Hospital entered. I am able to enter data in Hospital struct mapping to the Record struct, and everything is working well.
contract PatCord {
string  name;
uint  age;
string  bGroup;
bytes32  id;
mapping(address => string) hosp;
address recc;

constructor(string _name, uint _age, string _bGroup, bytes32 _id) public {
    name = _name;
    age = _age;
    bGroup = _bGroup;
    id = _id;
    hosp[msg.sender]= "ABC Hospital";
}

struct Record {
    string disease;
    string value;
}

struct Hospital {
    string name;
    Record[] records;
}

mapping(uint256 => Hospital) hos;
Hospital[] hospital;

function addRecord(uint _id, string _disease, string _value) public {
    hos[_id].records.push(Record(_disease, _value));
}

function returnRecord(uint _id) public view returns(string ,  string[] memory, string[] memory) {
    string memory name = "ABC Hospital";
    uint256 length = hos[_id].records.length;
    string[] memory disease = new string[](length);
    string[] memory value = new string[](length);
    for (uint i = 0; i < length; i+=1) {
        disease[i] = hos[_id].records[i].disease;
        value[i] = hos[_id].records[i].value;
    }
    return (name , disease, value);
}

function allRecords() view returns (Hospital[]) {
    return hospital;
}

}
I want to store every Hospital record inside an array which I can show separately on the screen. But finding no solution to this problem. Can anyone help me on this?


texts: Is there any way that smart contract can access xacml policies?

texts:
I am trying to implement role based access control model using blockchain. How do i store these policies? Later my smartcontract should be able to allow or deny the rquest of user based on policie.

Thank you.


texts: Error message: Cannot read property 'eth' of undefined

texts:
<script type="text/javascript">
        async function loadWeb3() {
    if (window.ethereum) {
        window.web3 = new Web3(window.ethereum);
        window.ethereum.enable();
    }
}
 async function loadContract() {
        return await new window.web3.eth.Contract(ABI,address);
    //I'm using actual abi and address here
    }
    async function load() {
        await loadWeb3();
         window.contract = await loadContract();
    }
load();
    </script>

This error message appears when i run my index.html file in the browser. What is the error with my code?


texts: How to implement a counter (variable that is updated every time the contract is called) in Solidity?

texts:
Parent and child contract are:

contract test{
   uint a ;
   function test() {
       a = 1;
   }
   function val() returns(uint){
       return a;
   }
}

contract test2 is test{
    uint b = a++;
    function show() returns(uint){
        return b;
    }
}

Every time I call show() I would like to get the new value of b as a is incremented afterwards. I'm not able to implement this using the above code. Is there an alternative for static variable in Solidity? If not, what should be done to get the desired working?


texts: Can't find v, r & s values in the signed transaction of myetherwallet

texts: I tried to create a simple transaction using myetherwallet by importing my account from metamask. Once I've put the 'to' address, ether value and gas price, I clicked on 'generate transaction' which provided me with 'raw transaction' and 'signed transaction'. I however do not find the v,r,s values in the signed transaction, neither the tx hash. Shouldn't the signed transaction contain the signature? What am I missing here?


texts:
Does a testnet ever merge with the mainnet? In other words, if I have ETH on a testnet, will I ever have actual ETH or do testnets remain for testing forever?

I Googled in multiple ways but could never find a simple "No" or "Yes" to this question.


texts: Can you inherit from a contract already deployed to the blockchain?

texts:
So instead of doing something like:

contract Parent {
...
}

contract Child is Parent {
...
}

Can the Parent be declared referencing an already deployed contract?

contract Parent = 0x123123123...

contract Child is Parent {
...
}


texts:
Apparently Etherum-wallet DOT net is different to ethereum DOT wallet DOT info.

I used the latter and transfered ETH from Cex.io to my wallet address on June 2. It has not arrived. Subsequent emails to both cex.io and ethereum-wallet DOT info have remained unanswered. Is there something specific I need to do to get the balance updated/reflected or have they been stolen?


texts:
I am trying to build new Dapp application for our startup by using web3j , I am facing an issue with signing the transaction from server side , because i need to know the private key for the client (wallet) and it's not best practices to send the the private key over the network .

So the question is : Did anyone solve this issue , or I should keep all the code in frontend-side ?


texts: How to detect and replace the transaction details that stored in local when user retry the transaction with higher price using Metamask

texts: For a web application i stored the transaction id of an activity. if the user retry the transaction with a higher gas price in metamask(in case of the transaction take too long, metamask gives this option), is there is any possibility to replace the current transaction id that i stored with new one. how can detect this retry. is there is any web3 method for this?


texts: How does zero knowledge proof prevent frontrunning

texts: I have learned about that zkp can hide the information of orders, e.g. the type and the number of assets, but it's still confusing. Is there any paper or project about using zero-knowledge proof to prevent front-running?


texts:
when I run this code I get the error "call to Voting.candidates errored: Error encoding arguments: Error: invalid BigNumber string (argument="value", value="", code=INVALID_ARGUMENT, version=bignumber/5.0.8)" anybody know how to fix this or what is means??
contract Voting {

    ///@dev keeps track of the voter candidates' info
    struct VoterCandidate {
        string voterName;
        uint voterAge;
    }

    ///@dev keeps track of all the candidates
    VoterCandidate[] public candidates;

    ///@dev creates a new "VoterCandidate" and adds a the candidate to the array of candidates
    function candidateRegistration(string memory _voterName, uint _voterAge) public {
        VoterCandidate memory newCandidate;
        newCandidate.voterName = _voterName;
        newCandidate.voterAge = _voterAge;
        candidates.push(newCandidate);
    }

}


texts:
Is there a command line Ethereum client for vanilla Raspbian?

Hello,

Is there a command line client for Ethereum such as Geth or Parity which would run on a vanilla Raspberry Pi 3 B? I.e I do not want to install a custom OS but rather use the normal Raspbian installed on this unit.

Vesa


texts: Key management in Ethereum desktop application

texts:
I am making a desktop dapp using Ethereum, web3.js, truffle, electron, and react. This will be a ethereum private blockchain.

I can make, compile, deploy, call, transact, on testRPC using the testRPCs default accounts.

I want to discuss on the best possible ways for Key management in a Desktop ethereum app.

Questions I have are:

1, How to create new accounts?

2, Once account is created how to get Public and private key and where to save them?

Constraint : Cannot use any third party tools like Mist or metamask.

Anybody please help in designing this?


texts: How to receive ether in wallet address and forward to another address on successful deposit?

texts:
I want to implement a feature in which users will send ether to wallet address(0x123) and on successful deposit, it needs to automatically transfer to my cold wallet(0x983).

I can able to achieve this features with the help of smart contract but how to achieve this with an only wallet address without including smart contracts?


texts:
I was trying to calculate the cost of a message call (CALL, DELEGATECALL, CALLCODE) following the yellow paper but I've not been able to fully understand it.

It seems that Ccallgas is an isolated formula not linked to the Ccall formula. My guess is that there is an error and the Ccall formula should be:

Ccall = Ccallgas + Cextra instead of Ccall = Cgascap + Cextra

Am I right? I don't understand either the meaning of gascap


texts:
In the following example,

   contract Simple {
        function arithmetics(uint _a, uint _b) returns (uint o_sum, uint o_product) {
            o_sum = _a + _b;
            o_product = _a * _b;
        }
    }

How would one go about getting the result from arithmetics(5, 6)?
And how would you declare a variable holding the result?

Thank you.


texts: What is the purpose of a dry run in truffle? I mean apart from showing you how much it will cost to deploy your contract?


texts:
given address[] wallets. What is the correct method to check that the list contains a given address?

Does solidity provide any native list contains function?

If not, is the only way to do a full iteration of the array and check each element?

Are there more memory efficient ways of doing this, maybe a mapping?


texts: truffle assert equal not accurate for small differences

texts:
For some reason my truffle test suite "should send coin correctly" passes when it shouldn't. I'm just running a test suite on the standard ERC20 code found on ethereum.org. When you take 1e+21 -1010, it sees it as equal to 1e+21 -1000, and still passes it even though it is not actually equal, there is a difference of 10 between the values. If I change it to -1000000 for example, the test will fail as expected. Do I have some kind of error in the data type? Or am I doing something wrong here?

var TokenERC20 = artifacts.require("./TokenERC20.sol")

contract('TokenERC20', function(accounts) {
    it("should return the correct symbol name", function() {
    return TokenERC20.deployed(TokenERC20, "1000", "BAT_CS_180D022818", "BATC1").then(function(instance) {
        return instance.symbol.call();
        }).then(function(symbol) {
            assert.equal(symbol.valueOf(), "BATC1", "BATC1 wasn't the symbol");
        });
    });
    it("should return the correct balance", function() {
    return TokenERC20.deployed(TokenERC20, "1000", "BAT_CS_180D022818", "BATC1").then(function(instance) {
        return instance.balanceOf.call(accounts[0]);
        }).then(function(balanceOf) {
            assert.equal(balanceOf, "1e+21", "1e+21 wasn't the supply");
        });
    });
    it("should send coin correctly", function() {
        var meta;

        //get initial balances of first two accounts
        var account_one = accounts[0];
        var account_two = accounts[1];

    var account_one_starting_balance;
    var account_two_starting_balance;
    var account_one_ending_balance;
    var account_two_ending_balance;

    var amount = 1000;

    return TokenERC20.deployed(TokenERC20, "1000", "BAT_CS_180D022818", "BATC1").then(function(instance) {
      meta = instance;
      return meta.balanceOf.call(account_one);
    }).then(function(balance) {
        account_one_starting_balance = balance.toNumber();
        return meta.balanceOf.call(account_two);
    }).then(function(balance) {
        account_two_starting_balance = balance.toNumber();
        return meta.transfer(account_two, amount, {from: account_one});
    }).then(function() {
        return meta.balanceOf.call(account_one);
    }).then(function(balance) {
        account_one_ending_balance = balance.toNumber();
        return meta.balanceOf.call(account_two);
    }).then(function(balance) {
        account_two_ending_balance = balance.toNumber();
        assert.equal(account_one_ending_balance, account_one_starting_balance - 1010, "Amount wasn't correctly taken from the sender");
      assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver");
    })
  });
});


texts: Testing Smart Contracts - accessing internal vars

texts:
I'm looking for a best practice answer re testing smart contracts.
We have internal variables of the contract that we'd like to access during tests. However, making them public incurs more gas during deployment due to the added accessor functions.
Is there an alternative way to access these vars during testing?


texts:
I am reading through the solidity docs and came across this comment in the code.

Can some one please explain how this is a security risk? Is it talking about calling a new contract using delegate which re-enters recursively ? I suppose i still fail to understand the security implications.

function bid() payable {
    // No arguments are necessary, all
    // information is already part of
    // the transaction. The keyword payable
    // is required for the function to
    // be able to receive Ether.

    // Revert the call if the bidding
    // period is over.
    require(now <= (auctionStart + biddingTime));

    // If the bid is not higher, send the
    // money back.
    require(msg.value > highestBid);

    if (highestBidder != 0) {
        // Sending back the money by simply using
        // highestBidder.send(highestBid) is a security risk
        // because it can be prevented by the caller by e.g.
        // raising the call stack to 1023. It is always safer
        // to let the recipients withdraw their money themselves.
        pendingReturns[highestBidder] += highestBid;
    }
    highestBidder = msg.sender;
    highestBid = msg.value;
    HighestBidIncreased(msg.sender, msg.value);
}

In the below function, it talks about setting a storage variable to 0 , in case the function is called again, I fail to understand how is this again a security issue. Is this something similar to multithreading in C++ environment (for lack of a better comparison i could think of).

function withdraw() returns (bool) {
    var amount = pendingReturns[msg.sender];
    if (amount > 0) {
        // It is important to set this to zero because the recipient
        // can call this function again as part of the receiving call
        // before `send` returns.
        pendingReturns[msg.sender] = 0;

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

Since each call is more or less a transaction, shouldn't there be no problems with them being re-entrant?

Thanks!


texts: Initializing a storage variable to point to a bytes32 slot

texts:
How can we initialize a storage variable to point to a specific storage slot?
Example:
pragma solidity ^0.6.9;

contract SomeContract {

    struct SomeStruct {
        uint someUint;
    }

    function readFromStorage(uint someParam) external returns (uint) {
        bytes32 slot = keccak256(abi.encodePacked(msg.sender, someParam));

        // How can this variable be initialized to point
        // to a struct beginning at storage slot "slot"?
        SomeStruct storage someStruct = *(slot);
        return someStruct.someUint;
    }
}


texts: Proof of ownership and dividend in a company

texts: I want to use the ethereum blockchain to prove ownership for example in a company (or even a hedge fund). How do I guarantee my investors (or buyers) that they bought a share of my company?


texts: Are HW wallets better than password managers?

texts:
A short premise:
HW wallets and password managers have surely different scopes, but they both seems to cover what I'm interested in, which is securely storing a private key.

Hardware wallets:
a device such as TREZOR (or LedgerNanoS) is usually recommended for storing a PK because it never expose it to the machine operating the Ethereum client, so your PK can't leave the device.
Seems good so far, but what if the device breaks? You can then recover seed from a paper backup. This seems to me the most fragile passage: a paper can get lost easily, can be stolen, etc.
Otherwise a password manager db can be easily spread into several clouds, storages.

Password Manager:
a SW such as KeePass can encrypt very securerly (Argon 2 for key derivation and AES256 as cipher) your PK. Assuming you don't directly store the PK but a Keystore File (with encrypted PK), you'll just need to enter its passphrase in MEW.
The only vulnerability that comes to my mind is about keyloggers, then it can be hardened using a keyfile + passphrase authentication in KeePass.
A KeePass db is strongly encrypted and can be easily backed up.

Which is the actual advantage in using a device like TREZOR here?


texts:
In defi contracts, I see codes like this
address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);

What's the point of casting an address to address? Or is this just messy code? Thanks


texts: I am curious to know if there is a way to do metaprogramming in Solidity. My use case is about generating a smart contract from user inputted data.


texts: IERC20.approve(spender, amount) thinks the owner is also the contract

texts:
I have these functions and deployed my contract to Ropsten testnet.
  function setSmartContractAllownace(uint daiAmountIn) public {
     IERC20 daiToken = IERC20(ropstenDAI);
     daiToken.approve(address(this), daiAmountIn);
  }

  function getContractAddress() public view returns (address) {
      return address(this);
  }

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

When I call getContractAddress() and getOwner(), they return the correct values respectively.
However, when I call setSmartContractAllownace(1000), it successfully approves, but the caller (owner) is set to the address of the smart contract.
I verified this by going into DAI and checking the allowance.
This is when I put my account with DAI as _owner and smart contract as _spender

As you can see, this returns 0.
But if I put _owner also as smart contract,

it shows the correct allowance.
What is going on?
Thank you.


texts: How to get Source code of an already deployed contract?

texts: How can I retrieve the solidity code of an already published contract in the mist wallet?


texts: Checksum vs. Hash: Differences and Similarities ?

texts:
What are similarities and differences between a "checksum" algorithm and a "hash" function?

Can they be used instead of each other? Or their usage are different?

For example, for verifying the integrity of a text, which one is better to be used?


texts: remix compiler warning infinite gas requirement

texts:
I'm trying to deploy a trivial faucet program which compiles OK with remix but I get the following error.
"Gas requirement of function Faucet.withdraw(uint256) high: infinite. "
This means that while it compiles I cannot deploy it to my Ganache blockchain.
I understand the concept of gas for a function but I cannot see what is potentially infinite here: I have put a tiny limit on any withdrawal amount.

Could someone please explain?

pragma solidity >=0.5.0;

contract Faucet {

    function withdraw(uint256 withdraw_amount) public   {
        require(withdraw_amount <= 2000000);
        msg.sender.transfer(withdraw_amount);
        }

    // Accept any incoming amount
    function () external payable {}
}


texts:
I am developing a simple application that should work only in a specific time, lets say between 0800 hrs and 1600 hours. How can I do it.
That means. The contract should start by itself at 0800 and stop by 1600 everyday.
The user should not be allowed to do any transaction other than this time.


texts: Any options to remove dependency on metamask before we get integrated crypto wallets in browser?

texts:
Metamask is quite complex for non-crypto savvy users, and lately it was very unreliable(two reverts last week).

What potential options do we have to decouple our dependency from metamask? I was thinking of few:

create new eth account for user and store privatekey of user encrypted in centralized db and sign transactions on his behalf(not decentralized)
user pastes his privatekey into browser to sign transactions (very insecure)

Is there anything else at the moment in development or is waiting for integrated wallet only option to make using erc20 or eth seamless?


texts: How do I send coins over personal blockchain?

texts:
What I have done --> I have created my own blockchain which is basically forked from Ethereum. So everything that can be done on Ethereum, can in theory by done on my blockchain. I can run a local node on my device.

What I Want to do --> Create two accounts using the browser front end and some JavaScript libraries like web3.js and store its keystore file on my device locally. I want to send coins from one account to another.

Will it be possible to run a local node and connecting to that node using
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost"));

How do I view/verify the transactions being sent?


texts: Is Trojan:Win32/Tilken.B!cl a real threat? Trojan horse on geth files

texts:
Windows Defender accused some geth and ethereum files to have a trojan horse called Tilken.B!cl

file: C:\Program Files\Geth\uninstall.exe
file: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Geth\Uninstall.lnk
regkey: HKLM\SOFTWARE\Wow6432Node\MICROSOFT\WINDOWS\CURRENTVERSION\UNINSTALL\Ethereum Geth
startup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Geth\Uninstall.lnk
uninstall: HKLM\SOFTWARE\Wow6432Node\MICROSOFT\WINDOWS\CURRENTVERSION\UNINSTALL\Ethereum Geth

Is it a false positive or a real threat??

Apparently this alert happened to more people:
Is my computer infected? Trojan:Win32/Tilken.B!c...

Microsoft Malware Encyclopedia


texts: Get Ethereum to run on a Raspberry Pi Zero?

texts: How would one get Ethereum to run on a raspberry pi zero?


texts: How does geth's --fast, --jitvm and --cache headers make blockchain download fast?

texts:
What does the --fast flag does? I read somewhere that it doesn't download transactions of the blocks rather just state downloads? But what are state downloads?

What does geth use cache for? It can simply put the downloaded data in filesystem right?

What is jitvm and jitvm cache? And also why we need to force it?


texts: Is there a tool to help find the 'distance' between two Ethereum addresses?

texts: I.e., if A has sent to B, distance = 1. If A has sent to B and B has sent to C, distance between A and C is 2.


texts: Unable to get value of pending transactions on one peer on another peer

texts:
I have two nodes (A and B) running as peers on a private network . How can i check if there are pending transactions on one node (suppose Node A ) from node B.

Node A has rpc enabled and rpcport is 8001

I wrote a js snippet for node B `

var Web3 = require('web3');

var web3 = new Web3(new Web3.providers.HttpProvider("http://ipAddress:8001"));

var mining_threads = 1;

console.log(web3);

function checkWork() {

    if (web3.eth.getBlock("pending").transactions.length > 0) {
        if (eth.mining) return;
        miner.start(mining_threads);
    } else {
        miner.stop();
    }
}

But this code results in the following error:

  err: TypeError: 'XMLHttpRequest' is not a function

And secondly when i log the web3 object above, it shows a property eth which is an object. But this eth object doesnot have pendingTransactions method.

How to fetch the pending transactions from Node A then ?


texts: Gas estimation failed when trying to input a list of bytes32[5]

texts:
I am trying to create a struct as shown in the code below.

The function setData is intended to create an object of the struct, take the inputs (a string and a list of type bytes32[5]) and set their values. The code compiles perfectly. However, when I try to run the setData function with the inputs shown below, I get Gas estimation failed.

Test Inputs:

"0x9b461b19602cfe81c9ffb52d6983b7c39c5b3f97",["0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac0","0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac1","0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac2","0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac3","0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac4"],"Frank"

pragma solidity ^0.4.21;

contract Registration {

    struct staffMemberData {
        string name;
        bytes32[5] staffMemberAttributes;
    }

    mapping (address => staffMemberData) staff;
    address[] public staffMemeberAccts;

    function setData(address _address, bytes32[5] _attributes, string _fName) public {
        var s = staff[_address];

        uint256 arraylength = 5;
        uint8 x = 0;
        while(x < arraylength)
        {
            s.staffMemberAttributes[x] = _attributes[x];
            x++;
        }

        s.name = _fName;

        staffMemeberAccts.push(_address) -1;
    }

    function getData() view public returns (address[]) {
        return staffMemeberAccts;
    }

}

What am I doing wrong? Is there a better way to do this to not consume as much gas?


texts: Truffle test promise that expectedly throws error

texts:
I have contract with methods that check input parameters using require(bool) so if at least on of conditions does not matched it throws an error. During test procedure (using Truffle and Chaijs) it looks like:

 Error: VM Exception while processing transaction: invalid opcode
  at Object.InvalidResponse (/usr/lib/node_modules/truffle/build/cli.bundled.js:37022:16)
  at /usr/lib/node_modules/truffle/build/cli.bundled.js:210096:36
  at XMLHttpRequest.request.onreadystatechange (/usr/lib/node_modules/truffle/build/cli.bundled.js:208875:13)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/lib/node_modules/truffle/build/cli.bundled.js:210748:18)
  at XMLHttpRequest._setReadyState (/usr/lib/node_modules/truffle/build/cli.bundled.js:211038:12)
  at XMLHttpRequest._onHttpResponseEnd (/usr/lib/node_modules/truffle/build/cli.bundled.js:211193:12)
  at IncomingMessage.<anonymous> (/usr/lib/node_modules/truffle/build/cli.bundled.js:211153:24)
  at endReadableNT (_stream_readable.js:1047:12)
  at _combinedTickCallback (internal/process/next_tick.js:102:11)
  at process._tickCallback (internal/process/next_tick.js:161:9)

Test uses promises like this:

return MyToken.deployed().then(inst => {
  instance = inst;
  return instance.purchase({from: accounts[1], value: amount});
})....

Problem is that I cannot handle this exception. I tried to wrap purchase call into function and use assert.throws(executor, message) - it does not works (suppose due it expects something synchronous).

How this promise can be tested (preferably without adding chai-as-promised)?


texts: Can't visit UI if Parity use --geth to set geth mode

texts:
I use --geth to set Parity to geth mode. Because I want to use personal.unlockAccount and unlock an account permanently.(If don't set geth mode, it can't unlock permanently... which mentioned in this issue.)

But when I use --geth when I start my Parity. I can't visit my Parity UI...
Before I set it, I can visit it with localhost:8180. But after I set it, I can't visit it with localhost:8180 or 127.0.0.1:8180 even 10.4.20.69:8180... How can I find back my webUI under geth mode? Thanks a lot.

This is my config:

[parity]
chain = "HyperAlbum-chain.json"
base_path = "node0"
[network]
port = 30300
[rpc]
port = 8540
apis = ["web3", "eth", "net", "personal", "parity", "parity_set", "traces", "rpc", "parity_accounts"]
interface = "10.4.20.69"
[ui]
port = 8180
[dapps]
port = 8080
[account]
password = ["node.pwds"]
[mining]
engine_signer = "0x00765Cc7584E3Ed11aE092b74d10AE2cE875aEAb"
reseal_on_txs = "none"
usd_per_tx = "0"

Thanks a lot. :)


texts: How Ethereum estimate the gas for running a contract?

texts:
I am new to Ethereum. I know gas limit and gas price well. but still confused in

when sending a transaction to run a deployed contract, does Ethereum suggest an estimation of how much gas limit is needed to complete the transaction?
if so, How accurate is that estimation? In other words, will it always be  completed successfully if only the estimation gas is being paid?
if no, How can i know/predict the gas needed?
For miners when they got a transaction to run a contract, are they able to know how much will it take to finish the execution (know how much gas limit (computational steps) this transaction costs) or they just know how much is the gas price?.
How validators verify that miners executed a contract correctly? will they re-execute it again or just validate the block without running contracts?

I tried to figure these out, but still not be able.

Thanks


texts: how get to nonce that need to send in ethereum transaction?

texts:
I have written down node js code to send eth using web3. I am getting nonce value using getTransactionCount which is working fine but as all know it can not count pending transaction so if i send another transaction before the first one confirmed it generates an error. here is my code

                    var pkey1 = xxxxxxxxxxxxxxx;
                    var privateKey = new Buffer(pkey1, 'hex');

                    web3.eth.getTransactionCount(fromAccount, function(err, nonce) {
                        web3.eth.getGasPrice(function(err, gasPrice) {
                            var gasLimit = 31500;
                            gasPriceHex = web3.utils.toHex(gasPrice);
                            gasLimitHex = web3.utils.toHex(gasLimit);
                            nonceHex = web3.utils.toHex(nonce);
                            amountHex = web3.utils.toHex(amount);
                            var rawTx = {
                                nonce: nonceHex,
                                gasPrice: gasPriceHex,
                                gas: gasLimitHex,
                                to: toAccount,
                                from: fromAccount,
                                value: amountHex,
                            };
                            var tx = new Tx(rawTx);
                            tx.sign(privateKey);

                            var serializedTx = tx.serialize();

                            try {
                                web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
                                    if (err) {
                                        console.log(err);
                                        res.json({
                                            status: false,
                                            msg: "Please try after sometime",
                                            httpcode: 400
                                        });
                                    } else {
                                        res.json({
                                            status: true,
                                            msg: "Transaction Done Successfully",
                                            txid: hash,
                                            httpcode: 200
                                        });
                                    }
                                });
                            } catch (e) {
                                res.json({
                                    status: false,
                                    msg: "insufficient funds",
                                    httpcode: 400
                                });
                            }
                        });
                    });


texts:
I am trying to create a tx to interact with one of smart contract function.
function withdraw(uint withdraw_amount) public {

}

I tried declaring the params for ethTx as this :
   const params = {
            nonce: nonce,
            to: contractAddress, //address of the receiver
            value: '0x000', // value in hexa format
            gasPrice: web3.utils.toHex('20'),
            gasLimit: GAS,
            chainId: 42, // 1 for main ethereum chain
            data: web3.utils.toHex("cont.methods.withdraw('100000000000000000')")
          };

the data only accepts params but I dont know to how to give it in hex and I am not sure this works or not but the tx is created but never finished (in pending state).
I even tried to use web3 methds for calculating the nonce and gas limit
     var GAS = await cont.methods.withdraw("100000000000000000").estimateGas({from: address},
             function(error, estimatedGas) {
      console.log(estimatedGas);
    });
    console.log("gas price is"+GAS);
    var nonce = await web3.eth.getTransactionCount(address);
    console.log(nonce);

Can anyone tell me what I am doing wrong here. Thanks!


texts: How can I get the gas limit specified for a past transaction from web3?

texts:
I'd like to know the difference between gas limit specified and gas actually used by a confirmed transactions from previous blocks.
For each transaction on Etherscan, you can see both the actual gas used by a transaction (named Gas Used by Transaction) and the gas limit specified at time of sending (name Gas Limit).
Using web3.eth.getTransactionReceipt only returns gasUsed (docs), which corresponds to actual gas used by transaction. How can I get the value for gas limit specified at the time of sending from web3 or some other source?


texts:
if my geth is syncing in fast mode and I try to query method eth_blockNumber, will it throw me an error, cause it is not, i tried curl in verbose mode and below is the result.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8545 (#0)
> POST / HTTP/1.1
> Host: localhost:8545
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 69
>
* upload completely sent off: 69 out of 69 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json
< Vary: Origin
< Date: Mon, 13 Jul 2020 13:05:50 GMT
< Content-Length: 41

Can anyone help me with this doubt?


texts: Are there any NFT marketplaces that accept non-media or even arbitrary file formats?

texts: I am curious as to whether there are NFT marketplaces that allow minting tokens for arbitrary file formats say pdfs, text files, etc .


texts: Is there any possible way to change the blockchain size?

texts: Is there any way to choose between Archive, Basic, Fast, Light? And whats the benefit of each size of blockchain. Sorry if I said something wrong, I am new. Thank you


texts: Is removal of elements from arrays possible in solidity?

texts: Assume a struct Node and an array of Nodes allNodes[]. I was successful in adding Node to the array but when I tried to use a removeNode() method (which uses the delete method in arrays), the value of allNodes.length remains the same. Is it because blockchains are "immutable". Doesn't immutable mean that when a transaction is made (even remove Node()), it cannot be undone?


texts:
I understand a contract being described as a top level abstraction, but what are some architectural and design advantages (and disadvantages) for developers in isolating their design classes into separate contracts? What are the general gas expense implications of separating functionality among contracts (for libraries, data/logic division) or spawning new contracts from existing contracts?

Personally I view contracts as an even higher level of abstraction than a class in a given oop (lower than a file, but higher than other general object types) What is the driving motivation to treat contracts as classes in Solidity?


texts: How blockchain detect and recover from local database corruption?

texts: I am thinking about a scenario, where an attacker modifies my local blockchain. However, since if one block is modified and then all subsequent blocks are required to re-mine. So, the attacker chooses to change the last block of my local blockchain. Then, a new transaction arrived and the hash of last block can't be matched with "the previous block hash" value in new transaction. What will happen now? Will the blockchain reject every new transaction?


texts: What is Parity doing after warp sync besides importing new blocks?

texts:
I noticed Parity is still busy working on old blocks after a warp sync - but it doesn't really tell why. e.g.

2018-06-07 08:38:14 UTC Imported #5746763 098a…98f4 (37 txs, 1.69 Mgas, 137.63 ms, 8.11 KiB)
2018-06-07 08:38:34 UTC Syncing #5746763 098a…98f4     0 blk/s    0 tx/s   0 Mgas/s      0+    0 Qed  #5746764    6/100 peers      5 MiB chain  117 MiB db  0 bytes queue   10 MiB sync  RPC:  0 conn, 22 req/s, 115 µs
2018-06-07 08:39:05 UTC Syncing #5746764 e094…7fb0     0 blk/s    0 tx/s   0 Mgas/s      0+    0 Qed  #5746760   11/100 peers    315 KiB chain  117 MiB db  0 bytes queue    6 MiB sync  RPC:  0 conn, 57 req/s,  91 µs
2018-06-07 08:39:05 UTC Syncing #5746764 e094…7fb0     0 blk/s    0 tx/s   0 Mgas/s      0+    0 Qed  #5746760   11/100 peers      2 MiB chain  117 MiB db  0 bytes queue    6 MiB sync  RPC:  0 conn, 57 req/s,  91 µs
2018-06-07 08:39:47 UTC   #5101162    1/100 peers     40 KiB chain  117 MiB db  0 bytes queue    8 MiB sync  RPC:  0 conn, 10 req/s,  43 µs
2018-06-07 08:39:47 UTC   #5101162    1/100 peers     53 KiB chain  117 MiB db  0 bytes queue    8 MiB sync  RPC:  0 conn, 11 req/s,  98 µs
2018-06-07 08:39:47 UTC   #5101162    1/100 peers     53 KiB chain  117 MiB db  0 bytes queue    8 MiB sync  RPC:  0 conn, 18 req/s, 631 µs
2018-06-07 08:39:47 UTC   #5101162    1/100 peers     53 KiB chain  117 MiB db  0 bytes queue    8 MiB sync  RPC:  0 conn, 18 req/s, 631 µs
2018-06-07 08:40:32 UTC Imported #5746771 564f…171e (139 txs, 7.99 Mgas, 851.06 ms, 27.05 KiB) + another 1 block(s) containing 241 tx(s)
2018-06-07 08:40:32 UTC   #5101480    1/100 peers      5 MiB chain  118 MiB db  0 bytes queue   15 MiB sync  RPC:  0 conn, 11 req/s, 8792769 µs
2018-06-07 08:40:32 UTC   #5101480    1/100 peers      5 MiB chain  118 MiB db  0 bytes queue   15 MiB sync  RPC:  0 conn, 11 req/s, 8792769 µs
2018-06-07 08:40:32 UTC   #5101480    1/100 peers      5 MiB chain  118 MiB db  0 bytes queue   15 MiB sync  RPC:  0 conn, 10 req/s, 1569665 µs
2018-06-07 08:40:32 UTC   #5101480    1/100 peers      5 MiB chain  118 MiB db  0 bytes queue   15 MiB sync  RPC:  0 conn, 10 req/s, 1569665 µs

The first few lines are understandable - #5746763 and #5746764 are new blocks from the network. But afterwards it's still doing something with #5101480 - and apparently, that took >8.7s, which caused the Parity node to be temporarily unresponsive to RPC calls.

What's happening here?


texts:
I'm new to Blockchain. I'd like to design a system where solvers can solve real-world tasks initiated by the task owners. Miners are part of a cloud/cluster that provides resources. They verify and mine the smart contracts between the owners and solvers. But I also want the miners and solvers to be rewarded.
I'd like to be able to set the rewards percentage in the contracts themselves, then basically some tokens are paid by the owner and some tokens are mined. How would I implement such a network? Any references would also be appreciated.
Would it be possible to mine the contracts on a private network, and mine Ether on the public network in parallel, then distribute a portion of the mined Ethers to the task solvers? or shall I focus on creating my own reward and consensus mechanism (e.g. proof-of-useful-work)?
I'm just trying to find a feasible way to reward both solvers of the tasks (the solution providers) and the miners (the nodes in the resource provider cluster)


texts: Truffle Console: How to suppress unwanted message

texts:
I am trying to learn truffle features by going through the following tutorial. Its generating a huge message, please guide me if its wrong or not. If its not wrong please guide me how to suppress the message
Medium Just Dev
I am executing the following command:
**truffle(ganache)> getBalance = web3.eth.getBalance**

I am getting the following message:

{ [Function: send]   method:     Method {
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter:
[ [Function: inputAddressFormatter],
[Function: inputDefaultBlockNumberFormatter] ],
outputFormatter: [Function: outputBigNumberFormatter],
transformPayload: undefined,
extraFormatters: undefined,
requestManager: RequestManager { provider: [Object], providers: [Object], subscriptions: {} },
accounts:
Accounts {
currentProvider: [Getter/Setter],
_requestManager: [Object],
givenProvider: null,
providers: [Object],
_provider: [Object],
setProvider: [Function],
_ethereumCall: [Object],
wallet: [Object] },

Somebody please guide me how to suppress the above message.
Zulfi.


texts: Could Ethereum obtain broad contract language support like NEO?

texts:
I recently saw NEO being advertised as Ethereum but with multiple language support for smart contracts.

Is this really something that Ethereum lacks? Is it not technically possible to build more compilers for smart contracts that generate Ethereum bytecode? I believe there are already three compilers, Solidity, Serpent and LLL.

All of this reminds me of the .NET hype where it was entirely possible to compile any language to JVM but .NET was still being touted as language-independent. Is history repeating itself? Or am I missing something?

Thanks.


texts: What's the difference between a side chain and a state channel?

texts:
I hear them almost used interchangeably, and I was wondering what the technical difference is so that I can use the terms correctly.

From my understanding, a sidechain is a subset of a state channel (just an implementation of a blockchain as the channel), but I'm curious if there are any good resources out there.


texts:
So for example, I want to enable my contract 1 week after deployment, thats now() + 1 week,
how could I know which block that will be so I can send my clients a countdown to that block with
https://bscscan.com/block/countdown/9999999


texts: Transfer token sent to wrong address (contract address)

texts:
Good day/eve.  I purchased the OMI token and initiated a withdrawal to my trezor hardware wallet as an ERC20 token. This was an error (isn't an ERC20 token any longer) and therefore the transaction was sent to Gochain to a the contract wallet address shown here: https://explorer.gochain.io/tx/0x15daabe45e768dfbbb38468bd714fc30cc312b1d7691a7639c72c836b3526d58.
It looks like this blockchain has a transfer function but I am unsure how to proceed. Any ideas you can share with me?


texts: Solidity - Can an attacker call private functions?

texts:
Looking around I found Solidity functions - private visibility but not an answer to my specific question. Basically my question is: is the private keyword enforced at the Solidity language level or EVM level? My intuition says it is a Solidity feature but I wanted to double check here.

I am just getting started with Ethereum so pardon any beginner mistakes. Consider the following Solidity code:

contract Silly {
  function unsafePrivateWithdraw(address addr, uint amount) private {
    addr.transfer(amount);
  }
  function safeWithdraw(address addr, uint amount) {
    if (!checkWithdrawConditions) throw; // pseudocode
    unsafePrivateWithdraw(addr, amount);
  }
}

I know that using Solidity one wouldn't be able to call unsafePrivateWithdraw directly. But could somebody write in LLL or EVM opcodes a direct call to the address of the unsafePrivateWithdraw function?


texts: Why block number is kept BigInteger in Web3j?

texts:
BigInteger blockNum = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send()
    .getBlock().getNumber();

Long.MAX_VALUE (9223372036854775807) is more than enough to hold block number.

It is easier and efficient to iterate over long than BigInteger. There are use-cases when we need to iterate over blocks; for example - to find N latest blocks.

Also addition, deletion and comparison is easier with long.


texts:
Aim: To log data from a smart contract.

Following function is written in accordance with low level interface to Logs in ethereum. However, due to lack of documentation, and being new in Solidity, I am not able to figure out how and where to get the logs.

function:

 function addNewUser(address _userAddr, uint _amount) public {
        log1(
            bytes32(_userAddr),
            bytes32(msg.sender)
        );
        require(msg.sender == _userAddr); //only owner of lottery can create new Users
        uint256 id = users.push(User(_amount, _userAddr)) - 1;
        addressToUser[_userAddr] = id;
        NewUser(_amount, _userAddr); //event to FE (no return possible in BC edit functions)
    }

When i call function on truffle's console following data is displayed:

  Command: lot.addNewUserToLottery(24,
  0x6330a553fc93768f612722bb8c2ec78ac90b3bbc);

TRUFFLE CONSOLE

{ tx: '0xcfd479f7493f215d3f4bac54ab6331fc2dfaea88784a0f543614e22c7092ccf8',
  receipt:
   { transactionHash: '0xcfd479f7493f215d3f4bac54ab6331fc2dfaea88784a0f543614e22c7092ccf8',
     transactionIndex: 0,
     blockHash: '0xdd0ebd3f560bd8ce143fe0a77e99818e9a072fa7b9afb79f4beca0363dfb5047',
     blockNumber: 110,
     gasUsed: 96578,
     cumulativeGasUsed: 96578,
     contractAddress: null,
     logs: [ [Object], [Object] ],
     status: '0x01',
     logsBloom: '0x00000000000000000000000000000000000000040000000000000000000000000000008000000000000080000000000000000000000000400000000000000000000000000800000000000000000000000000000000000000040000000000000000000000000000000000001000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' },
  logs: [] }

testrpc BLOCKCHAIN

 develop:testrpc   Gas usage: 26981 +0ms
  develop:testrpc   Block Number: 117 +0ms
  develop:testrpc   Block Time: Sat Apr 14 2018 15:25:59 GMT+0530 (IST) +0ms
  develop:testrpc  +0ms
  develop:testrpc eth_getTransactionReceipt +1ms
  develop:testrpc eth_sendTransaction +6s
  develop:testrpc  +48ms
  develop:testrpc   Transaction: 0x2f901a79252860c2200cc2923eba859ea585922a844a1aae69ee0240fe4ae45d +1ms

Where are the logs printed? Am I missing something?


texts: Confused by the way to construct an abstract contract

texts:
Confused by an example of the doc
Codes like below
// These abstract contracts are only provided to make the
// interface known to the compiler. Note the function
// without body. If a contract does not implement all
// functions it can only be used as an interface.
abstract contract Config {
   function lookup(uint id) public virtual returns (address adr);
}

// Multiple inheritance is possible. Note that `owned` is
// also a base class of `Destructible`, yet there is only a single
// instance of `owned` (as for virtual inheritance in C++).
contract Named is Owned, Destructible {
   constructor(bytes32 name) {
       Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);
       NameReg(config.lookup(1)).register(name);
   }
....

What I don't get is how can construct a Config contract instance like that ?
Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970);

Config is an abstract contract without defining a constructor.


texts: How to airdrop tokens to multiple addresses in one transaction

texts:
I am trying to host an airdrop but sending the tokens individually to thousands of people would take forever. Is there a way to do it in one transaction with multiple recipients.

If so, could you please provide me with some code.

Thanks


texts: connecting smart contract in solidity front end with ropsten test net

texts:
Index.html file :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="main.css">

Coursetro Instructor

        Instructor Name
        <input id="name" type="text">

        Instructor Age
        <input id="age" type="text">

        <button id="button">Update Instructor</button>

Main.css file :

body {
    background-color:#F0F0F0;
    padding: 2em;
    font-family: 'Raleway','Source Sans Pro', 'Arial';
}
.container {
    width: 50%;
    margin: 0 auto;
}
label {
    display:block;
    margin-bottom:10px;
}
input {
    padding:10px;
    width: 50%;
    margin-bottom: 1em;
}
button {
    margin: 2em 0;
    padding: 1em 4em;
    display:block;
}

#instructor {
    padding:1em;
    background-color:#fff;
    margin: 1em 0;
}
#loader {
    width: 100px;
    display:none;
}

Smart contract in remix :

pragma solidity ^0.4.18;
contract Coursetro{
    string public fname;
    uint public age;

       function setInstructor(string _fname,uint _age) public{ //demo is constructor function
        fname = _fname;
        age = _age;
                    }
    function getInstructor() public constant returns(string,uint){
        return(fname,age);
    }
}

Steps which I have followed:

I have run ropsten testnet and using meta mask I have run my smart contract in remix.
Then I have taken ABI and address from remix and  put in javascript code.
Here I am getting the error.