texts: How to connect 2 nodes without admin.addPeer()?

texts:
So, I started 2 nodes on my private net using geth, with custom genesis file, different port numbers, all how it was supposed to be. In one instance I added the    admin.nodeInfo.enode of the other and two nodes were perfectly in sync. I mined on one and the second had the same block number as the first. Brilliant. However, after restart the nodes were not peers anymore and I had to type admin.addPeer() again in order to sync them. Is there a way to sync the nodes without manually adding the peers?

To clarify, I did not use the --nodiscover flag so I think there should be some way the first node to discover second wtihout manual typing.

I know you can sync two nodes without admin.addPeer() if you declare the admin.nodeInfo.enode of the other in static-nodes.json located in the data dir of the first. But that also requiers manual entering. I want to know if there is another, simpler way.


texts:
Is there regulation and penalty on how long the period is between buying and selling Ethereum. Say I sell within a week of buying, then I have to pay much higher taxes and a penalty fee?

What is the minimum amount of time between buy and sell without incurring extra penalty?

I am using Coinbase by the way, not sure if that makes a difference.


texts: One contract accessing data from another fails

texts:
I am trying to get two contracts to interact:

pragma solidity ^0.5.10;

contract C2 {

    address public addr;

    constructor(address per) public {
        addr = per;
    }

    function remote_get_number() external view returns(uint) {
        return C1(addr).get_a_number();
    }

    function remote_set_number(uint num) external {
        C1(addr).set_a_number(num);
    }
}

contract C1 {

    uint public a_number;

    function get_a_number() external view returns(uint) {
        return(a_number);
    }

    function set_a_number(uint num) external  {
        a_number = num;
    }
}

I create an instance of C1, then create a C2 instance using the address of the C1 instance as the argument of the C2 constructor.

If I call, say remote_set_number(42), it works correctly; calling get_a_number() returns 42. Likewise for any uint value. However, when I call remote_get_number(), event though all that does is return the result of a C1(addr).remote_get_number() call, the value returned is always 0.

How do I get a call of a function in one contract to correctly return a value when it is called by a function in another? It seems to me that this follows the patterns given in the Solidity documentation, so I have no idea why it's not working. Can anyone shed a little light?

(This was done using Injected Web3 on a private blockchain in Remix)

UPDATE:

I tried updating to the latest stable geth (1.9.3), and now I get the following error for any interaction between contracts: Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Internal JSON-RPC error.

I have tried it with two different blockchains, with different genesis blocks. #1:

{
    "config": {
        "chainId":123 ,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },

    "nonce": "0x0000000000000042",     "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",     "gasLimit": "0x8000000",     "difficulty": "0x400",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0xDB725f67f09228Ea1075f36a0fDb568B9aeBd54C",
    "alloc":{
      "DB725f67f09228Ea1075f36a0fDb568B9aeBd54C":{
        "balance":"6660000080800000000777"
      }
  }
}

and #2:

{
    "config": {
        "chainId":123 ,
        "homesteadBlock": 0,
        "byzantiumBlock": 0,
        "constantinopleBlock": 0,
        "petersburgBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },

    "nonce": "0x0000000000000042",     "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",     "gasLimit": "0x8000000",     "difficulty": "0x80",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0xB10Ec08f54343133875f0244e2A435C19789ec28",
    "alloc":{
      "B10Ec08f54343133875f0244e2A435C19789ec28":{
        "balance":"6660010005550000100777"
      }
  }
}

I have tried using a different versions of solidity - but I've had the same results with Solidity 0.4.1, 0.4.4, 0.5.1, and 0.5.11.


texts: Diffrent between smart contract and dapp

texts:
I struggle with the following questions about definitions.

Is a dapp just the implementation of a smart contract? So when someone says he is writing a smart contract he is actually writing a dapp?

Also, can I write a dapp which is not a smart contract or is any dapp automaticly a smart contract?

Thanks for helping me out.


texts: cannot "npm install -g truffle" in PowerShell - #ERROR (cannot find module 'original-require')


texts: T:Floating point multiplication, then flooring result to get uint

texts:
In pseudo-code:

uint basePrice = shop.basePrices(_Index_);
float rate = increaseRate(_index) / 100,
float multiplier = math:pow((1 + rate), _amount),
floor(basePrice * Multiplier).

I want to end up with an integer. How can I do multiplication on decimals then floor it at the end to give a nice uint result?

EDIT:

This compiled.

function cost(uint _minerIndex, uint _owned) public pure returns (uint) {
    uint basePrice = shop.basePrices(_minerIndex_);
    uint rate = baseRates(_minerIndex) * 100;
    return (basePrice * ((1 + rate) ** _owned)) / 100;
  }

but I don't see how I could extract this logic to use floating points at all, The documentation talks about rational numbers but gives zero examples of instantiating a rational number.


texts: Several basic question about difference Bitcoin and Ether transactions

texts:
Sorry for the easy questions.
I was developing tools for Bitcoin and now I want to try and use Ethereum instead.

Raw transaction does not contain inputs and outputs, enough balance confirm outside this? Where and how?
Can I decode Signed raw transaction?


texts:
as per ethereum docs

Even if a contract’s code does not contain a call to selfdestruct, it
can still perform that operation using delegatecall or callcode.

is this real?

  1.if it is then even if my contract don't have kill function defined can i kill that contract? how to call delefatecall or callcode?

  2.anyone other then me can kill the contract?
  if yes then how to stop that?


texts:
What is the standard way to delay the payment of an ERC20 token?

Context:

I am looking for a way that a user would pay for my ERC20 token in ETH, then an arbitrary number of days later, lets say 7 days, they would receive the tokens.

How is this usually achieved in Solidity?

I have read in the docs that that date/time handling is done with block.timestamp

Some example code I have found is:

function f(uint start, uint daysAfter) {
    if (now >= start + daysAfter * 1 days) {
      // ...
    }
}

but I am unsure on how to use it to trigger payment to a user after x days.


texts: Save data in transaction generated through a smart contract

texts:
I want to lunch a clustering (procedure) algorithm in off_chain  on data recorded in an IPFS.
Input: my data, k:  number of cluster or class
Output:  data clustered or labelled in class k

How to save the output in a blockchain (on-chain) through transactions?
How to include the On-chain blockchain in all this through transactions?

In other words:

I want to generate transactions, in these transactions I want to save my partitioned data(k cluster) in object if to lunch a consensus protocol?

the problem is that, I cannot generate several transactions in a unique smart contract because I have only a single private key and I can’t sign all my transactions with one private key. Moreover in a smart contract I can’t generate external transactions?

How to solve the problem?

Cordially.


texts: How to know solidity version of remix for already deployed contract

texts:
I recently deployed a smart contact using remix and MyEtherWallet. The contract is deployed successfully.

But when I am trying to verify the contract code on etherscan. I need compiler version for that. But I don't remember what compiler version did I use. Is there any chance of getting that?

I have contract code, abi, address but not solidity version. How can I verify my contract on etherscan. Hit and try are taking very long time.


texts:
I'd like to connect geth by IPC on rails. I start geth as follows.

$build/bin/geth --datadir "/home/vagrant/.ethereum" --networkid "1" --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --ipcpath "/home/vagrant/.ethereum/geth.ipc"

Then I tried to connect from rails console using ethereum-ruby.  However, it returns error. Could you tell me how to connect geth from ruby?(It doesn't matter whether it is used the library or not.

[1] pry(main)> client = Ethereum::IpcClient.new("#{ENV['HOME']}/.ethereum/geth.ipc")
=> #<Ethereum::IpcClient:0x007f4f4365f470
 @batch=[],
 @id=1,
 @ipcpath="/home/vagrant/.ethereum/geth.ipc">
[2] pry(main)> client.eth_coinbase
NoMethodError: undefined method `eth_coinbase' for #<Ethereum::IpcClient:0x007f4f4365f470>
from (pry):2:in `<main>'


texts: How much is the biggest BytesX type in solidity? (Bytes32?)

texts:
I'm trying to keep it simple while returning and array of strings. I want to return a fixed bytesX array with small text. How much is the possible X in the BytesX type?
In Remix it seems to be Bytes32. Is it right?
Thanks


texts: How can I tell my progress and the number of peers I'm connected to when using geth to download blockchain?

texts:
I'm running get --fast --cache=1024 on my laptop as we speak, and I'd like to know some stats about how many peers I'm connected to at any given time.  I've been checking the size of my chaindata directory for a rough estimate of my progress, but is there any way to get this information from the geth process itself?

Thanks!


texts: What is the difference between `now` and `block.timestamp`?

texts:
My main goal is to obtain time spent between two transaction calls inside my smart-contract. I am not sure, should I depend on now or block.timestamp to obtain the most accurate time difference in between transactions.

I have call my contract's start() and end() functions to store now and/or block.timestamp values. getTimeDif() returns the difference.

Contract-1:

contract Now {
   uint start;
   uint end;
   function start(){
      start = now;
   }
   function end(){
      end = now;
   }
   function getTimeDif() returns(uint){
      return end - start;
   }
}

Scnerio:

Now.start(); //Transaction mined on blk.num=100.
Now.end();  //Transaction mined on blk.num=200.
console.log( Timestamp. getTimeDif(); )  //Transaction called on blk.num=201.

Contract-2:

contract Timestamp {
   uint start;
   uint end;
   function start(){
      start = block.timestamp;
   }
   function end(){
      end = block.timestamp;
   }
   function getTimeDif() returns(uint){
      return end - start;
   }
}

Scnerio:

Timestamp.start(); //Transaction mined on blk.num=100.
Timestamp.end();  //Transaction mined on blk.num=200.
console.log( Timestamp. getTimeDif(); )  //Transaction called on blk.num=201.

[Q]  On the contracts above, should I assume difference between stored now value and stored block.stamp value to be same? ( Timestamp.getTimeDif() ?= Now.getTimeDif() ) Which one might return me the most accurate time difference between two called transactions?


texts: Recover public key from transaction signature

texts:
I have this transaction:

{
  "blockHash": "0x163ad564b32bf17db9262391c2c9a5f191e4fd0b098ae5ce9d2e3e7dcde4bd70",
  "blockNumber": "0x2",
  "from": "0x55d40a83b8445c004df5964ce4a0e261b599c01a",
  "gas": "0x76c0",
  "gasPrice": "0x9184e72a000",
  "hash": "0x5e97c5377da7864e5b82784c9e5335a2e075adfec3b075f5f2e5705733aacf8b",
  "input": "0x",
  "nonce": "0x8",
  "to": "0x589724c5abf2bce219726477cf0a60fa09321380",
  "transactionIndex": "0x0",
  "value": "0x1",
  "v": "0x1c",
  "r": "0xfe084488847df1cf427f72784c4b1ba86526ed5f8ef0feb6bc51caf450d66e8b",
  "s": "0x6226e5f4dd0d948b7014199faf018c27862c56faad0b49197057816dee9a7fa8"
}

So I made two files from the data of the transaction above: msg (transaction hash) & sig (r + s + v-27).

[root .eth]# hexdump -C msg
00000000  5e 97 c5 37 7d a7 86 4e  5b 82 78 4c 9e 53 35 a2  |^..7}..N[.xL.S5.|
00000010  e0 75 ad fe c3 b0 75 f5  f2 e5 70 57 33 aa cf 8b  |.u....u...pW3...|
00000020
[root .eth]# hexdump -C sig
00000000  fe 08 44 88 84 7d f1 cf  42 7f 72 78 4c 4b 1b a8  |..D..}..B.rxLK..|
00000010  65 26 ed 5f 8e f0 fe b6  bc 51 ca f4 50 d6 6e 8b  |e&._.....Q..P.n.|
00000020  62 26 e5 f4 dd 0d 94 8b  70 14 19 9f af 01 8c 27  |b&......p......'|
00000030  86 2c 56 fa ad 0b 49 19  70 57 81 6d ee 9a 7f a8  |.,V...I.pW.m....|
00000040  01                                                |.|
00000041

Then I wrote a program in go to recover the public key:

[root@v48807 .eth]# cat recover-pk.go
package main

import (
  "io/ioutil"
  "fmt"
  "os"

        secp256k1 "github.com/ethereum/go-ethereum/crypto/secp256k1"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
        msg, err := ioutil.ReadFile("msg")
  check(err)

        sig, err := ioutil.ReadFile("sig")
  check(err)

  pkbin, err := secp256k1.RecoverPubkey(msg, sig)
  check(err)

        f, err := os.Create("pkbin")
  check(err)
  defer f.Close()
        n, err := f.Write(pkbin)
  check(err)
  fmt.Printf("wrote %d bytes\n", n)
}

Here is a dump of the resulting public key:

[root .eth]# hexdump -C pkbin
00000000  04 bc 63 e4 84 c2 ed 68  56 8d 20 74 b0 ff 2e a1  |..c....hV. t....|
00000010  b0 51 02 3d d9 c8 f2 4c  c0 c2 5d 93 f4 14 2b bc  |.Q.=...L..]...+.|
00000020  40 56 d9 4b 32 dc 1e 65  74 6b c7 0a 3e fe 2a ba  |@V.K2..etk..>.*.|
00000030  db d2 e3 74 d8 ad 9c fd  d1 0c f1 1b 12 74 ef df  |...t.........t..|
00000040  53                                                |S|
00000041

The problem is that this public key is a different from that that I generated in the first place:

[root .eth]# cat addr1/address
55d40a83b8445c004df5964ce4a0e261b599c01a
[root .eth]# hexdump -C addr1/pubo-bin
00000000  04 0c 2d 16 2c 3d 76 cd  47 de e5 84 c9 9e 08 80  |..-.,=v.G.......|
00000010  b4 f2 2a 38 3b 7e bc bb  f6 cc bb 25 4a fe 01 b6  |..*8;~.....%J...|
00000020  dd 37 de ee ee b1 06 9a  af 39 f0 e8 c4 6a f7 ca  |.7.......9...j..|
00000030  53 01 5f 8f 73 7e 57 cc  2b 7a 61 32 35 54 e7 9c  |S._.s~W.+za25T..|
00000040  26                                                |&|
00000041

As you can see, the ethereum address (file address) matches the one from was used to send the ether in the transaction in the beginning of the post.

I generated the keypair like this:

[root .eth]# cat genkey.sh
#!/usr/bin/env bash
openssl ecparam -name secp256k1 -genkey -noout | openssl ec -text -noout > keypair
cat keypair | grep pub -A 5 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^04//' > pub
cat keypair | grep priv -A 3 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^00//' > priv
cat pub | keccak-256sum -x -l | tr -d ' -' | tail -c 41 > address
cat priv | xxd -r -p > priv-bin
cat pub | xxd -r -p > pub-bin
#geth account import priv

So what might be the problem?  Why the recovered public key doesn't match the original public key?


texts:
Could someone please point out what is wrong in this code? It seems that when I call the registerClient() function, it succeeds and returns TRUE. But when I call the getRegisteredClients() method, it always returns 0!!

struct RegisteredCandidate {
    bytes32 ownerID;
    address clientAddress;
}

mapping( bytes32=> RegisteredCandidate) registeredCandidates;
bytes32[] registeredClients; //an array of clients to keep track of numbers

//Just a modifier to restrict calls
modifier ifIssuer() {
            if (issuer != msg.sender){
                  revert();
              }
              else {
                _;
     }
    }

function registerClient(bytes32 _clientID) public returns (bool) {

      //if the clientID is not already present in the map
      if(registeredCandidates[_clientID].ownerID != _clientID) {

          registeredCandidates[_clientID].ownerID = _clientID;
          registeredCandidates[_clientID].clientAddress = msg.sender;
          registeredClients.push(_clientID); //updating the counter array
          return true;
      }

      return false;
  }

    function getRegisteredClients() constant returns (uint) {
        registeredClients.length;

    }

Thanks for any help on this.

One more question to ask: is there a better way to form the same logic?

Thanks.


texts:
I'm trying to test basic web3 with node. I have testrpc running and I have the following in a javascript file:

var Web3 = require('web3');

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

console.log(web3.eth.accounts[0]);

When I run node filename.js it returns undefined. Why is that?

When I change web3.eth.accounts[0] to web3.eth.accounts I get this :

Accounts {
currentProvider: [Getter/Setter],
_requestManager:
 RequestManager {
 provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
 providers:
  { WebsocketProvider: [Function: WebsocketProvider],
    HttpProvider: [Function: HttpProvider],
    IpcProvider: [Function: IpcProvider] },
 subscriptions: {} },
givenProvider: null,
providers:
{ WebsocketProvider: [Function: WebsocketProvider],
 HttpProvider: [Function: HttpProvider],
 IpcProvider: [Function: IpcProvider] },
_provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
setProvider: [Function],
_ethereumCall:
{ getId:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'net_version' },
 getGasPrice:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'eth_gasPrice' },
 getTransactionCount:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'eth_getTransactionCount' } },
wallet:
Wallet {
 _accounts: [Circular],
 length: 0,
 defaultKeyName: 'web3js_wallet' } }


texts:
This is a limitation of an article that proposed a smart contract in healthcare sector:
In Ethereum blockchain, smart contracts are stored on-chain, making
them immutable. However, this poses a major challenge in the development process of smart contracts,
as immutability makes them lack upgradability. Once smart contracts are developed and deployed, they can no longer be modified. Therefore, it is not possible to patch security vulnerabilities or software bugs with an update.
I want to define it as a hypothesis for my dissertation and try to solve it, but I don't know that it could be a good topic or not and it could be solved or not and how could it be solved
Could you please help me and answer this questions?
Thank you in advance


texts: Contract not deploying on blockchain using solc & web3

texts:
I am using the npm package of solc to compile the contracts and accessing it as given here. It is compiling my contracts. But when I try to deploy the contract using

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

as given here. I am doing all this in a JavaScript file. I am running a node locally using geth, and I am accessing it using the web3 httpprovider. When I execute the file, I am getting error as:

D:\Projectfolder\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOve
rrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var
ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_I
S_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!M
odule["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){proce
ss["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["nor
malize"](filename);var ret=nodeFS["readFileSync"](filename);if(!

Error: invalid address
    at inputAddressFormatter (D:\Projectfolder\node_modules\web3\lib\web3\formatters.js:271:11)
    at inputTransactionFormatter (D:\Projectfolder\node_modules\web3\lib\web3\formatters.js:97:20)
    at D:\Projectfolder\node_modules\web3\lib\web3\method.js:89:28
    at Array.map (native)
    at Method.formatInput (D:\Projectfolder\node_modules\web3\lib\web3\method.js:88:32)
    at Method.toPayload (D:\Projectfolder\node_modules\web3\lib\web3\method.js:114:23)
    at Eth.send [as sendTransaction] (D:\Projectfolder\node_modules\web3\lib\web3\method.js:139:30)
    at Object.<anonymous> (D:\FILEPATH\check.js:22:10)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

How do I remove the error?

I tried another contract, changed the line as web3.eth.sendTransaction({from:web3.eth.accounts[0], data: bytecode, gas: 300000} And it's working. But when I try to deploy famous greeter contract using web3 line as: web3.eth.sendTransaction(_greeting,{from:web3.eth.accounts[0], data: bytecode, gas: 300000}It still throws error.

Oh, finally this is resolved. I just needed to add JSON.parse(abiDefinition). Now the greeter contract is also working. This one is deployed using greeterContract.new(_greeting,{from:web3.eth.accounts[0], data:bytecode, gas: 300000}


texts: What is meaning of logical comparison of ethereum address | solidity

texts:
I am reading this smart contract. In that smart contract, they are comparing two addresses.
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);

What is the meaning of comparing two address. On what basis it will return true of false.


texts: What is the difference between an exchange like Coinbase and a wallet like Jaxx, MEW, MetaMask?

texts: What is the difference between storing ether with an exchange (e.g. Coinbase, Kraken, Gemini, Poloniex, Bittrex) and a wallet like Jaxx, MEW, MetaMask?


texts: What is a cheap way to store mnemonic generator list of 1024 words in smart contract?

texts:
What is the cheapest way to store a list of 1024 words for a mnemonic generator, and why?

These ideas had a gas cost of 165720 GAS for a string array, and 42300 GAS for storing all the words in a byte array, 6 byte per word.

contract mnemonicgenerator {

bytes public listBytes;

string[] public listString;

function storeString() {
    listString.push("about");
    listString.push("above");
    listString.push("abroad");
    listString.push("accept");
    listString.push("access");
}

function storeBytes() {
    bytes memory toBytes = new bytes(6*5);
    assembly {
      mstore(add(toBytes, 32), "about")
      mstore(add(toBytes, 38), "above")
      mstore(add(toBytes, 44), "abroad")
      mstore(add(toBytes, 50), "accept")
      mstore(add(toBytes, 56), "access")
    }
    listBytes = toBytes;
}
}

and a bytes6 array costs 104258 GAS

bytes6[] public listBytes6;

function storeBytes() {
      listBytes6.push("about");
      listBytes6.push("above");
      listBytes6.push("abroad");
      listBytes6.push("accept");
      listBytes6.push("access");
}


texts: What happens if there is no fallback function in solidity?

texts:
Here is the short definition about fallback function in solidity:
Solidity fallback function does not have any arguments, has external visibility and does not return anything.

What happens if there is no fallback function and someone calls non-existing function in the smart contract? Is there security complication without a fallback function?


texts: how to create a smart contract that uses ERC20 as way of payment?

texts:
im creating a smart contract that will receive and automatically redistribute erc20 tokens!
how can i implement that in solidity?
i've tried a couple of codes examples but nothing have worked so far!
do anyone know how to do it or can give me hints?
maybe add line to receive the gas in ether and then execute the transfer of erc20 tokens?
could really use some help!


texts: Simple Factory Contract is much Larger than its Child Contract

texts:
I coded a very simple factory contract:
pragma solidity ^0.7.3;

import "hardhat/console.sol";
import "./Pair.sol";

contract Factory{
    mapping(address => mapping(address => address)) public getPair;

    // Creates a pair
    function createPair(address token1, address token2) public{
        require(getPair[token1][token2]==address(0));
        Pair pair = new Pair(token1,token2);
        getPair[token1][token2] = address(pair);
    }
}

Now according to hardhat contract sizer plugin, after compiling, Factory contract size is 43.56 kB while Pair is only 16.61 kB.
Shouldn't factory just be slightly larger than Pair.sol? What am I missing here?


texts: Please provide example for web3.eth.sendTransaction

texts:
I created a contract (in the Ropsten Test Net) for the most basic example described in this article:
http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

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

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

The following Javascript calls that contract:

var abi = [{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}];
var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at('0x51a5846DB9DEb1Cd72ccab36F825C06328a21b8C');

myContractInstance.set.call(1, function(error, result){
    if(!error) {
        console.log("#" + result + "#")
    } else {
        console.error(error);
    }
})

myContractInstance.get.call(function(error, result){
    if(!error) {
        console.log("##" + result + "##")
    } else {
        console.error(error);
    }
})

The "set" call does not work, because it requires "sendTransaction" instead of "call".

I have tried every combination of parameters in web3.eth.sendTransaction, and I continually get the following error message:
"sendTransaction Invalid number of arguments to Solidity function"

I have read the API documentation (https://github.com/ethereum/wiki/wiki/JavaScript-API), which does not provide a good example for web3.eth.sendTransaction.
Please do not provide just a theoretical explanation, or a requirement to install additional tools.

Please provide a specific javascript code example that has been tested, to show how I can use just javascript to execute the "set" function in the contract shown above.


texts: Are mnemonic seeds or hierarchical deterministic wallets standardized?

texts:
Some wallets for Bitcoin and Ethereum will give you a list of about 15 words to write down instead of giving you a private key.

From what I understand, the list of words is derived from the key, and can be used to recreate it.

The question I have, is basically whether or not ALL (or virtually all) implementations of this system are compatible. Imagine I try to recover my wallet using the seed years later on a totally different wallet. Can I be confident it will work. Are all seed mnemonics using the exact same math, and will they likely continue with the same scheme (or a backwards compatible one) decades from now?


texts: What is used for default string value in mapping?

texts:
For example, I have a contract like this:

contract example {
    mapping (uint => string) map;

    function example () {
        map[123] = "123";
    }

    function return1 () returns (string) {
        return map[123];
    }

    function return2 () returns (string) {
        return map[1];
    }
}

When I'll call return1, it obviously returns '123', but what happens on return2?


texts: Why contract is not working on test net but work in remix

texts:
I wrote a solidity contract where one can share a file hash along with the accounts which can have access to the file hash. Sort of a file sharing thing. Just a basic contract, accounts having access control can get the file hash and the rest can't (they get an error message).

I test it on remix first and it is working absolutely fine. But once it is deployed on my ethereum private network, the blockCount variable is not getting incremented. So when I call function getFileHash, it returns "error".

Contract code:

pragma solidity ^0.4.0;
contract hcare

{
    struct block
    {
            string fileHash;
            uint numRecv;
            address[] recvAddress;
    }

    uint i;
    uint recvCount;
    //uint8 public blockCount;
    address owner;
    block temp;
     //a single block
    block[] Blocks; //array of blocks

    event fileUploaded (address sender , uint cnt);

    function hcare()
    {
            owner = msg.sender;

    }

    function addBlock (string fHash, address[] recvAddr) public
    {

            //temp = block(fHash , recvAddr.length , recvAddr);

            Blocks.push(block(fHash , recvAddr.length , recvAddr));
            fileUploaded (msg.sender, Blocks.length);
    }

    function getBlockCount() public constant returns (uint)
    {
        return Blocks.length;
    }

    function getFileHash () public constant returns(string)
    {
            string tempFHash;
            uint ctr=0;
            uint i;
            uint j;

            for (i=0; i < Blocks.length;i++)
            {
                    for ( j=0; j<Blocks[i].recvAddress.length;j++)
                    {
                            if (Blocks[i].recvAddress[j] == msg.sender)
                            {
                                    tempFHash = Blocks[i].fileHash;
                                    ctr = 1;

        //                             if (ctr == 1)
//                                    break;
                             }
                    }
            }
            if(ctr == 1)
            return tempFHash;
            else
            return "error";
        }
    }

Edit1: Replaced the blockCount variable by returning Blocks.length , but still the block length returns zero. From what I can guess, nothing is being added to the structure array.

Edit2: Uploaded a refined version of the code at PasteBin. The main problem of block not adding to structure persists.


texts: Truffle contract bytecode not updating with library address

texts:
After deploying a library using truffle, I want to compile a contract and use the library address inside its generated bytecode. Now inside the contract bytecode I get something like _DateTime______.

I want to be able to integrate truffle inside a web3 blockchain-api, that uses the command contract.deploy({data: bytecode}), but I can not get the library address inside the bytecode, and the request is always crashing.

I am able to do this if I compile manually (using solc) , the library, then get the address and use the flag --link (+ the library address) in the solc command, when compiling the other contract, but I want to find out how to do this automatically using truffle. Thank you.


texts: Encrypted accounts backup and restore from 12 word seed

texts: In my wallet I used ethereumjs-accounts library to generate and manage accounts. It allows to export and import accounts by json string or zip file. My goal is to add to export/import functionality 12-word-seed encryption. If user want to backup accounts, he should write down generated 12 words (or specify it by himself) and next time to export it, he should reenter this words to decrypt backup file. If something doesn't make sense, please let me know.


texts: Truffle - can deploy to ropsten but not mainnet

texts:
I am trying to deploy a contract to the mainnet. My truffle.js looks like this:

require('babel-register')
module.exports = {
  networks: {
    "live": {
      network_id: 1,
      host: 'localhost',
      port: 8546
    }
  },
  rpc: {
    host: "localhost",
    port: 8545
  }
};

I have connected to the mainnet in geth (just with geth and geth attach though I've also tried geth --rpcport 8546 --rpcaddr 127.0.0.1 for example). My blockchain is fully up to date (running eth.blockNumber will show I'm at the latest block or close to it).

Running the following command to deploy my contract:

truffle migrate --network live

Will result in the following error:

  Invalid JSON RPC response: ""

This problem is truffle isn't connecting to the mainnet at all. I've successfully deployed to the ropsten test network using truffle when geth is connected to that, so am not sure why the mainnet isn't working (when deploying to ropsten I have basically the same truffle.js as above except network_id: 3 instead of network_id: 1, and the same command to deploy the contract except with --network ropsten instead of --network live).


texts:
I hope this question isn't too vague, but it would really help me to get some advice on from the community on this subject.

Which testnet is the most suitable for testing of a dapp? Do testnet transactions times vary greatly? Is there any one testnet that is more consistent?  Are testnet faucets generally always available and dependable?


texts: what is the transferfrom event signature?

texts: I am currently writing a code that list all types of transactions in a given contract . my plan is to just check for all logs whether the topics[0] == an event signature of a function. and now i am missing the even signature of transferfrom. does anyone know the exact event signature of that so i can do the keccak hash of it that would be put in the topics[0]?


texts:
It's first time when I tried to make an Ethereum wallet and to make a transfer.
Compared to what I am used with other type of d.currency, this transaction seems to be taking forever.

In almost 24h windows not even 10% of the blocks have been approved. transcation link.

Is there a way to speed up the process or to know an estimate when it will be finished or to just cancel it and return the funds?

Details:

Feed Paid: 0.000441 Ether
Gas Used: 21,000
Gas Price: 0.000000021 Ether (21 Gwei)
Transaction ID: 0x9bd221b2bc305afe020ba9712478d4d3b3f03dba0d683a5f5e9dfe2a6a2cd921
4371658 (7837 block confirmations)

Using MyEtherWallet

Thanks


texts: Accidently sent ERC 20 tokens to an ETH address on Binance

texts: I made a mistake as the wrong address was in my clipboard. Will I lose my tokens?


texts:
I have an array of finite size, say something like uint[100] Arr;.

My question is, if I want to continually push to this array, what happens if it already has 100 uints in it and I push another one? Will I crash? Or will it automatically pop out the first element?

If it does not pop out the first element, am I okay to do something like this:

if (Arr.length == 100) {
    delete Arr[0];
}
Arr.push(new_uint);


texts: Mapping with different datatypes showing on one struct

texts:
is it possible that in I can use a uint and a address that showing on the same struct(Submission) as mapping ? I need something what makes it easy to read out the mapping with a uint (number) and with a address. What could be the best way to do that ? Thank you in advance !
 struct Submission {
    uint id;
    Student student;
    Examiner examiner;
    Thesis thesis;
    // examniner accepts allocation
    bool accepted;
    // examiner finished correction
    bool corrected;
    // examiner marks submission as verified
    bool verified;
}

 // save submission in mapping with id as key
mapping(uint => Submission) public submissions;


texts:
I want to deploy a smart contract with Node-js. I followed this guide but an error occurs where i effort instantiate my smart contract.

app.js:

var Web3=require('web3');
var fs=require('fs');
var solc=require('solc');

var web3=new Web3('ws://127.0.0.1:8545');
var address="0x7c028611F45a40a0ef035416B6bFc405F190990c";
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
for (let contractName in contract_compiled.contracts) {
var contract_byteCode=contract_compiled.contracts[contractName].bytecode;
var contract_abi=JSON.parse(contract_compiled.contracts[contractName].interface);
}
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var gasResult;
var contract=new web3.eth.Contract(contract_abi);

In the last line the error occurs:

Error: You must provide the json interface of the contract when instantiating a contract object.


texts: After a successful geth fast sync, Mist began to sync all the db again

texts:
After 3 days of syncing with geth --fast, finally I got the last block synced
I started Mist and it began syncing again from -3,800,xxx
The DB folders were correctly set - I double checked them. Where is the problem?


texts: API or code to find the current price of a ERC20 compliant token listed on Etherscan

texts: In the web application I am working on , I need to find the current price of an ERC20 token listed on etherscan . How can this be done using code or some etherscan api ? Any help is appreciated.


texts:
I am using Oraclize in a smart contract and want to encrypt my API key. According to http://docs.oraclize.it/#ethereum-advanced-topics-encrypted-queries there is a python script from Oraclize that is used to encrypt text (https://github.com/oraclize/encrypted-queries), and this command should encrypt "YOUR QUERY" for example:

python encrypted_queries_tools.py -e -p 044992e9473b7d90ca54d2886c7addd14a61109af202f1c95e218b0c99eb060c7134c4ae46345d0383ac996185762f04997d6fd6c393c86e4325c469741e64eca9 "YOUR QUERY"

Running that command I get this error:

  C:\Python27\encrypted-queries-master\encrypted-queries-master\tools>python
  encrypted_queries_tools.py -e -p
  044992e9473b7d90ca54d2886c7addd14a61109af202f1c95e218b0c99eb060c7134c4ae46345d0383ac996185762f04997d6fd6c393c86e4325c469741e64eca9
  "YOUR QUERY" File "encrypted_queries_tools.py", line 100 print
  "Please, provide a valid public key" Is the public key given on the
  website incorrect?


texts:
Inside the callback of an event, how do I get the scope outside the function? Specifically, in the following scenario, I want the web3 object:
(using truffle-contracts and web3 1.0 here)

...
const web3 = new Web3(someProvider);

myContract.deployed().then(function(instance) {
    // both ways work
    instance.myEvent({}, function(error, event) {
        // here, I want to use web3
        web3.toAscii(event.args[0])
    })
});


texts: What is the proper pattern to use a temporary variable and ensure it gets stored?

texts:
A contract has a state variable, which is complex. For the example, lets say it is a mapping of structs. Inside a method, I want to access that and store the changes. Like so:

contract FooManager {
  struct Foo {
    uint expiresAt;
    uint balance;
  }
  mapping(address => Foo) public fooIndex;

  public function claimFrom(address minter) public payable {
    require(fooIndex[minter].balance < amount);

    fooIndex[minter].balance += msg.value;
    fooIndex[minter].expiresAt += 1000;
  }
}

In this simple example, the repetition of fooIndex[minter].method is still manageable and readable. But with e.g. child mappings in, say the Foo struct, it quickly becomes tangled and ugly. fooIndex[minter].claimants[msg.sender].balance = msg.value are no exceptions there.

What is the common pattern to DRY this? I can create a memory-variable, like below, but that is not stored. The extra gas for allocating memory, may become an issue if this pattern is repeated, but is proably negligible in most cases.

  public function claimFrom(address minter) public payable {
    Foo memory thisFoo;
    thisFoo = fooIndex[minter];
    require(thisFoo.balance < amount);

    thisFoo.balance += msg.value;
    thisFoo.expiresAt += 1000;
  }
}

I've seen some examples in which, at the end, the memory-variable gets assigned back to the storage variable. Like so:

  public function claimFrom(address minter) public payable {
    Foo memory thisFoo;
    thisFoo = fooIndex[minter];
    require(thisFoo.balance < amount);

    thisFoo.balance += msg.value;
    thisFoo.expiresAt += 1000;

    fooIndex[minter] = thisFoo;
  }

It works, but seems clumsy to me: assigning the wrong thing, or forgetting to re-assign is an obvious mistake to make. It also seems wasteful to me, esp in the case of large structs, in which only the dirty (changed) attributes need to be overridden, and not the entire struct; again, this is more obvious in situations where a struct contains child-mappings with other structs and so on: a tree. I'm not sure, if the compiler can and will optimize this, though.

Did I miss an obvious language construct? Did I misunderstand the storage and memory completely?


texts: Given transaction hash, how to proof that it was a successful erc-20 token transfer using web3?

texts:
I have a transaction hash and an RPC access to fully synced node. How to check if the token was actually moved? The transaction might be old, so there is no point in querying the contract.

If I understand correctly, the transaction from some account to
ERC-20 compatible contract is merely a request for a contract to do
the transfer.
If I lookup transaction receipt for this transaction in the block, it has status field. But, this only means that that no error was raised during execution of the contract.
If I look into events attached to the receipt, I might find a Transfer one but this only means that the contract emitted it, not that a account balance was actually changed.


texts:
I am aware of the following types (as reported by testrpc/ganache & truffle):

VM Exception while processing transaction: revert
VM Exception while processing transaction: invalid opcode
VM Exception while processing transaction: out of gas
VM Exception while processing transaction: invalid JUMP

Are there any other types which I am not aware of?

Thank you!


texts:
I can not figure out how to stop a running geth node without killing the process. I tried to lookup geth help but there is no mention of stopping, halting or any shutdown command.

How to shutdown geth cleanly?

Edit:

I'm running it as a daemon, CTRL+C is no option.


texts:
I had a look at this video
https://www.youtube.com/watch?v=vhdDQXLCRpE

I can send tokens to MyEtherWallet from my exchange. Do I have to withdraw to my public key? Or, can I send it to one of my Ethereum addresses?


texts: What is the max value of gaslimit in genesis.json?

texts:
What is the max number of gaslimit you can set in genesis.json?

I'd like to put lots of data in one block, so I need to set max gaslimit in genesis.json.


texts: How to declare an array of structs as storage variables?

texts:
I do not want to use .push and would like to define a static, const array of struct on top.
  struct Info{
    address a;
    uint256 b;
    uint256 c;
    uint256 d;
}

Info[] public infoArrary = [
{0xabcd,1,2,3},
{0xabcd,1,2,3},
];

It gives me compilation errors. I am a C guy, so please advise.


texts: Unlock account on Ethereum client, or sign every transaction sent it to Ethereum client?

texts:
I have a contract which needs to be updated occasionally.

For this purpose, I set up an Ethereum client, namely, a Parity node.

At this point, I see several ways of carrying out the specified task:

Unlock my account once (i.e., at the Parity node command line or toml configuration file), and then simply send a transaction every time I want to update the contract.
Send an 'unlock-account' request to the Parity node followed by a transaction, every time I want to update the contract.
Sign a transaction and send it to the Parity node, every time I want to update the contract.

Options 1 and 2 are achieved with my account's password, while option 3 is achieved with my account's private key.

Advantages of each option:

No need to send the account's password from my server to the parity node
The account becomes unlocked only when necessary
The account is never unlocked

Disadvantages of each option:

The account is always unlocked
The account is sometimes unlocked, and its password needs to be sent on every transaction
The account's private key needs to be sent on every transaction

Between options 1 and 2, I don't see any reason why to use option 2.

Between options 1 and 3, I am not really sure what is the correct approach.

Sending secret information to the Parity node, whether it's a private key or a password, sounds like it can be easily solved (for example, using HTTPS).

However, leaving an unlocked account on the Parity node also sounds like it can be easily solved by allowing access only to my server (for example, using my servers' IP address).

I have read this answer, which explains how to protect option 1, if this were your choice.

But all in all, it feels like option 3 is the more correct choice.

Am I right, and what other considerations have I missed here?

UPDATE:

Not sure why this question was put on hold, because I was planning to add my practical efforts (i.e., some code) and then put it on bounty.

Here is the code that I have for each option:

Option #1:

let transaction = contract.methods.myFunc();
let options = {
    from: ACCOUNT_ADDRESS,
    gasPrice: GAS_PRICE,
    gas: await transaction.estimateGas()
};
await transaction.send(options);

And in the Parity configuration (toml) file, I added:

[account]
unlock = [0xAccountAddress]
password = ["password.txt"]

Option #2:

let transaction = contract.methods.myFunc();
let options = {
    from: ACCOUNT_ADDRESS,
    gasPrice: GAS_PRICE,
    gas: await transaction.estimateGas()
};
await web3.eth.personal.unlockAccount(ACCOUNT_ADDRESS, ACCOUNT_PASSWORD);
await transaction.send(options);

Option #3:

let transaction = contract.methods.myFunc();
let tx = {
    to: contract._address,
    data: transaction.encodeABI(),
    gasPrice: GAS_PRICE,
    gas: await transaction.estimateGas()
};
let signedTransaction = await web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);

As in the title, my question is - should I unlock the account on Parity (options 1 or 2), or should I sign every transaction sent to Parity (option 3)?

Thank you!


texts: Are there any darkweb stores running ethereum?

texts: First, I don't support sale of illicit items.  Having said that, wouldn't the implementation of ethereum on the darkweb prevent the host from running off with the funds?


texts:
I deployed a private version of Ethereum on my laptop.

I am using this code to deploy:

geth –-identity "blockdb" –-rpc -–rpcport "9040" --rpccorsdomain "*" –-rpcapi "db,eth,net,web3" –-datadir "c:\\blockchain" –-port "30303" –-nodiscover –-networkid 76543 console

and this genesis:

{
"config": {
    "chainId": 76543,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
               },
"difficulty": "0x4000",
"gasLimit": "0x8000000",
"alloc": {}
 }
 }

The blockchain seems to deploy well, since it gives me the same chain ID, i open Mist (without changing an ysettings) and can see the wallets i create. Miner.start() also works. I see the ethers coming in from the mining. I can see the wallets i create andthe minutes since last block. but the status remains always connecting.

My questions are as follows:

1) When i close the console and restart it, to restart the node, i use the above command again. is that correct? Because:

2) when I restart, I can see the wallets previously created but not the ether. the ether is lost. they all restart from 0. why is that?

3) I am trying to interact 'externally' with the blockchain, by using nethereum and ethereum wallet. In both apps I can see the wallets and their balance. but i cannot create new wallets, deploy contracts or transfer ether.


texts:
How can i call second function so that it could return key_Number and key name ?

function TransferKey (address receiver, string _name, uint Key_Number)
    public  {
    name = _name;
    assert (Keys[msg.sender] != 0);
    if(Keys[msg.sender] <= Key_Number)  return;
    //This function is anytime a node wanner send keys
    //It checks if the keys of the sender is less than the Key_Number
    //This code reduces the number of keys in possession of the the sender by one
    Keys[msg.sender] -= Key_Number;
    //This code also increases the address by the number sent
    Keys[receiver] += Key_Number;
    emit sent( msg.sender, receiver,Key_Number);

AND this is function that should return the uint and the string value of the transfer key

    function NumberOfKeysInPossession(address account) public view returns ( uint, string ) {
         //This function return Key_Number of a given account.
         return Keys[account] , keys[_name];
         //It checks the number of keys owned by a particular account.
    }


texts: What if I in theory had the private key to a public contract on the blockchain?

texts: If I in theory had the private key to a public contract on the blockchain. Would I be able to do anything with that key?


texts: How to make mining efficient in terms of memory, for a light weight client?

texts: Since mining is resource intensive process, how to make it more efficient for a lightweight client in terms of memory. I am ready for a trade off even it takes more time to mine than what it would take for a normal client.


texts:
I need an ETH-USD price oracle for my vyper contract. So far, the oracle services I've found, like chainlink, are written in solidity. Is it possible to use a solidity oracle in a vyper contract? How can I do this?

Would I have to build my own oracle?


texts:
In the previous version of Nethereum (1.0.6), I was able to do something like this:

var miningResult = await web3.Miner.Start.SendRequestAsync(200);
Assert.IsTrue(miningResult);

In 2.0.0-rc5 I get an error: Web3 does not contain a definition of Miner
How can I do the same in version 2.0.0-rc5?


texts: Exchange deposits using smart contracts and externally owned accounts

texts:
While researching how different exchanges handle user deposits, I noticed a stark contrast between several prominent exchanges.
Kraken:

Exchanges like Kraken use newly generated deposit addresses (no smart contract)

Bitstamp and Binance:

Exchanges like Bitstamp and Binance have client smart contracts.
In other words, the customer has a dedicated address to deposit all
ERC-20 related tokens to it. This wallet though has to first go
through a smart contract wallet that is owned from the exchange

Bittrex:

Warning - sending ETH to Bittrex is a smart contract invocation..
So here's what I found after a friend asked for help.. When you ask
for deposit address in Bittrex, what happens behind the scenes is that
a new instance of smart contract is created just for you..

Why do some exchanges choose to generate a new deposit address for each customer while others choose to move it through a smart contract first? What are the benefits/drawbacks of each approach?


texts: How dangerous the 'short address' attack is as of 2019, October and what ways there are to mitigate it?

texts:
From what I read there's a well public knowledge of reantrancy and underflows/overflows due to the cases of documented hacks and stolen ether - yet the short address attack seems less known. I know in order to protect against it in my contract I should add something like:

contract okcontract {
    modifier noshortaddress(uint size) {
          assert(msg.data.length >= size + 4);
      _;
}function transfer(address _to, uint256 _value) noshortaddress(2 * 32) {
     // do stuff
}}

So since the attack is dependent on the EVM: is there a fix in the EVM against it or is it still code based? I know an attack like that will be impossible to launch from any credible exchange/wallet since they will not except a "weird" address, in this case: address shorter than 42 characters (0x + the hash, in the case of short address it will be 40 total: 0x + 38 - 00 or maybe even 36: 0x + 36 - 0000 ... etc depending on how lucky one is to generate address with zeroes on the end).

Finally: is it sufficient to just put a withdraw function before the end since the request will be sent into bytes to the EVM and the last byte added will be to some other fuction making it impossible? In other words: contract where after "withdraw" I have say "check-balance" or any other function is safe since no byte added to this will result into address with higher balance?
Thank you!


texts: I tried to get some Kovan ethers, but all the site/faucets I get revered to by MetaMask don't seem to work. Anyone any suggestions or maybe even some spart Kovan Ethers? My address is: 0xa8323F5fBcf1980B2093a633cF03020900B81d53 thanks!


texts: In simple terms, how did the DAO get hacked and funds removed from it?

texts: How did the DAO get hacked? Can someone explain in simple terms?


texts: Is it ok to *not* zero out old mapping keys to save gas?

texts:
I have an escrow from which addresses can withdraw from after a timelock. Each address (1) has a balance, (2) can request to withdraw from at any time, and (3) actually withdraw from at a later date. I have three separate data structures to manage requests and withdrawals:

// mapping(address => mapping(timestamp when funds will be withdrawable => funds)
mapping(address => mapping(uint256 => uint256) private requests;

// mapping(address => array of timestamps at which funds will be withdrawable
mapping(address => uint256[]) private timestamps;

// mapping(address => mapping(timestamp => whether the timestamp has been added to 'timestamps'
mapping(address => mapping(uint256 => bool)) private timestampLookups;

When an address requests a withdrawal, they can call:

function requestWithdrawal(uint256 amount) external {

    // The timestamp at which funds will be withdrawable
    uint256 timestamp = block.timestamp + 2000000;

    // Increment the amount that will become withdrawable for the given timestamp
    requests[msg.sender][timestamp] += amount;

    // Add the timestamp to `timestamps` if not already a member
    if (timestampLookup[msg.sender][timestamp] == false) {
        timestampLookup[msg.sender][timestamp] = true;
        timestamps[msg.sender].push(timestamp);
    }
}

After the lockup elapses, an address can now withdraw its funds by calling the following:

function withdraw(uint256 amount) external {

    // The sum of withdrawable tokens spanning all timestamps
    uint256 amount;

    // Loop over 'timestamps'...
    for (uint16 i = 0; i < timestamps[msg.sender].length; i++) {

        // ... to get the timestamp of each request
        uint256 memory timestamp = timestamps[msg.sender][i];

        // Only proceed if the timestamp has expired
        if (timestamp <= block.timestamp) {

            // Then add the value of the request for the timestamp
            amount += requests[msg.sender][timestamp];

        } else {

            // see below for idea of what to do here

        }
    }

    // Finally, transfer 'amount'
    require(myToken(msg.sender, amount));
}

In the withdraw for loop, I need to loop over timestamps to access the cumulative withdrawable value across all timestamps in requests.

The problem is that I need to confirm the token.transfer succeeds before mutating requests, timestamps, and timestampLookups, which would ideally be done in the for loop.

Rather than iterate over the same data twice, my idea is to create a uint256[] memory newTimestamps inside function withdraw and add the timestamps that have not expired (in the else block). Then, if require(myToken(msg.sender, amount)); returns truthy, simply reassign timestamps[msg.sender] to newTimestamps, at which point the timestamps that have been withdrawn from would be effectively deleted.  If the transfer fails, don't do any reassignment.

Would it be good practice to not zero out values from the other two data structures (requests and timestampLookups) and leave them as is, knowing (1) those keys will never be accessed again and (2) to only and always rely on timestamps as the single source of truth for pending withdrawals?

PS There is logic in these functions to require that there are enough funds in the address' balance for withdrawal that I removed for simplicity.


texts: Contract deployment error : value.forEach is not a function

texts:
This is a simple contract I am trying out with an Ethereum testrpc instance.

pragma solidity ^0.4.11;
/// @title List

// Begin contract defintion
contract List {

    struct ListMembers {
        bytes32 listOwner;
        bytes32[] members;
        uint256 rNumber;
        uint256 aNumber;
        uint256 uNumber;
    }

    ListMembers public lm;
    mapping (bytes32 => bool) public addedMembers;

    function List(bytes32 listOwner) {
        lm.listOwner = listOwner;
        lm.rNumber = 10000;
        lm.aNumber = 0;
        lm.uNumber = 0;
    }
}

And, this is the web3.js code to deploy the contract.

var Web3 = require('web3');
var fs = require('fs');
//
var ethHttpProvider = new Web3.providers.HttpProvider("http://localhost:8545");
var web3 = new Web3(ethHttpProvider);
var abiFile = fs.readFileSync('Lists.abi').toString();
var abiDef = JSON.parse(abiFile);
var byteCode = fs.readFileSync('Lists.bin').toString();
//
var listContract = web3.eth.contract(abiDef);
deployedContract = listContract.new('A',{data: byteCode, from: web3.eth.accounts[0], gas: 4700000});
//

And, this is the error I am getting:

TypeError: value.forEach is not a function

What am I missing?


texts: Does uncle blocks in poa forks contains transactions?

texts:
Since that forks can happen in poa networks (I asked how to prevent forks here);
What does means ? is uncle blocks contains transactions or they are just empty blocks ?


texts: Solidity's address.transfer() function throwing exceeds gas limit error

texts:
I am learning Solidity in order to make a simple user interface in which users can purchase items and have ether sent from the purchaser to the Store.

First, I have created one contract, one for the store and one for the purchaser.

pragma solidity ^0.5.0;

contract ShoeStore {
    function () external payable {

    }

    function getBalance() public view returns (uint) {
        return msg.sender.balance;
    }
}

contract StorePurchase {

    ShoeStore private _instance;

    function Store() public {
        _instance = new ShoeStore();
    }

    function getBalance() public view returns (uint) {
        return msg.sender.balance;
    }

    function sendEther() public payable {
        require(msg.sender.balance > 100);
        address(_instance).transfer(2);
    }

    function () external payable {

    }

First, I instantiate the ShoeStore contract within the StorePurchase contract so I can attain the address that the purchaser is to send to. Then, using the .transfer() function, I send 2 ether to the ShoeStore contract. However, I am getting an "Exceeds gas limit" error and I am unsure as to why I am exceeding the gas limit.

Perhaps, there is a design flaw in constructing the two contracts (I don't need to make security too much of a priority, I just need to make sure these transfer methods work). Or if someone can point me out to another resource that shows a simple way to transfer ether to one contract to another that would be helpful.


texts: Can I download the whole blockchain from somewhere?

texts:
Bitcoin used to offer sharing/downloading a bootstrap.dat which contains the whole blockchain.

Are there alternatives to getting it trickling through the peer-to-peer network? Can I just download it somewhere? Wouldn't this be ideal for distribution via torrent?

If so, how do I import it into the Ethereum client?

My client would still be validating this data (can it?), and it is all signed and proof-of-worked, so there is no real security problem here, is there?


texts:
In Ethereum, when a node ‘broadcasts’ a transaction or block, what algorithm is used to broadcast that transaction or block to all the nodes? Also, how does this algorithm discover peers? What are some resources I could use to learn about this algorithm and its use in Ethereum?

Note:
This is not the same question as mine. Mine is much more in-depth.


texts: Difference between Ethereumj and Web3j and how to connect private Ethereum network

texts: I want to develop a Spring MVC web application that use a private Ethereum network and I feel confused witch API to use Ethereumj or Web3j. I'd like to know the difference between them and how to connect my local blockchain.


texts: Truffle: calling a contract function with another contract as parameter

texts:
I am testing a token vesting contract with truffle(from openzeppelin). To release tokens you call TokenVesting.release(ERC20Basic token).

const tokenAddress = await ico.token.call();
var token = ERC20Basic.at(tokenAddress);

const vestingAddress = await ico.vestingAddress.call();
var vestingContract = TokenVesting.at(vestingAddress);

await vestingContract.release(token);

This gives me the error "Error: Invalid number of arguments to Solidity function". Any ideas?

Edit: full release signature

/**
 * @notice Transfers vested tokens to beneficiary.
 * @param token ERC20 token which is being vested
 */
function release(ERC20Basic token) public {
  uint256 unreleased = releasableAmount(token);

    require(unreleased > 0);

    released[token] = released[token].add(unreleased);

    token.safeTransfer(beneficiary, unreleased);

    emit Released(unreleased);
 }


texts:
Is it possible to use the Geth Console and turn off syncing entirely?

If there is a JS command or another way to make the Geth Console turn off syncing entirely while still being able to use the console commands for testing purposes I would be interested in knowing how to do it.


texts:
As suggest in What is topics[0] in Event logs? I am trying to find out 'Event hash' but it's not matching the output for below transaction.

Input Data

Function: transfer(address _to, uint256 _value) ***

MethodID: 0xa9059cbb
[0]:0000000000000000000000000d2b2fb39b10cd50cab7aa8e834879069ab1a8d4
[1]:0000000000000000000000000000000000000000000000000000010e6a06cb00

Event Logs

Topics
[0] 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
[1] 0x0000000000000000000000004dc8f417d4eb731d179a0f08b1feaf25216cefd0
[2] 0x0000000000000000000000000d2b2fb39b10cd50cab7aa8e834879069ab1a8d4

However when I try to find the keccak hash it's showing different hash.

  from Crypto.Hash import keccak
  keccak_hash = keccak.new(digest_bits=256)
  keccak_hash.update("transfer(address,uint256)")
  print keccak_hash.hexdigest()

>>a9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b


texts:
What I do?.

Download logs and collect address
Use address to getBalance
Result make a hodler table

Result

Too much generate request to infura

Question
Is any function/method to make a one request?
Snippet
logs, err := app.CallLogs(context.Background())
    for _, vLog := range logs {
        go func(log types.Log) {
                ....
                ether := GetUserBalance(app.instance, transferEvent.To.String()) // Generate TOO much request
                if err := hodler.InsertOrUpdate(ctx, client, transferEvent.To.String(), ether); err != nil {
                    logger.Error(err)
                }
            }
        }(vLog)
    }


texts: solc.compile() @0.5.0 is not working like 0.4 version

texts:
I read the solc document and followed the instruction.
When I am using solc@0.4.24 version, compile command is working fine

solc.compile(smartContractPath, 1);

When I switched to solc@0.5.0 version, compile command throwing error

  (function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath"normalize";var ret=nodeFS"readFileSync";i

  AssertionError [ERR_ASSERTION]: Invalid callback specified.

In the solc documentation it is not mentioned about the changes in compile command.
Please tell how to use .compile function in solc@0.5.0 version.


texts:
I start my geth node with --maxpeers 50 but have never been able to go above ~15 peers when peercount is queried.  I noticed in the Network Activity monitor there are connections that are being constantly cycled through with very little network activity.  They appear and disappear without ever much traffic in the send and receive columns.
I've opened TCP and UDP 30303 and UDP 30301 through my firewall.  UPNP is also enabled on my router.  What else could it be?


texts: Is it possible to write a contract where exchange happens in an offline (no Internet) LAN environment

texts:
Is it possible to create a contract to broke an exchange/transaction between two parties where the two parties may or may not be connected to the internet when the transaction occurs, and they may not reconnect to the Internet after the transaction. How will the network verify such transaction if such transaction could be done?

For example:

Suppose Alice and Bob makes a contract where they could at a future time they could make some transaction at a later time (They are not in an offline environment when the contract is broke). Neither Alice and Bob are obligated to make a transaction, but if Alice and Bob could talk to each other in a p2p manner without Internet (perhaps HTTP in a LAN for instance), they should be able to perform such transaction. Is it possible for Alice and Bob to make such transaction if neither of them has access to the Internet and the main Ethereum network? What strategy do I have to make this possible if I assume neither Bob nor Alice has access to the Internet, and neither of them will reconnect to the Internet/could access the Ethereum network after the contract has been broke.

If such transaction isn't possible (my intuition tells me that it isn't), is it possible in a case, where either Alice or Bob connects to the Internet perhaps, after the transaction take place. If only Alice connects to the Ethereum network, how does the network verify that what Alice said was true, that Bob did indeed initiate the transaction with Alice, even though Bob will probably never connect to the Ethereum network.


texts: Accessing array elements with inline assembly

texts:
Using a loop in inline assembly compared to a regular solidity for loop saves around 20% in gas cost.

I'm struggling however with looping over an array through inline assembly. Is this possible and if so, how?

Many thanks.

pragma solidity ^0.4.21;

contract Loop {
    uint[] array = [1, 2, 3, 4, 5];

    function returnNthElement(uint _index) returns (uint) {
        assembly {
            let index := _index
            let length := mload(sload(array_slot))
            for
               { let i := 0 }
               lt(i, length)
               { i := add(i, 1)}
           {
               //How to return element at index '_index' ?
           }
        }
    }
}


texts: Different between gas and gasLimit keys when executing transactions

texts:
Below is the code that I'm running. When I entered "gas" and "gasLimit" as the keys, both worked. Why is that? What does "gas" represent? And what is the optimum amount of gasLimit should I use (ethgasstation.info is currently recommending "Gas Used: 21,000").

smartContract.methods.transferFrom(walletAddress, recipientAddress, tokenId.send({
        from: walletAddress,
        gas: 4700000,
}, function (err, transactionHash) {

    if (!err) {
            console.log(transactionHash + " success");
    } else {
            console.log(err);
    }

});


texts: What happens when you change an array connected to a mapping in solidity?

texts:
I have a mapping

mapping(address => BetByUser[]) betsByAddress;

What happens when I change an object in BetByUser array, or push something to the array? Will it also change the mapping?


texts: Gas price to deploy contracts in ETC Mainnet

texts:
What is the standard Gas price to specify while deploying contracts in ETC mainnet?
We can always reference ethereum gas station when it comes to ethereum network. But is there any trusted source like ethereum gas station for the ETC network?
Can anyone help me with how much to specify to perform transactions smoothly in ETC?


texts: How do I withdraw Ether from my Chainlink node

texts:
I'm running a chainlink node on mainnet. My chainlink node has an ether balance I would like to withdraw, but I'm not sure how to find the private key for the node wallet.
I know that the tempkeys folder generated in ~/.chainlink is important, but even after reading the contents (using sudo vim), I still cannot understand where the private key is.
Thanks!


texts: Are all nodes 'mining' nodes in a PoA network?

texts:
I now have my PoA network running and I can add nodes which are approved by the others. But I have a question about can we add read only nodes?

I do not really understand the different types of nodes in PoA but can we add a node which does not need any proposing process under clique.propose?


texts: Why OpenZepplin always use private visibility for state variables?

texts:
Why OpenZepplin always use private visibility with getter functions for its state variables? I can't find a reason why they are not using public, is there any potential security or gas cost difference when using private instead of public?
    mapping (address => uint256) private _balances;

mapping (address => mapping (address => uint256)) private _allowances;

uint256 private _totalSupply;

/**
 * @dev See {IERC20-totalSupply}.
 */
function totalSupply() public view returns (uint256) {
    return _totalSupply;
}

/**
 * @dev See {IERC20-balanceOf}.
 */
function balanceOf(address account) public view returns (uint256) {
    return _balances[account];
}

This pattern is repeated in all their contracts:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts


texts: How to look up IPFS url in Ethereum Bytecode meta data

texts:
I have a solidity contract that is deployed on the Ethereum mainnet. The contract's bytecode ended with (what I assume to be) an IPFS url
{ipfs}64736f6c634300060c0033
How do I look up this URL on ipfs? It doesn't seem to be in the correct format currently to be searchable


texts: I'm looking for one or more possibly open source Ethereum smart contracts that have been tested and perform some useful use case.


texts: Contracts calling other contracts - setting 'from' field?

texts:
I'm aware a very similar question exists - but I feel my use case is sufficiently different to warrant a new question.

I have two instances of the following contract Own...

contract Own {
    address public owner;

    function Own(){
        owner = msg.sender;
    }
    function transfer(address to){
        if (msg.sender != owner) throw;
        owner = to;
    }
}

I want to write another contract that takes the transaction hashes of the above contract, and swaps the owner of the contract with each other through two calls to the Own.transfer(address) function.

I thought it would be something like the following, but the syntax is incorrect around the o1.transfer(p2,{from:p1});...

contract Tx {
    address public p1;
    address public p2;
    Own public o1;
    Own public o2;

    function Tx(address ownAddress){
        p1 = msg.sender;
        o1 = Own(ownAddress);
    }
    function participate(address ownAddress){
        p2 = msg.sender;
        o2 = Own(ownAddress);
        o1.transfer(p2,{from:p1});
        o2.transfer(p1,{from:p2});
    }
}

For note - both Own & Tx contracts are within the same .sol file, so have knowledge about each other.


texts: Updating ERC20 Contract from 0.4.0 to 0.6.0

texts:
Im updating some ERC20 contact code from solidity 0.4.0 to 0.6.0 and hitting some snags as it seems openzeppeling has changed its structure since then as can be expected.

I cant access the balances variable from the ERC20 contract to update the owners balance in the contructor as the OZ ERC20 balances variable is now set to private as is the _totalSupply variable - how do I set these values in the parent OZ contracts or am I doing this all wrong

    pragma solidity <=0.6.0;

    import "openzeppelin-solidity/contracts/math/SafeMath.sol";
    import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";

    contract Token is ERC20 {

        string public name = "test";
        string public symbol = "TST";
        uint8 public decimals = 18;
        uint256 public initSup = 1000;

        constructor() public {
            _totalSupply = initSup;
            balances[msg.sender] = initSup;
        }

    }


texts:
Because EVM cannot watch events, we cannot send a token to an exchange and immediately get back some other token (EVM just does not "know" when it was send a token). As far as I understand, this is the reason why all exchanges I know require first create a wallet on the exchange site and first send the token to this wallet.

Then:

How do exchanges create a wallet? How does the exchange generate the wallet address? (We know that Solidity cannot generate random numbers. Is it done off-chain?)
How then the exchange could control this wallet, i.e. give it the "command" to send the token for the actual exchange operation? (E.g. if it is ERC-20, then the exchange could not control the token contract and so could not cause it to send the token for the exchange operation. If it is say an ERC-721 or ERC-1155, then the exchange also can't control the contract and the same trouble arises.)

So, I don't understand how exchanges work internally.


texts: Invalid BigNumber Value Uniswap and Ethers JS

texts:
Hey guys I am using the Uniswap Javascript SDK and Ethers JS to make a swap but I am getting this
Error: invalid BigNumber value (argument="value", value=[-626648004,3158], code=INVALID_ARGUMENT, version=bignumber/5.1.1)

This is my code:

            await window.ethereum.enable();
            let provider = new ethers.getDefaultProvider('ropsten');
            const signer =  (new ethers.providers.Web3Provider(window.ethereum)).getSigner();
            console.log(provider.network.name);

            const amountIn = '1000000000000000000'; // 1 WETH

            const accounts = await ethereum.request({ method: 'eth_requestAccounts' });

            const DENT = new Token(ChainId.ROPSTEN, "0xa51f5e00b3a454ba56c4add590d5cfeb2d197ae0", 8);
            const pair = await Fetcher.fetchPairData(DENT, WETH[DENT.chainId]);

            const route = new Route([pair], WETH[DENT.chainId]);
            console.log(route.midPrice.toSignificant(8));

            const trade = new Trade(route,  new TokenAmount(WETH[DENT.chainId], amountIn),  TradeType.EXACT_INPUT);

            const slippageTolerance = new Percent('50', '10000');  // 50 bips, or 0.50%

            const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw; // needs to be converted to e.g. hex
            const path = [WETH[DENT.chainId].address, DENT.address];
            const to =  accounts[0]; // should be a checksummed recipient address

            const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 minutes from the current Unix time
            const value = trade.inputAmount.raw;  // // needs to be converted to e.g. hex

            const account = signer.connectUnchecked(provider);

            const uniswap = new ethers.Contract('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',['function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)'], account);
            const tx = await uniswap.swapExactETHForTokens(amountOutMin, path, to, deadline, {value: value, gasPrice: 20e9});

I tried using the  ether's BigNumber constructor but I still got the same error. Does anyone know what's going on?


texts:
Yesterday Dec 6th 2017 the number of Ethereum accounts grew to 13.4 million. The size of the chaindata of a pruned Ethereum node is now, depending on the mode, somewhere between 25 and 40 GB?

As more and more apps meant for global use rely on users to have cryptocurrencies and tokens, the number of Ethereum accounts can start to approach that of Internet users in general.

How big even the pruned node will grow if we have like 1 billion plus accounts? Proportional growth from 35 GB / 13.4M accounts node size would give 2.6 TB node size.

Not trying to invoke FUD, just asking?


texts: Can we make N+1 block as a genesis block by deleting orignal genesis block?

texts: I want to know that can we delete the genesis block and make the next block as the genesis block as it can save lot's of space and it can be used everywhere in all kinds of industry.


texts:
I'm exploring ways to enable contracts/dApp owners to pay for gas on behalf of users.

I know contact abstraction should enable this eventually, and the first step has been done with EIP208 which introduces NULL_SENDER, but I'm interested in what can be done now.

From what I've seen here on StackEchange and elsewhere, it all comes down to two options:

1. Refund users after they perform a transaction

This is actually not an option :) because I want users not to touch ETH, they don't even need to know that ETH exists.

2. Collect signed TXs/messages from users and forward them to the blockchain (and pay for gas, of course)

This is a valid solution, but the big problem is that users need to trust the dApp owner/message handler to forward their messages. I've stumbled upon uPort's meta transactions and their concept of multiple relayers is somehow appealing, but it's not clear how are relayers incentivized to forward TXs/messages and pay for gas? I've send uPort team a message, waiting for the answer... Ethereum Alarm Clock is a great project and something similar can be also implemented for the problem I'm talking about, but there are no guarantees that TXs will be executed.

Regarding all of this, I have two questions:

Is there any way/idea to do this forwarding in a trustless way now, when we still don't have account abstraction)?
Can anyone explain how this will work when account abstraction gets implemented?

Thanks! :)


texts: Decentralized Identifier - DID method Registration

texts:
I am trying to register a new DID method like 'DID:mymethod' for my specific use cases. I am planning to register this new method under the Ethereum Blockchain. But, I am not sure who do I approach for this registration process. For example, should I contact Ethereum Community for this registration or should I contact the W3C community?
I have already gone through the below links:
1. https://www.w3.org/TR/did-spec-registries/ - Though this link covers the list of currently present DID methods, it does not specify how this may be registered. The only registration process this link talks about is if we want to register new parameters for the DID document.
2. https://www.w3.org/TR/did-core/ - Mainly talks about how a method should work but not about how they may be registered.
Thanks in advance


texts: Function with returns compiles without return statement

texts:
I was surprised to find out that the returns clause in function declaration seems not to be enforced. That is, the following code compiles in browser-solidity (foo returns 0 when invoked):

pragma solidity ^0.4.4;

contract TestContract {
    function foo() returns (uint) {
        uint b = 3+5;
        //return b;
    }
}

Isn't it supposed not to type-check if the function that is declared to return something in fact does not? What is the rationale behind this design decision?


texts: Remix erc20 contract totalsupply shows 0

texts:
I create this contract using Remix.

When I call to totalsupply,it shows 0.

What am I doing wrong? Any help is much appreciated.


texts: redirecting value received to another erc20 wallet

texts:
How can I redirect any value/tokens sent to an ERC20 wallet, to another wallet?  I heard of a new method of stealing currencies and would like to know how it works in practice. Basically, the bad guy spreads the privatekey everywhere on the web and funds the associated wallet with some tokens. Victims will then try to empty the wallet through the privatekey but the wallet has no GAS and any GAS sent to it is redirected to another wallet.  So all the thief has to do, is to spread the privatekey around and wait for victims to take the bait.

 How would a contract like this look like?


texts: Why Send Transaction is Error 'exceeds block gas limit'?

texts:
Why can't I send Ethereum with a code like this :

const Web3 = require('web3')

const provider = new Web3.providers.HttpProvider('https://provider')
const web3 = new Web3(provider)

const account = web3.eth.accounts.privateKeyToAccount('privkey is here')
let coinbase = account.address
web3.eth.accounts.wallet.add(account)
web3.eth.defaultAccount = coinbase

web3.eth.sendTransaction({ from: coinbase, gas: 200000000, to: 'address send', value: (1 * (10 * 18)) }).then((receipt) => { console.log(receipt); }).catch((error) => { console.error(error); });

At show log like this :

  Error: Returned error: exceeds block gas limit


texts: How to compress data for cheapest storage reads?

texts:
Increasing gas costs in Eth and increasing storage operation gas cost (also see eip 2929) triggers another research to find cheaper ways to compress data into single storage slots (32 bytes) while optimising for cheaper sload.
I will share my own experiments in an answer below, but am still looking for better solutions. So this is an open question from my side.


texts: I am trying to find a way to do encryption in solidity.I have a string and I want to encrypt it using some key. Can we do it in solidity?


texts:
I want to add data in Quorum that are visible only to specific users,

how could i implement that ?

Thank you


texts: Using Trezor, My list of tokens is gone and my alt coins do not appear in myetherwallet.

texts: Hi Guys I hope someone can help me. Using Trezor and myetherwallet for sending and receiving ETH and other ERC20 tokens. Successfully using for months. I opened my "View wallet info" today and the entire list of tokens are gone. Token balances are gone, drop down on "amount to send" only shows ETH. (NOte all my ETH is still there but I am unable to see, send or figure out what happened to all of my ERC20 tokens. I have a bunch of different tokens I have been trading. Any advice please?


texts: How to forward returned bytes from calls executed with assembly?

texts:
I would like to make an external call with assembly, but am having trouble retrieving the return data as "bytes". The code below currently returns only 32 bytes, which just shows the length of the returned data, but not the actual byte array. Also, it seems that I need to return outside of the assembly code lines, since the return in assembly will halt execution entirely and return.
How can I copy the return data from the assembly call to the bytes object "data" which is instantiated outside of the assembly lines?
function extCall(address calledContract, bytes memory callData) internal returns (bytes memory) {
        bytes memory data;
        assembly {
            let success := call(gas(), calledContract, 0, add(callData,0x20), mload(callData), 0, 0)
            if eq(success, 0) {
                revert(0, 0)
            }
            mstore8(data, returndatasize())
            returndatacopy(data, 0, returndatasize())
            // cannot return in assembly: execution will halt.
        }
        return data;
    }


texts: How to dynamically generate a variable without declaring it in a contract (solidity)

texts:
Is it possible to generate a non-local variable with a function?

Weird question but it's for an exercise my senior asked me to do, I've scoured the web for an answer to no avail.

Instead of declaring the variable:

contract MetaCoin{
 uint counter=0;
}

Maybe do something like:

contract MetaCoint{
function createCounterVariable(){
  //creates counter variable
 }
}

It will be functionally identical to the declaring the variable, and other functions can access the generated variable somehow. At least this is how I interpret what I'm supposed to do.


texts:
Here is the function in question :

function WithdrawDividend(address, uint256 value) public {

  require(value <= _balances[msg.sender]);

  if (!RestrictedFromDividend[msg.sender]) {

    _SavedDividend[msg.sender] =
    _balances[address(this)].mul(value).div(100000000);
    uint256 DividendsToBurn = _SavedDividend[msg.sender].mul(10).div(10000);
    uint256 DividendstoDividend = _SavedDividend[msg.sender].sub(DividendsToBurn);

    _balances[address(this)] = _balances[address(this)].sub(DividendstoDividend).sub(DividendsToBurn);
    _balances[msg.sender] = _balances[msg.sender].add(DividendstoDividend);
    _balances[address(0)] = _balances[address(0)].add(DividendsToBurn);

    emit Transfer(address(this), msg.sender, DividendstoDividend);
    emit Transfer(address(this), address(0), DividendsToBurn);

    _SavedDividend[msg.sender] = 0;

    RestrictedFromDividend[msg.sender] = true;

    ClaimTime[msg.sender] = now;
  }
}

When I use this function here to check whether or not a person is RestrictedFromDividend or not :

function AmIRestrictedFromTheDividend(address) public view returns (bool) {

  if(!RestrictedFromDividend[msg.sender]){

    return false;

  } else {

    return true;

  }
}

I get 'false' returned everytime, even after immediately using the WithdrawDividend function.

RestrictedFromDividend is removed using the following function, if that helps:

function MakeEligible(address) public {

  if (now >= ClaimTime[msg.sender] + 30 minutes){

    RestrictedFromDividend[msg.sender] = false;

  } else {

    RestrictedFromDividend[msg.sender] = true;

  }
}


texts: Passing a struct to a function gives TypeError: Internal or recursive type not allowed

texts:
I am trying to pass in a struct to the constructor of a contract but am getting the error

TypeError: Internal or recursive type is not allowed for public or external functions

The contract is

pragma solidity ^0.4.0;

contract Writer {

  struct Paragraph {
    string[] lines;
  }

  struct Essay {
    Paragraph[] paragraphs;
  }

  Essay[] private essays;

  function Writer(Essay initialEssay) {
    essays.push(initialEssay);
  }

}

I did some digging and it seems the issue is not actually to do with the struct being defined within the contract (where else would it be defined after all) but with the nested array, so I changed it to

contract Writer {

  struct Paragraph {
    string sentances;
  }

  struct Essay {
    string title;
    Paragraph[] paragraphs;
  }

  Essay[] private essays;

  function Writer(Essay essay) {
    essays.push(essay);
  }

}

but now I get

InternalCompilerError: Static memory load of more than 32 bytes requested.

So then I tried this way, manually constructing the struct.

contract Writer {

  struct Paragraph {
    string sentances;
  }

  struct Essay {
    string title;
    Paragraph[] paragraphs;
  }

  Essay[] private essays;

  function Writer(string title, string[] _paras) {
    Paragraph[] storage paras;
    for (uint256 i = 0; i < _paras.length; i++) {
        Paragraph memory para = Paragraph(_paras[i]);
        paras.push(para);
    }
    Essay memory initialEssay = Essay(title, paras);
    essays.push(initialEssay);
  }
}

which gives

UnimplementedFeatureError: Nested arrays not yet implemented.

Should I perhaps ditch using a struct and instead define a new contract to represent an Essay?


texts:
I am relatively new to Ethereum, and i want to know exactly how to migrate to quorum. And by that i mean migrate exisiting contracts.

I also want to know about the how to start with quorum and if there are any tutorials, outside the official ones, of course.


texts: Is it possible to have a pointer to stored data from an past block?

texts:
The motivation behind this question is the need to take a snapshot of a large mapping object in a cheap way. Basically I'd like to copy or have a reference to a large mapping from one contract to another without spending too much gas.

Is it possible to have a pointer to another contract's public state variable from a specific block number?

What would this look like in Solidity?

If it's not possible in Solidity, would it be possible in assembly?


texts: How does ethereum's core functionalities work?

texts: Does ethereum's blokchain use a smart contract for it's core functionalities of transferring ether? If not then how does it work?


texts: Creating Initial ERC721 Tokens Programmatically

texts: I'm interested in minting 100 unique tokens in the constructor of a smart contract, but I'm having an issue where the minting function hasn't been defined yet while the constructor runs.  Do I have to deploy the smart contract first, then manually run the mint function 100 times?  Is there a programmatic way to solve this?


texts:
New to mining. I am trying to figure out how to use lolMiner on Ubuntu 20.04. Here are the specs of my GPU:
  *-display
       description: VGA compatible controller
       product: Ellesmere [Radeon RX 470/480/570/570X/580/580X/590]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:06:00.0
       version: ef
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller bus_master cap_list rom
       configuration: driver=amdgpu latency=0
       resources: irq:62 memory:e0000000-efffffff memory:f0000000-f01fffff ioport:e000(size=256) memory:fcf00000-fcf3ffff memory:c0000-dffff

When I try to enter into lolMiner, I get this error:
+---------------------------------------------------------+
|  _       _ __  __ _                   _   ____  ____    |
| | | ___ | |  \/  (_)_ __   ___ _ __  / | |___ \| ___|   |
| | |/ _ \| | |\/| | | '_ \ / _ \ '__| | |   __) |___ \   |
| | | (_) | | |  | | | | | |  __/ |    | |_ / __/ ___) |  |
| |_|\___/|_|_|  |_|_|_| |_|\___|_|    |_(_)_____|____/   |
|                                                         |
|              This software is for mining                |
|              Ethash, Etchash                            |
|              Equihash 144/5, 192/7, 210/9               |
|              BeamHash I, II, III                        |
|              ZelHash     (EquihashR 125/4/0)            |
|              Cuck(ar)oo 29                              |
|              Cuckaroo   30 CTX                          |
|              Cuckatoo   31/32                           |
|                                                         |
|                                                         |
|             Made by Lolliedieb, April 2021              |
+---------------------------------------------------------+

Setup Miner...
No OpenCL devices found in your system. Closing lolMiner.

Does using lolMiner or any miner for that matter not allow you to use any Radeon RX GPU's?
I tried finding resources to help me but I am diving into rabbit holes with not getting anywhere with figuring it out.


texts: Transfer ownership of specific mapped array to a different address

texts:
I have this contract with a mapped array of the struct Item linked to a specific address. I want to transfer a specific array in Item[] to a different owner/address. What is the best way to achieve this?
contract Linked {

    struct Item {
        address owner;
        string qrcode;
    }

    mapping(address => Item[]) public userItems;

    function addItem(string memory _qrcode) public {
        Item memory item = Item(msg.sender, _qrcode);
        userItems[msg.sender].push(item);
        items.push(item);
    }

    function transfer(string memory _qrcode, address _newOwner) public returns (bool success){
       //find the row with the qrcode and transfer to another owner
    }
 }


texts: How to retrieve the Contract account balance in web3 or in geth command line?

texts:
I have created a private network with miner node using Ethereum. Then I deployed an Ethereum smart contract in the network. I have got the contract address as "0x045bfe22453a9ca06aff4bdc5d7f5870eba121bd"

Now from my eth.coinbase I would like to transfer some ethers to the contract account.

After unlocking the account, I used the code

  eth.sendTransaction({from:eth.coinbase,to:"0x045bfe22453a9ca06aff4bdc5d7f5870eba121bd",value:web3.toWei(3,"ether"),gas:'1000000'});

After doing this, I have checked for eth.pendingtransactions, those got mined and added to blocks.

I debugged the transactionReceipt, could not able to get the data anything.

How to get the balance in contract account?


texts:
I have started Sync of ETH node to my VPS. I want to call RPC Call to get balance details of addresses. What i have done is as below:
1) Install geth started geth service
2) geth --fast --rpc

After few hours i have stopped geth sync and add some peers using admin.addPeers() method

Again start geth sync using below command on specific port

geth --syncmode light console --rpc --rpcport 3000

after this i have fired admin.peers it shows empty Array so i have add some peers and then check using admin.peers below is the image of admin.peers

Now i am still not able to call RPC Call on my IP 5.101.139.166:3000
I am getting error

Error: Couldn't connect to server
Here are some additional things that may help.

Documentation  Contact Support
Loading...
Cancel Request
Unknown Response Code0.000 milliseconds
Read
Current Status of Node sync is as below

Error while calling RPC Call


texts:
I'm syncing my geth client with ropsten testnet and just realized how slow is the syncing process after a certain block(trying to retrieve information from blocks that got in blockchain yesterday) for a couple of hours.

Basically I got several messages like this one, saying a potential rewrite attack:

I0111 08:28:09.783928 eth/downloader/downloader.go:723] Peer 7335842dc6658f60 [hs 0.00/s, bs 0.00/s, rs 0.00/s, ss 0.00/s, miss    0, rtt 13.155759485s]: potential rewrite attack: #224778 [00000000�] <= #224778 limit

My question differs from this question as I'm not yet synced as I've checked out. One of the answers there doesn't apply here as I made sure I referenced the ropsten genesis block and checked the hash of that genesis block in my local database to certify I'm running to get in sync with the right network. So, I don't believe the cause of this high delay in my node syncing process isn't actually the addition of old morden to my local database.

Is this behavior expected when syncing? Is there any way to maximize the peer coverage to speed up the whole process if comes to that?


texts: Watching Solidity event gives error: TypeError: watch is not a function

texts:
I am trying to watch a Solidity event in my React app, but I keep getting the following exception error thrown:

TypeError: MyEvent.watch is not a function

I am sure the event is present in MyContract.json. Here is what my code looks like:

componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();

      // Get the contract instance.
      const Contract = truffleContract(MyContract);
      Contract.setProvider(web3.currentProvider);
      const contractInstance = await Contract.deployed();

      // Watch for MyEvent
      contractInstance.MyEvent().watch((error, result) => {});

    } catch (error) {
      console.log(error);  // always gives: TypeError: contractInstance.MyEvent(...).watch is not a function
    }
  };

And this is how MyContract.sol code looks like:

pragma solidity ^0.4.24;

contract MyContract {
    event MyEvent();

    function myFunction() public {
        emit MyEvent();
    }
}


texts: Uint to Bytes32 conversion -- how does this make sense

texts:
Pretty simple code here:

pragma solidity ^0.4.13;

contract Oracle{
    event Print(string _name, bytes32 _value);
    bytes32 key;

    function Store(bytes32 _key) returns (bytes32) {
        key = _key;
        Print("Key",_key);
        return _key;
    }

}

Now I'm trying to store the value 1 as a key.

Using remix,

entered key: 1
printed key: 0x0100000000000000000000000000000000000000000000000000000000000000

entered key: "0x01"
printed key: 0x0100000000000000000000000000000000000000000000000000000000000000

Now a weird one:

entered key: "0x1"
printed key: 0x0100000000000000000000000000000000000000000000000000000000000000

And also weird:

entered key: "1"
printed key: 0x3100000000000000000000000000000000000000000000000000000000000000

And also super weird...when using NodeJS to push a raw transaction:

Entered:1
Printed key: 0x1000000000000000000000000000000000000000000000000000000000000000

So the question, why does "0x1" and "0x01" and 1 all give me the same answer on remix and not on node?  And why is 1 when in quotes something different?


texts: My Private key from myetherwallet.com was stolen

texts: My private key (from myetherwallet.com) was stolen by hackers. Can I change it?


texts: Clarification on multiplication from modular exponentiation precompiled contract

texts:
I'm trying to understand what exactly Vitalik means in the following (from here):

  Note that adding precompiles for addition and subtraction is not required, as the in-EVM algorithm is efficient enough, and
  multiplication can be done through this precompile via a * b = ((a + b)**2 - (a - b)**2) / 4.

My understanding is that this is a more efficient way of performing the multiplication, but what exactly is to be passed to the modexp contract in order to achieve multiplication? is it the squaring of (a+b) and (a-b)? And in that case, what should be passed as the modulus value?