texts: Error: Provided address "[object Promise]" is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can't be

texts:
i want to use the 'set' function ,but the console tell me that i have a wrong ,it also can say that 'set is not a function ',you can see this :

import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";
import "./App.css";

var simpleinstance ;

class App extends Component {
  state = { storageValue: 0, web3: null, accounts: null, contract: null };

  componentDidMount = async () => {
    try {
      const web3 = await getWeb3();
      // Use web3 to get the user's accounts.
      const accounts = await web3.eth.getAccounts();
      // Get the contract instance.
      const networkId = await web3.eth.net.getId();
      // Get network provider and web3 instance.
      const deployedNetwork = SimpleStorageContract.networks[networkId];

      const instance = new web3.eth.Contract(SimpleStorageContract.abi
        ,deployedNetwork && deployedNetwork.address,);
        simpleinstance=instance;

      // Set web3, accounts, and contract to the state, and then proceed with an
      // example of interacting with the contract's methods.
      this.setState({ web3, accounts, contract: instance }, this.runExample);
    } catch (error) {
      // Catch any errors for any of the above operations.
      alert(
        `Failed to load web3, accounts, or contract. Check console for details.`,
      );
      console.error(error);
    }
  };
  // runExample = async () => {
  //   const { accounts, contract } = this.state;

  //   // Stores a given value, 5 by default.
  //   await contract.methods.set(1000).send({ from: accounts[0] });

  //   // Get the value from the contract to prove it worked.
  //   const response = await contract.methods.get().call();

  //   // Update state with the result.
  //   this.setState({ storageValue: response });
  // };

  render() {
    if (!this.state.web3) {
      return
Loading Web3, accounts, and contract...
;
    }
    return (

Good to Go!

Your Truffle Box is installed and ready.

Smart Contract Example

          If your contracts compiled and migrated successfully, below will show
          a stored value of 1000 (by default).

          Try changing the value stored on line 40 of App.js.

The stored value is: {this.state.storageValue}

        <input style={{width:200,height:20}} ref='Change_data_Input'></input>
        <button style={{width:40,height:20}}
        onClick={()=>{
          var value=this.refs.Change_data_Input.value;

          simpleinstance.methods.set(value).send({from:this.state.web3.eth.getCoinbase()}).then((result)=>{
            console.log("helloworld");
          })
          }}>修改</button>

    );
  }
}
export default App;

the main question is here !but i don't know how to call the 'set' function..

         simpleinstance.methods.set(value).send({from:this.state.web3.eth.getCoinbase()}).then((result)=>{
            console.log("helloworld");
          })


texts: Web3 method getTransactionReceipt() does not return token transfer value for particular token transaction

texts: I've tested getTransactionReceipt(), to get all detail about transaction with amount of token transfer. Also tested getTransaction but it returns only Ether transferred value. Is there any other method using which I can get amount of token transferred?


texts: While setting environment for ethereum ,  I got an Error that port 8545 is listened by another process, Actually testrpc and embark simulator both are using  the same port. If i kill one process and give to another then it is not the case. I want to use both process using different port . How do I change the port number of that process (Either testrpc or embark) . How do I Change the port for embark simulator (or port of testrpc) ?


texts: How to include the named of the called contract in Event Log

texts: in my code I am using events in order to log some date. I would like to include the name of the contracts I am calling out of my main contract into this event log. Does anyone have an idea how to do that?


texts: How to correctly downgrade geth from 1.6.0 to 1.5.9 on Win 10

texts:
The question is self-explanatory, I believe. I saw how to downgrade on Mac or Linux, but  ironically I have geth running of Win 10 machine as well (do not ask why?)

In geth version 1.6.0.-stable-facc47cs the key word seems to be not stable but facc... at least on my PC :-)
It throws out too often.


texts:
I have clone the source code of go-ethereum from github and i want to modify it so i can get owner crypto.

Step 1: go run mkalloc.go genesis.json from go-ethereum/core it gen hex for mainnetAllocData

Step 2: added it to genesis_alloc.go

Step 3: go test cpu -8

Step 4: fix hash test for new generate hash into params/config.go

Step 5: rerun go test cpu -8

Steo 6: make geth

I have read the reference but I do not know the next step how, can someone show me or give me link, please.

Is there references or link that i use to learn how to create wallet, transaction, smart contract,...????


texts: Fees are too Damn High to send $20 worth of USDC. How can one minimize these fees?

texts:
It's 2020 September 3. Fees to send 20 USDC to someone is about $10-15 worth of gas fees. How can I minimize the gas fees when using metamask? And is it true that if I set the gas fee too low, I would lose my ETH on a failed USDC transaction?
Last time this happened was with cryptokitties a few years ago. How come nothing was revamped to foresee a potential gas fee issue all these years on layer 1? What solutions are there for layer 1?


texts: My contract shows a zero balance on Metamask

texts:
I just need some help on a contract I'm doing an experimental project token for.
My setup as follows:
Using Remix for solidity
Metamask account linked Contract is using
pragma ^0.4.4 (original code version of this contract) Contract
deployed to Ropsten test network via Metamask
Ive copied an existing contract (ConsenSys token) and added my own features and supply
Solidity remixes the contract and accepts it and I've deployed it.
I've "cut & Paste contract "link" to Metamask - under the "add custom token" option
but it shows a 0 (Nil) balance (have tried a few different contract variants & decimals options
all resulting in 0 balances on Metamask??)
My decimal range is set to 0
so there should be no problem with it reading the total token supply as a whole value?

I've checked on the contract itself in remix to see it deployed the correct decimal and also correct
supply - both seem fine (see attached)

Metamask shows "zero" balance
and also when I check the contact on Etherscan tab from the Metamask tab
it shows the contract with an 18 decimal placement?

So I'm a little stuck on this - and could use some advice on how to get Metamask to read the correct token value.


texts: Unable to change the length of a global 2D storage array

texts:
I am facing difficulties changing the length of a global 2D storage array.

It seems to be working correctly on Remix IDE, but when I try to test it on ganache-cli (formerly known as testrpc) - either via truffle test (Javascript) or via web3 (Python) - it fails to work.

By "fail to work", I mean I can set the length of the array, but when I retrieve it - I always get 0.

Here is a minimal piece of code which reproduces the problem:

pragma solidity ^0.4.11;

contract Test {
    struct Data {
        uint256 a;
        uint256 b;
        uint256 c;
        uint256 d;
        uint256 e;
        uint256 f;
    }

    Data[][] private lists;

    function Test() public {
    }

    function setLength(uint256 length) public {
        lists.length = length;
    }

    function getLength() public constant returns (uint256) {
        return lists.length;
    }
}

As you can see, I am using a storage array.

Any ideas will be highly appreciated.

Thank you!!!


texts:
On my POA network there are 5 nodes/miners but suddenly all nodes stopped mining and giving this in console
"INFO [09-05|08:50:16.267] Looking for peers peercount=4 tried=4 static=0".
We tried to check the pending transactions in the txpool which showed this message on 3 of the miners and 2 miners listed 0 pending transactions
txpool.status
{
pending: 3,
queued: 0
}
If we try to start the mining by using miner.start() then the console shows the message as
INFO [09-05|08:53:23.471] Commit new mining work                   number=7961999 sealhash="d93ccf…cdb147" uncles=0 txs=0 gas=0 fees=0 elapsed="94.336µs"
INFO [09-05|08:53:23.471] Signed recently, must wait for others
INFO [09-05|08:57:23.483] Commit new mining work                   number=7961999 sealhash="c3f025…388121" uncles=0 txs=1 gas=21000 fees=0.0050589 elapsed="562.983µs"
INFO [09-05|08:57:23.484] Signed recently, must wait for others
I have also  tried to remove the miner from list by using clique.propose('*miner address*',false) but it does not remove the miner from the network.
Can anyone suggest what should I do that all nodes start mining again? I've tried "miner.start()" but it did not help.


texts: Get transaction in mainnet from layer2 rollup

texts:
With the coming of optimistic & ZKP rollups, I was wondering how we will be able to retrieve transaction data through etherscan.io generated from a layer2 solution.
Let's put an example:

Platform A operates with optimistic rollups, so creates a batch of 2000 transactions in a side-chain, and puts just one transaction T in the mainnet that relates to these 2000 tx's.

If one transaction T' out of these 2000 tx's was a transfer of ETH between two accounts generated from platform A:

How do I check transaction T' in the mainnet if I don't have a reference to its origin in a side-chain, but just one transaction T?
Are there certain transactions in a side-chain that can't be batched? for instance, if it is a withdrawal, should this create one specific transaction in the mainnet instead of including it in a batch T?
If there are different rollup platforms, will we have to go to the block explorer -if available- of each individual platform to see the details from the batched transactions?


texts: How do I edit a contract already in the blockchain?

texts:
I have a contract currently in the chain and I want to add a feature. Do I need to make a brand new contract, or is there a better way?
And if I have registered the contract with a name can I transfer it to the new contract?


texts: How get nonce of smart contract account with JSON RPC function? eth_getTransactionCount only for EXTERNAL accounts right?

texts:
How get nonce of smart contract account with JSON RPC function? (Number of new smart contract accounts created by a smart contract account?)

eth_getTransactionCount only for EXTERNAL accounts so won't work right?


texts: Request multiple API endpoints in Oraclize call

texts:
I want to make calls to multiple API endpoints. In my case, this is because I don't want to store the whole JSON response in my contract.

If I wanted to get the ?color=red and ?color=blue endpoints, could I use a call like this?

oraclize_query("URL",
               "json(http://my.api.com/).thing.stuff.0",
               "color=red",
               "color=blue");

This is a total guess. And it wouldn't allow me to pick out different JSON paths (thing.stuff.0), which I would want.

But I don't see any documentation about it. I am going off this piece of the source code:

contract OraclizeI {
    address public cbAddress;
    function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
    function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
    function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
    ...
}


texts: getPastEvents on localhost is not a function error

texts:
Now, I'm working on an Ethereum Blockchain project to transfer the ownership of stored devices by using local web3 provider  at the truffle environment.

Truffle v5.0.27 (core: 5.0.27)
Solidity v0.5.0 (solc-js)
Node v10.15.3
Web3.js v1.0.0-beta.37

**Browser details

OS: [Windows 10]
Browser tried both [firefox, chrome]
MetaMask Version [7.0.1]

Hence, I'm attempting to query all past events that a contract has ever emitted by using the following code

App.contracts.DeviceManager.deployed().then(function(instance) {
    DeviceManagerContractInstance= instance;
    DeviceManagerContractInstance.getPastEvents('allEvents',
    { fromBlock: 0, toBlock: 'latest' })

    .then(events => console.log("events:",events))
    .catch((err) => console.error("err",err));
     })

but I was getting this error

TypeError: DeviceManagerContractInstance.getPastEvents is not a function

Also, I tried to use allEvents()

 DeviceManagerContractInstance.events.allEvents()
.on('data', (event) => {
    console.log(event);
})
.on('error', console.error);

However, it's throwing the same error.

I don't know what is missing, and if the problem belongs to localhost or, code syntax.

Any Idea,


texts: Struct getter and Setter using inline assembly in solidity

texts:
I have a storage slot defined
bytes32 internal constant USER_STRUCT_SLOT =
        0xd722976edd762e336e189ef10d2d356b8698dc8a2e03a97b539ab9d3974a1630;

struct UserData {
        uint256 level;
        uint256 stakeToken;
        uint256 stableToken;
        uint256 rewards;
        uint256 rewardPercentTimes100;
        uint256 lastUpdateTime;
}

We have written a getter for this like :
function getUserDataStructValue(MyStruct memory data) private view returns (uint256 _u, uint256 _v, uint256 _w, uint256 _x, uint256 _y, uint256 _z) {
    assembly {
        _u := mload(data)
        _v := mload(add(data,0x20))
        _w := mload(add(data,0x40))
        _x := mload(add(data,0x60))
        _y := mload(add(data,0x80))
        _z := mload(add(data,0xA0))
    }
}

Not sure about how the Retrieval and setting of the Structure will work wrt the slot we provided
How to set the Values in a struct using inline assembly code ?


texts: Can I switch my Eth-1 node and Eth-2 node off while waiting for activation?

texts: I setup a Medalla-Geth-Node and a Eth-2 node (Teku) and went through all the steps in the launch pad. My status went from "Deposited" to "Pending" and currently the beaconchain-explorer says "estimated activation in 12 days". Can I power down my computer in the meantime and turn it back on shortly before activation. I dont want to waste electricity. Or will I loose my spot in the activation queue?


texts:
I had a private ethereum blockchain with 1 node running in production. I accidentally ran a geth init genesis.json --datadir . command in my main node.
Did this command overwrite the data directory folder of my main node? I was able to set up another node in the network on another server because geth process was running on a Unix system service daemon, which means that the data folder wasn't actually unlinked while the process was running.
Now I have 2 private blockchain nodes and I want to stop and reset the 1st one, but I'm not sure what will happen to the blockchain. If I stop the 1st node and then use the 2nd node as a peer to resync the first node when I restart, will the chain be corrupted? I have miners on both nodes and I'm using a clique algorithm for consensus.


texts: Is there anyway to implement Proof of stake (PoS) in Ethereum?

texts:
I am looking for a mechanism that implements Proof of stake (PoS) in ethereum. I am working on a mechanism that closely related to PoS, however, I do not find any other platforms. I was hoping that Proof of Authority (PoA) somehow related to PoS but I get confused by the implementation available on the web.
If you have any knowledge  and tutorials that a complete private implements similar to PoS or PoA, please help to get those information. I also have a question that in PoA, regardless of the reputation, the nodes chances to become miner is random and equally weighted?
Thanks in advance.


texts: Error when interacting with an Ethereum Smart Contract using web3.py

texts:
I'm using web3.py to interact with an Ethereum Smart Contract which is:

pragma solidity ^0.4.0;

contract Coin {
    address public minter;
    string public name;
    mapping (address => uint) public balances;

    event Sent(address from, address to, uint amount);

    function Coin() public {
        minter = msg.sender;
        name = 'MyCoin';
    }

    // Create new Tokens
    function mint(address _reciever, uint _amount) public {
        if (msg.sender != minter) return;
        balances[_reciever] += _amount;
    }

    // Send tokens
    function send(address _reciever, uint _amount) public {
        if (balances[msg.sender] < _amount) return;
        balances[msg.sender] -= _amount;
        balances[_reciever] += _amount;
        Sent(msg.sender, _reciever, _amount);
    }

    function getBalance(address _user) public view returns (uint){
        return balances[_user];
    }

    function balances(address _account) public view returns (uint, string) {
        return (balances[_account], name);
    }
}

Compiling, deploying and generating ABI and contract address were successful. Hower, when i try to access to the deployed smart contract using web3.py i got a strange exception when i call the function balances() in the smart contract.

eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes

I used geth with a custom genesis block and parity chain dev node, but without any success.

Here is my Python code:

import json
from web3 import Web3, RPCProvider
from web3.contract import ConciseContract
import time

RPC_IP = '127.0.0.1'
RPC_PORT = '8545'

# read the contract informations then convert them into a Python dict
with open('contract_informations.json', 'r') as f:
    data = json.loads(f.read())

ABI = data.get('abi')
CONTARCT_ADDRESS = data.get('contract_address')

w3 = Web3(RPCProvider(RPC_IP, RPC_PORT))

contract_instance = w3.eth.contract(ABI, CONTARCT_ADDRESS, ContractFactoryClass=ConciseContract)

contract_instance.mint('0x00a329c0648769A73afAc7F9381E08FB43dBEA72', 1000, transact={'from': w3.eth.accounts[0]})

print(contract_instance.getBalance('0x00a329c0648769A73afAc7F9381E08FB43dBEA72'))

When i run the Python code there is two exceptions:

web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

and

eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes

However, when i deploy the contract using Parity web interface, everything works fine.

Did, web3.py has some limitations or did i miss something ?

Thanks for your answers.


texts: Can use smart contract as payment gateway

texts: Most suggest that cannot use ERC20 token as payment gateway integration .Why?


texts: Which operations can change ethereum address balance?

texts:
I am writing a program that would monitor changes in balance of a set of ethereum addresses. I did the same for UTXO based coins, and the logic was pretty simple. All of the changes were directly recorded in blocks. But ethereum appears to be more complicated. Which operations I have to monitor to be sure I won't miss anything? It is important that I have to monitor changes of balance, not the balance itself.

Operations that are capable of changing balance, that I found:
 1. Basic transactions on the blockchain level
 2. Block rewards for mining
 3. Smart contract internal transactions

Is there anything else that I have to be aware of?
When ETH 2.0 arrives, will the staking reward format be different from the current types of balance update?


texts: Could you run Ethereum to behave like a faster Bitcoin?

texts: Without Smart Contracts. Would that system scale better and have less technical hustles than Bitcoin itself?


texts: Should I use Ethereum blockhain for its immutability in my project?

texts:
First of all, I am completely new to blockchains so sorry if I'm asking any silly questions:)

I would like to build a test web project: users can create accounts and manage various kinds of agreements e.g. one user borrow some money to another one, the first one creates an agreement and the second one should sign it.

I would like to use private Ethereum chain as a database to ensure all the agreements are immutable so that anyone could prove it validity. For now I'm thinking of having several nodes with the chain with PoA, several nodes with servers handling e.g. authorization and frontend.

Questions:

Is it a valid use case or should I simply use a database?
Will I get some additional security bonuses if I use the chain?
Should I store agreements itself in a chain?
Should create user accounts straight in a chain thus not having to use any backend I mean using contracts only?

Thank you very much!


texts: I cant´t import the keyfile from jaxx via geth into Mist. I know there are good answers here already. And i tried to solve it myself but it always says:" Fatal: keyfile must be given as argument". I`m using windows 7. Any help? Thx


texts: How to generate a unique random number in web3.js?

texts:
I need to generate a unique 128 bit number and know this number in my web3.js script.

Previously I tried this (create these numbers in my contract and retrieve them to web3.js). It seems impossible.

Now I consider an alternative solution: I instead generate a random number in web.js code and pass it to the contract to be stored in a map.

So the question: How in web3.js to generate a 128 bit random number with almost 100% probability than no other process using my contract generated the same number?


texts:
As per my current understanding PoW algorithm is to ensure that only the decided number of blocks are made in a time frame and we adjust difficulty accordingly.
I'm a beginner in Solidity and Ethereum and i want to understand each line of this code, please help me to analyze it

bytes32 public currentChallenge;                         // The coin starts with a challenge
uint public timeOfLastProof;                             // Variable to keep track of when rewards were given

Line 1: currentChallenge is a variable of type byte32 ( sequence of 32 bytes, 256 bits in total )

Line 2:uint is a datatype for currency amount and dates ( in unix time )

  uint public difficulty = 10**32;                         // Difficulty starts reasonably low

Line 3: What does 10**32 does ? I have an idea that it is related to number of bits but not crystal clear about what it does

    function proofOfWork(uint nonce){
    bytes8 n = bytes8(sha3(nonce, currentChallenge));    // Generate a random hash based on input
    if (n < bytes8(difficulty)) throw;                   // Check if it's under the difficulty

Line 4: proofOfWork accepts nonce ( any random number ) as input, which I'll be manually entering in my Ethereum Wallet.

Line 5: We create a random hash by concatenating nonce and currentChallenge and store it in n

Line 6: If the computation by current nonce is not able to match the difficulty then do not proceed

        uint timeSinceLastProof = (now - timeOfLastProof);  // Calculate time since last reward was given
    if (timeSinceLastProof <  5 seconds) throw;         // Rewards cannot be given too quickly
    balanceOf[msg.sender] += timeSinceLastProof / 60 seconds;  // The reward to the winner grows by the minute

Line 7 and Line 8 : Can we compare time just by adding unit(seconds) just like in Line 8:, how does it work ?

difficulty = difficulty * 10 minutes / timeSinceLastProof + 1;  // Adjusts the difficulty

Line 9: This is based on unitary method, if blocks are being made in more than 10 minutes then lower the difficulty , else increase it. Again same doubt as in Line 3 what's happening on multiplying ( * ) , why are we adding 1 ?

    timeOfLastProof = now;                              // Reset the counter
    currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number-1));  // Save a hash that will be used as the next proof

Line 10 and Line 11 : Update timeOfLastProof and currentChallenge.
Getting inside the parameter 3 in sha3
block.blockhash(block.number-1), I have asked this in another thread too , and i got to know that:

blockhash(block.number-1) gives blockhash ( a random number) of the previous block, and we are taking the previous block specifically to maintain the chain. Is this right ?
block.blockhash(block.number-1) - Is there a structure with the name block and blockhash one of its data members ?


texts: Is it possible to serialize transaction data on geth or PHP?

texts:
I need ethereumjs-tx in PHP. Seems there is no PHP library so far. I found only JS and Python Library. Is it possible to serialize transaction data on geth? If not, I will use nodejs or create the PHP library. Before that, I want to ask this question.

What I need:

$rawTx = [
  'nonce' => '0x17',
  'gasPrice' => '0x4a817c800',
  'gasLimit' => '0x5209',
  'to' => '0x5dbb9793537515398a1176d365b636a5321d9e39',
  'value' => '0xde0b6b3a7640000',
  'data' => '',
  'chainId' => 3
];

$tx = new Tx($rawTx);
$serializedTx = $tx->serialize(); // or access geth function if it possible

ethereumjs-tx

Create and sign OFFLINE raw transactions?


texts: Invalid JSON RPC Response with web3.eth.filter

texts:
I'm trying to retrieve all pending transactions by using web3.eth.filter given an address, but i always receive "Invalid JSON RPC Response "" ".
Web3 version is 0.20.6.

I'm using rinkeby testnet.

var options = {
  from: "0x9596f1439576e0142976F0822883DE62e326B542",
};
var filter =  web3.eth.filter( options );

filter.watch(function (error, log) {
  if ( error )
    console.log(error.message);
  else {
    console.log(log);
  }
});


texts: Is holding REP safe in address from which REP/Ether has been srnt?

texts: Is there any reduction in security with holding REP in address after a transaction out (to exchange for example) has been made? Could the key to address be revealed or compromised, assuming using hardware wallet?


texts: What is the gas cost of keccak256("abc")?

texts:
According to this answer, the gas cost of keccak256 is:

  30 gas + 6 gas for each word (rounded up) for input data to a SHA3 Keccak-256 operation

I'm assuming that the size of a word is 256 bits and the size of a character is 8 bits.

Hence the gas cost keccak256("abc") or any other string of up to 32 characters is 36 gas units.

Is my assumption correct?

If yes, is my conclusion correct?

Thank you!


texts: Mnemonic and HD Path in Ganache and ethereumjs-tx gives different private key and address

texts:
I am having difficulty reproducing the private key and address using the mnemonic and HD path provided by Ganache.
Mnemonic

weird farm vast surge upper truth answer end radar impact mind jeans

HD Path

/44'/60'/0'/0/0

JS Code to Reproduce Keys/Addresses
var hdkey = require('ethereumjs-wallet/hdkey')

let rootNode = hdkey.fromMasterSeed('weird farm vast surge upper truth answer end radar impact mind jeans')
console.log('Address: ', rootNode.derivePath("m/44'/60'/0'/0/0").getWallet().getAddressString())
console.log('Private Key: ', rootNode.derivePath("m/44'/60'/0'/0/0").getWallet().getPrivateKeyString())

JS Output

Address:  0xccb154949e497124538e918fbc3146500ebbe38e
Private Key:  0xa0f34e8dddc55fb9a59a00f58499faa96bebfe1b47b5b821f6f2bb303895c309

Question: Why are the address and private key produced by the JS code (ethereumjs-wallet) different from the one in Ganache?
Using Ganache 1.2.2 on Mac OSX, ethereumjs-wallet 0.6.2


texts: Can Dapp respond to an API evocation which in turn calls an EOA and then evoke a contract?

texts:
Can a Dapp (leveraging web3.js) respond to an API evocation from an external system which in turn calls an EOA and then evoke a contract on the blockchain?

External system calls a Dapp
Dapp calls a smart contract via an EOA

Nathan Aw


texts: Acess position in array vs Access key in mapping (uint IDs) - What's the efficient way?

texts:
I have a doubt about efficiency in solidity, when searching in lists of integer values, in mapping vs array.
Array
Imagine that I use the array position as element ID, and the content as the value, as following:
 uint[] public valuesArray;

And if I want to retrieve the value of a certain ID (2):
uint valueTwo = valuesArray[2]

mapping
Another way to achieve this, with a mapping could be the following:
mapping(uint => uint) valuesMapping;

And if I want to retrieve the value of a certain ID (2):
uint valueTwo = valuesMapping[2]

Case 1- uint types
What would be the most efficient way (best practice) to achieve that, in order to consume as less gas as possible? Array or Mapping
Case 2- address types
Which would be more efficient in this case? (Array or Mapping)
address[] public addressArray;
mapping(uint => address) addressMapping;

If I have address values inside the array/mapping instead of uints:
address addressTwo = addressArray[2];

VS
address addressTwo = addressMapping[2]

Thanks in advance


texts: Unable to grant role to self using AccessControl.sol

texts:
myContract implements OpenZeppelin's AccessControl. I want my account to grant MINTER_ROLE to the same account. The value of "account" is the same as the contract's creator.
Why is the code below returning an error for the 4th line?
var minterRoleHex = web3.utils.asciiToHex('MINTER_ROLE');
var adminRoleHex = await window.myContract.methods.getRoleAdmin(minterRoleHex)
    .call();
var hasRole = await window.myContract.methods.hasRole(adminRoleHex, account)
    .call(); // returns true
window.videoContract.methods.grantRole(minterRoleHex, account)
    .call(); // error: sender must be an admin to grant


texts:
I'm trying to listen for an event I've created on remix IDE , from NodeJS.
I call a smart contract method from where the event is triggered and I'm waiting for it in my console...but I don't receive anything :(

I'm using NodeJS with ExpressJS
Web3  Version:  1.0.0-beta.46

The Smart contract code would be something like :

pragma solidity >= 0.4.22 < 0.6.0;

contract Test {

event test1(address a,uint16 b,uint16 c,uint16 d,uint16 e);
event test2(address a,uint128 f,uint16 g);
event test3(address a,uint128 f,bool h);

//method 1
function method1(uint16 a,uint16 b,uint16 c,uint16 d) external payable {
// ... some code ... //

//here I trigger the event
    emit test1(msg.sender,a,b,c,d);
}

//method 2
function method2(uint128 f,uint16 g) external payable {
// ... some code ... //

//here I trigger the event
    emit test2(msg.sender,f,g);
}

//method 3
function method3(uint128 f) external payable {
// ... some code ... //

//here I trigger the event
    emit test3(msg.sender,f,true);
}

}

And this is how I listen for the event , in NodeJS :

 SmartContract.events.test1({fromBlock: 0, toBlock: 'latest'} , (error, event) => { console.log(JSON.stringify(event)); })
 .on('data', (event) => {
console.log("The event is : " + JSON.stringify(event));
 }).on('changed', (event) => {
console.log("Changed event : " + JSON.stringify(event));
 }).on('error', console.error);

I've tried to listen without any parameters like fromBlock or toBlock as well,but didn't work...
I don't get any error or something.
I start listening before to perform the smart contract method and after I perform it

the mined block received has the status "0x1" so the transaction was ok.But I don't know why the listener isn't working...

EDIT : Instantiation of the smart contract :

 const address = "0xB740096F1a6642190c816EfE37697891c65Afc92";
 const theABI = require('./getABI.js');
 var SmartContract = new web3.eth.Contract(theABI.getABI() , address);

The getABI.js file has just 1 function that returns the ABI.
I'm sure and I've just rechecked,the ABI contains the events.Here's a snippet of code from the ABI where an event is present:

    {
            "anonymous": false,
            "inputs": [
                    {
                            "indexed": false,
                            "name": "a",
                            "type": "address"
                    },
                    {
                            "indexed": false,
                            "name": "f",
                            "type": "uint128"
                    },
                    {
                            "indexed": false,
                            "name": "g",
                            "type": "uint16"
                    }
            ],
            "name": "test2",
            "type": "event"
    },

Instantiation of web3 :

 const Web3 = require('web3');
 const web3 = new Web3(Web3.givenProvider || "ws://IP SERVER:PORT");

I've also tried the following approach :

 // Receives all events from the smart contract
 const listener = SmartContract.events.allEvents({}, (error, event) =>{ console.log("THE CALLBACK EVENT IS : " + JSON.stringify(event)); })
 .on('data', async (event) => { console.log("THE EVENT IS : " + JSON.stringify(event)); })
 .on('receipt', async function(result) { console.log("THE RECEIPT EVENT IS : " + JSON.stringify(event)); })
 .on('transactionHash', function(hash){ console.log("THE HASH EVENT IS : " + JSON.stringify(event)); })
 .on('error', function(error){ console.log("THE ERROR EVENT IS : " + JSON.stringify(event)); });

Still no output from event listener...


texts: How do miners decide which block should be an ommer block?

texts:
Let's say there is a fork and there are two valid blocks. How do the miners choose which block to work on if they receive both the valid blocks at the same time(Is this possible?)? After this decision, one block becomes the ommer block and won't be placed on the main chain. What parameters are considered during this decision?

Also, how long does it take (how many blocks) for a fork to generally get resolved in the Ethereum public blockchain network?


texts: Emit of boolean returns "null" instead of "false" (Solidity, web3.js)

texts:
A Solidity event is supposed to emit a boolean. In case of won = true the transaction receipt in web3 logs true as expected, but if won = false the emit logs null instead false. I have no idea why. First I thought it is because of the same variable name, but that is not the cause.

I have this Solidity function which either emits "true" or "false"

event GameResult(bool won);

//My simplified contract
function lottery(uint8 guess) public payable returns(bool){
  uint8 result = 1;
  bool won = false;
  if (guess == result) {
    //Won!
    msg.sender.transfer(msg.value * 2);
    won = true;
  }
  emit GameResult(won);
}

UPDATE: Here is my web3 function to call the contract (only the relevant part. Full code can be found on Github):

async function play() {
  let headsOrTailsSelection = 1;

  //A test to get the emit values from the contract: true "works", "false" not
  headsOrTails.once('GameResult', function(error, event){ console.log(event.returnValues); });

  returnValue = await headsOrTails.methods.lottery(headsOrTailsSelection).send({ from: account, value: amountToBetWei });
  console.log(returnValue);
}

General infos:

Currently using Ganache as a local blockchain for development
Solidity version: ^0.5.0
IDE: VS Code


texts: Oracle used by a Smart Contract no longer available

texts: Ethereum relies on Oracles to provide information about the outside world used by SmartContracts. Also, when a node syncs (in slow mode) it has to go  over all transactions (including SmartContract transactions) to validate the entire transaction history. Well, what if by the time a new node is syncing, the oracle is no longer available?


texts: Strange output from truffle migrate --network live --dry-run

texts:
I can't get my contract to deploy successfully using Infura, MetaMask, and Truffle.

When I run truffle migrate --network live I get this error:

Error encountered, bailing. Network state unknown. Review successful transactions manually.
insufficient funds for gas * price + value

But then, if I run truffle migrate --network live --dry-run I get this output:

sender doesn't have enough funds to send tx. The upfront cost is: 672197500000000000 and the sender's account only has: 60000000000000000

Assuming that value is in wei, why would it cost so much to deploy a contract? What can I do about this?

Here is my truffle.js file:

var HDWalletProvider = require("truffle-hdwallet-provider");

var mnemonic = "my_mnemonic";

module.exports = {
  networks: {
    live: {
      network_id: 1,
      provider: new HDWalletProvider(mnemonic, "https://mainnet.infura.io/my_api_key")
    }
  }
};


texts: Automatically tax transaction and distribute to all token holders

texts:
Is there an efficient way to automatically "tax" every transaction and proportionately send the taxed amount to all non-blacklisted token holders? From my understanding, looping through all addresses upon every transaction will cost an extraordinary amount of gas.
Is it possible to do this by keeping track of a totalTaxedAmount and returning the following when calling balanceOf(address)?
function balanceOf(address addr) public view returns (uint256){
    return balances[addr] + balances[addr]*totalTaxedAmount/totalSupply;
}

Will this actually reflect a token count increase?


texts: Truffle stuck when deploy smart contract when using Ledger wallet

texts:
I have a little problem deploying smart contract with ledger nano s as provider on ropsten. The script just remain stuck at first migration

Starting migrations...
======================
> Network name:    'ropsten'
> Network id:      3
> Block gas limit: 8000029 (0x7a121d)

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

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x1b85c85699b9f40798b5892a7492c303048915e80ac69803f94e617744769865
   ⠋ Blocks: 211          Seconds: 2829

This is my truffle configuration

require("dotenv").config();
const gasPrice = require("./get_gas_price");
const HDWalletProvider = require("@truffle/hdwallet-provider");
const Web3 = require("web3");
const web3 = new Web3();

const LedgerProviderRopsten = require('./ledger-provider-ropsten');
const LedgerProviderMainnet = require('./ledger-provider-mainnet');

module.exports = {
  networks: {
    testnet: {
      provider: () => new HDWalletProvider(process.env.MNEMONIC, process.env.BLOCKCHAIN_NODE_ROPSTEN),
      network_id: "*",
    },
    mainnet: {
      provider: () => LedgerProviderMainnet,
      network_id: 1,
      gasPrice: web3.utils.toWei((gasPrice.fast / 10).toString(), "gwei"),
    },
    ropsten: {
      provider: () => LedgerProviderRopsten,
      network_id: 3,
      gasPrice: 20000000000
    }
  },
  compilers: {
    solc: {
      version: "0.6.9",
      settings: {
        optimizer: {
          enabled: true
        }
      }
    }
  }
};

Ledger provider configuration

const LedgerWalletProvider = require('@ledgerhq/web3-subprovider');
const createLedgerSubprovider = LedgerWalletProvider.default;
const TransportNodeHid = require('@ledgerhq/hw-transport-node-hid').default;
const ProviderEngine = require('web3-provider-engine');
const RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
// const logger = require("@ledgerhq/logs");
// logger.listen(log => console.log(log));

const localNode = 'http://127.0.0.1:8545';

const getTransport = () => TransportNodeHid.create();
const ledger = createLedgerSubprovider(getTransport, {
    networkId: 3, paths: ["44'/1'/0'/0/0"], askConfirm: false,
});

const engine = new ProviderEngine();
engine.addProvider(ledger);
// process.env.BLOCKCHAIN_NODE_ROPSTEN
engine.addProvider(new RpcSubprovider({ rpcUrl: process.env.BLOCKCHAIN_NODE_ROPSTEN }));
engine.start();

module.exports = engine;

Operating System: Ubuntu 20
Ethereum client: geth Version: 1.9.15-stable
Truffle version (truffle version): 5.1.29
node version (node --version): 10.21.0
npm version (npm --version): 6.14.5


texts: how often should the wallet be backed up?

texts: Is it enough to backup the wallet when it is created or should they be backed up every so often. I am guessing it should be enough to back up once for every account but do not know much about cryptocurrency and this technology and wanted to be sure.


texts: Simplest web3 SendSignedTransaction not working for 10th nonce?

texts:
The most basic code to start a transaction is not working for me. after the 9th transaction. How can this be. I have the following .js file and I start it in CMD with Node C:/Programs/code_snippets/create-transaction.js

Started it perfectly fine 9 times, then the 10th in didn't work. Repeated this 2x, because I thought I messed up code without remembering. Any advice?

I don't get any error, it just stays doing nothing after receiving
Tx Hex: f86f10852e90edd000830c350094b29d0bde21ff7f1a89ebed0d9c40ca9f71119d7c87038d7ea4c68000834869212aa0ed69e3115bce1c0e06d6695027c109dfa0c9748c669175ccf214a0fe62664fa6a045de9493ebe5cce95e65e46640652d312f635e8d42ad3c2742688bb11ffaa999

   // Add the web3 node module
var Web3 = require('web3');

// Show web3 where it needs to look for the Ethereum node.
web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/Whm5Ks3VGzJMBGHh4MEx'));

// An extra module is required for this, use npm to install before running
var Tx = require('ethereumjs-tx');

// Used to sign the transaction. Obviously you SHOULD better secure this than just plain text
var privateKey = new Buffer('265f303edd16be057608a0810414c2889c24e7ce8e9e4a88ae5b8a561c26935a', 'hex');

 // The receiving address of the transaction
var receivingAddr = ('0x29307EE93F49E9eB1425e40C9119b9Cb6e39d9B5');

// Value to be sent, converted to wei and then into a hex value
var txValue = web3.utils.numberToHex(web3.utils.toWei('0.01', 'ether'));

var noncePromise = web3.eth.getTransactionCount('0x24003FbB79cfA541eE32C59ef3A7424541f4AA01', 'pending');
var balancePromise = web3.eth.getBalance('0xED54EbBC73C7fb8B6607547b7541D8799708D93B');
var gasPricePromise = web3.eth.getGasPrice();
//var PendingTransactionFromBlock = web3.eth.getTransactionFromBlock('pending', 2)
var BlockPromise = web3.eth.getBlock('pending', false);

var allPromises = Promise.all([
    noncePromise,
    balancePromise,
    gasPricePromise,
    BlockPromise

]);

 // This function is ONLY called once ALL promises are fulfilled
    var sendPromise = allPromises.then(function(results) {
    var nonce = results[0];
    var balance = results[1];
    var gasPrice = results[2];
    var Block = results[3];

 var run = true;
    var i = 0;
    var numberBlockTransactionHashes = Block.transactions.length;
    var TransactionDataPromise = [];
    TransactionDataPromise.push(web3.eth.getTransaction(Block.transactions[i]));
    console.log("numberBlockTransactionHashes: " + numberBlockTransactionHashes);
/* while (run) {

    TransactionDataPromise.push(web3.eth.getTransaction(Block.transactions[i]));

    if (i == numberBlockTransactionHashes)
    {
        run = false;
        continue; // jump to top
    }

    i++
}     */

// Data to be sent in transaction, converted into a hex value. Normal tx's do not need this and use '0x' as default, but who wants to be normal?
var txData = web3.utils.asciiToHex('hi');

var rawTx = {
  nonce: '0x' + nonce, // Nonce is the times the address has transacted, should always be higher than the last nonce 0x0#
 gasLimit: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(200000000000),
 to: receivingAddr, // The receiving address of this transaction
  value: txValue, // The value we are sending '0x16345785d8a0000' which is 0.1 Ether
  data: txData // The data to be sent with transaction, '0x6f6820686169206d61726b' or 'oh hai mark'
}

console.log(rawTx); // This is used for testing to see if the rawTx was formmated created properly, comment out the code below to use.

var tx = new Tx(rawTx);
tx.sign(privateKey); // Here we sign the transaction with the private key

var serializedTx = tx.serialize(); // Clean things up a bit

console.log("Tx Hex" + serializedTx.toString('hex')); // Log the resulting raw transaction hex for debugging if it fails to send

web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')) // Broadcast the transaction to the network
.on('receipt', console.log); // When a receipt is issued, log it to the console

});


texts: I have a stock exchange project that I hired to a developer. I'm okay with bitcoin but I am new to Ethereum. The developer is in the process of develop the Ether wallet. Like a regular stock market, I want an API generates unique ethereum addresses (connected to my cold wallet) for each registered members.  Which informations should I share with my developer to do it? can someone help me to redirect me as I am a newbie? I just want to in safe.


texts:
I'd like to know either how to implement the skinny CREATE2 in Python or a package that provides it.
This is the function I'm trying to port from TypeScript to Python. It calls generateAddress2 with that particular salt (size 32):
export function getUserIdentity(walletAddr) {
    const bytecode = getBytecode(walletAddr)
    const addr = getAddress(
        `0x${generateAddress2(ADDR_FACTORY, Buffer.alloc(32), bytecode).toString(
            "hex"
        )}`
    )
    return { bytecode, addr }
}

And this is the ethereumjs generateAddress2 implementation:
/**
 * Generates an address for a contract created using CREATE2.
 * @param from The address which is creating this new address
 * @param salt A salt
 * @param initCode The init code of the contract being created
 */
export const generateAddress2 = function(from: Buffer, salt: Buffer, initCode: Buffer): Buffer {
  assertIsBuffer(from)
  assertIsBuffer(salt)
  assertIsBuffer(initCode)

  assert(from.length === 20)
  assert(salt.length === 32)

  const address = keccak256(
    Buffer.concat([Buffer.from('ff', 'hex'), from, salt, keccak256(initCode)]),
  )

  return address.slice(-20)
}

Many thanks!


texts: Solidity: Is there any catch mechanism for throw? If not switch into return usage might be better?

texts:
Based on experienced mentors it seems like throw mechanism is suggested here. I guess catch mechanism does not exist for throw: https://ethereum.stackexchange.com/a/2512/4575.

Based on that I have a problem: First I have to check some condition which might take high gas value. If the condition is failed throw will take place. So if condition fails, I want to pay back the money to the client. Otherwise, money should pay back to the cluster.

[Q] If condition fails, throw will take place. Since throw terminates the code, there is no way for me to catch the reverted version, and apply 1 line of code to payback the money to client. Is there any alternative solution to handle this issue?

Please note that condition will change state. So I have to do throw if there is condition fails.

function payMeBack() {
    if(require(<some condition>)) //if condition is wrong throw take place and never JUMPS to else side.
       if(!client.send(gainedWei)) throw;
    else
       if(!cluster.send(gainedWei)) throw;
    gainedWei = 0;
    client.success = 1;
}

Thank you for your valuable time and help.


texts: Is ownership of tokenized real assets through NFT upheld by law?

texts:
Let's say you've tokenized your house as a non-fungible token (NFT) on the Ethereum blockchain.
if an NFT simply represents ownership of a tokenized asset, what actors or agencies currently will uphold the rule of law in the event of theft of that physical asset, given that the house cannot be stored on-chain?
You might own a house according to an NFT, but if someone walks in, changes the locks, and steals the house from you, will the authorities really save you based on the supposed credibility of the NFT you showed them?


texts:
i have been trying to run a node in a virtual machine. Im using Ubuntu 16.04 and have already installed Geth to it. Im running it with geth --rpc --cache=1024 --verbosity 5. When i attach to the console and send the eth.syncing command i get this information:

{
  currentBlock: 4081498,
  highestBlock: 4081655,
  knownStates: 747286,
  pulledStates: 730115,
  startingBlock: 4067468
}

I cant get it to sync to the last block, please dont tell me to delete de blockchain and start again because i have already done it like 5 times and i always get stucked. Have already lost 2 weeks in syncing time.

What is wrong with my node?

My node is listed in the ethstats panel as "ArgenPool"


texts: How to get the private keys associated with the web3.eth.accounts from testrpc?

texts:
I know I should be able to get it, but does anyone know how to get the private keys associated with the web3.eth.accounts from the testrpc?

Much thanks and upvotes to the wise sage with the answer.


texts: How to make a function only available for the founder?

texts:
I have created a contract that allows a function issue, the code as followed;

function Issue(uint256 _value) public  {
    balanceOf[msg.sender] += _value;            // Subtract from the sender
    totalSupply += _value;                      // Updates totalSupply

 }

I want to edit that only the creator of the contract can Issue more token. I tried changing the public to internal, but after changing that, I cannot find the Issue function.

My questions is how do I edit this to make the issue only available to the founder?


texts: Noob Troubleshooting failed BSC transaction using ethers.js and Pancakeswap v2 router

texts:
How do i debug or troubleshoot this... I am going broke $0.07 at a time.. LOL
The code approves WBNB on Pancakeswap and gives a transaction receipt.
Then it fails the swapExactTokensForTokens when swapping 0.005 WBNB for BUSD
The Approval https://bscscan.com/tx/0xc02b45832450e03e4c9e842238fc6ca7d400e9af6287d6fde5f40c973746b7b5
The Failed Swap
https://bscscan.com/tx/0x72db3b1471a4a62d676a0f76097d6bf59533fe450a7d0b7d0423168c7f6e8a8b
const ethers = require('ethers');

const addresses = {
    WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
    BUSD: '0xe9e7cea3dedca5984780bafc599bd69add087d56',
    factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
    router: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
    recipient: '0x4F2200C7E437F92A2bbB03A5c867b379B72F87B0'
  }

const privateKey = 'My Privates';
const mygasPrice = ethers.utils.parseUnits('5', 'gwei');

const provider = new ethers.providers.WebSocketProvider('wss://muddy-young-frost.bsc.quiknode.pro');
const wallet = new ethers.Wallet(privateKey);
const account = wallet.connect(provider);

const router = new ethers.Contract(
  addresses.router,
  [
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
    'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
  ],
  account
);

const wbnb1 = new ethers.Contract(
    addresses.WBNB,
    [
      'function approve(address spender, uint amount) public returns(bool)',
    ],
    account
  );

  console.log(`Before Approve`);
  const valueToapprove = ethers.utils.parseUnits('0.01', 'ether');
  const init = async () => {
    const tx = await wbnb1.approve(
      router.address,
      valueToapprove,
      {
          gasPrice: mygasPrice,
          gasLimit: 210000
      }
    );
    console.log(`After Approve`);
    const receipt = await tx.wait();
    console.log('Transaction receipt');
    console.log(receipt);
  }

  init();

  const testtx = async () => {
  console.log(`after testtx`);

  let tokenIn = addresses.WBNB , tokenOut = addresses.BUSD;

  const amountIn = ethers.utils.parseUnits('0.005', 'ether');
  const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
  //Our execution price will be a bit different, we need some flexbility
  const amountOutMin = amounts[1].sub(amounts[1].div(10));

  console.log(`
    Buying new token
    =================
    tokenIn: ${amountIn} ${tokenIn} (WBNB)
    tokenOut: ${amountOutMin} ${tokenOut}
  `);

  const tx = await router.swapExactTokensForTokens(
    amountIn,
    amountOutMin,
    [tokenIn, tokenOut],
    addresses.recipient,
    Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
    {
        gasPrice: mygasPrice,
        gasLimit: 210000
    }
  );
  console.log(`line 115`);
  const receipt = await tx.wait();
  console.log('Transaction receipt');
  console.log(receipt);
}
testtx();


texts: use of privateFor while creating contract

texts:
I am having two contracts, custodian and trader. I am using custodian as a member of trader contract.
contract trader {
.
.
custodian public custodianUser;
.
.
}

I am deploying custodian on separate node. When I try to set custodian by calling a function setCustodian of trader, I am not able to see custodian getting associated for trader. Code works fine in remix and also on my ubuntu instance if I dont use privateFor while deploying contract. Can any one help me to use privateFor wisely. The script used was as follows:

loadScript("trader.js");
var traderbin = output.contracts["trading2.sol:trader"].bin
var traderContract =
web3.eth.contract(JSON.parse(output.contracts["trading2.sol:trader"].abi));
var trader = traderContract.new(
   {
     from: web3.eth.accounts[0],
     data: '0x' + traderbin,
     gas: '4700000',
     privateFor: [<key1>,<key2>,<key3>]
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + '
transactionHash: ' + contract.transactionHash);
    }
 });

    var custodianBin = output.contracts["trading2.sol:custodian"].bin
    var custodian = web3.eth.contract(JSON.parse(output.contracts["trading2.sol:custodian"].abi));
var custodianContract = custodian.new(
   {
     from: web3.eth.accounts[0],
     data: '0x' + custodianBin,
     gas: '4700000',
     privateFor: [<key4>,<key5>]
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + '
transactionHash: ' + contract.transactionHash);
    }
 });

I am having 3 Different contracts deployed as follows:
Trader1 >
Custodian1 >
CustodianMain >
Custodian2 >
Trader2

If I make changes in Trader2, changes should pass upwards until Trader1

In order to make it happen, do I need to add privateFor for all nodes?
If I add all node public keys in privateFor, then is there any advantage of using quorum in this scenario?


texts: How to pass token address of one contract into another contract?

texts: I have two contracts , one is company contract to register company and get its token and other is to make transaction using that token. so how can i use that token in second smart contract ?


texts: Encounter error when assigning mapping to another

texts:
I've declared a mapping mapping (address => uint) public stakeholderId; in another contract. I want to copy it from the contract, so I've declared a mapping and want to assign the mapping to it:

contract ActivityInterface{
    address CongressAddress = 0x1;
    Congress temp = Congress(CongressAddress);
    mapping (address => uint) stakeholderId = temp.stakeholderId;
}

However, why does it show the following error for the line mapping (address => uint) stakeholderId = temp.stakeholderId;:

  Type function (address) returns (uint256) is not implicitly
  convertible to expected type mapping(address => uint256).


texts:
I somehow is running geth with full sync.
>geth --syncmode full --datadir F:\ethereum-full --keystore F:\keystore --port 30303 --nousb

INFO [09-28|10:38:47.956] Starting Geth on Ethereum mainnet...
INFO [09-28|10:38:47.972] Bumping default cache on mainnet         provided=1024 updated=4096
INFO [09-28|10:38:47.979] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-28|10:38:47.985] Set global gas cap                       cap=25000000
INFO [09-28|10:38:47.989] Allocated trie memory caches             clean=1023.00MiB dirty=1024.00MiB
INFO [09-28|10:38:47.994] Allocated cache and file handles         database=F:\ethereum-full\geth\chaindata cache=2.00GiB handles=8192
INFO [09-28|10:38:48.462] Opened ancient database                  database=F:\ethereum-full\geth\chaindata\ancient
INFO [09-28|10:38:48.522] Initialised chain configuration          config="{ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSupport: true EIP150: 2463000 EIP155: 2675000 EIP158: 2675000 Byzantium: 4370000 Constantinople: 7280000 Petersburg: 7280000 Istanbul: 9069000, Muir Glacier: 9200000, YOLO v1: <nil>, Engine: ethash}"
INFO [09-28|10:38:48.540] Disk storage enabled for ethash caches   dir=F:\ethereum-full\geth\ethash count=3
INFO [09-28|10:38:48.546] Disk storage enabled for ethash DAGs     dir=F:\Ethash count=2
INFO [09-28|10:38:48.551] Initialising Ethereum protocol           versions="[65 64 63]" network=1 dbversion=8
INFO [09-28|10:38:48.557] Loaded most recent local header          number=606284 hash="dc3976…c9f559" td=3528586994344036326 age=4y10mo3w
INFO [09-28|10:38:48.563] Loaded most recent local full block      number=606284 hash="dc3976…c9f559" td=3528586994344036326 age=4y10mo3w
INFO [09-28|10:38:48.567] Loaded most recent local fast block      number=606284 hash="dc3976…c9f559" td=3528586994344036326 age=4y10mo3w
WARN [09-28|10:38:48.571] Head state missing, repairing            number=606284 hash="dc3976…c9f559"
INFO [09-28|10:38:52.286] Deep froze chain segment                 blocks=26788 elapsed=3.764s number=516284 hash="0c6e7e…94c65c"

The command doesn't output anything more for a long time.
What's the progress of the sync now?


texts: How can I use geth's ecRecover to verify a signed message from TREZOR?

texts:
I cannot get this to work. I understand from this that TREZOR adds the magic message and a hexadecimal message length (as opposed to ASCII length) of the message before signing.

Is it just not possible to manipulate the given plaintext message by pre-pending the same data prior to sending over to geth for verification?


texts: Explore transaction from truffle test file

texts:
I have create this test:
const { expectEvent } = require('@openzeppelin/test-helpers');

const MyContract = artifacts.require('MyContract');

contract('MyContract', function (accounts) {
    const [owner] = accounts;

    beforeEach(async function () {
        this.myContract = await MyContract.new({from: owner});
    });

    describe('construction', function () {
        let txHash = this.myContract.transactionHash

    });
});

txHash contains the hash of the deployment transaction.
How can i access to all transaction fields (especially "from" field)
Thanks


texts: What are the differences between Bitcoin blockchain and Ethereum blockchain?

texts: Ethereum has been debated in the bitcoin ecosystem and was criticized. In order to understand better both projects, what are the main differences between BTC and ETH regarding the blockchain composition?


texts:
I have a Smart Contract that I'd like to build a web based marketplace app for. How can I list all available "Items" in the contract. Seeing as there is no upper limit to the number of minted Items, how can I implement pagination and search?
What is a best practice and scalable solution:

to simply return the Items[] array

sync the array with my database on Transfer and other events

other suggestions?
pragma solidity ^0.4.24;

contract Item is ERC721{

  struct Item{
      string name; // Name of the Item
      uint level; // Item Level
      uint rarityLevel;  // 1 = normal, 2 = rare, 3 = epic, 4 = legendary
  }

  Item[] public items; // First Item has Index 0
  address public owner;

  function Item() public {
      owner = msg.sender; // The Sender is the Owner; Ethereum Address of the Owner
  }

  function createItem(string _name, address _to) public{
      require(owner == msg.sender); // Only the Owner can create Items
      uint id = items.length; // Item ID = Length of the Array Items
      items.push(Item(_name,5,1)) // Item ("Sword",5,1)
      _mint(_to,id); // Assigns the Token to the Ethereum Address that is specified
  }

}


texts: TypeError: Cannot read property 'unlockAccount' of undefined

texts:
I have included all required modules while starting Geth:

instance: Geth/v1.9.9-stable-01744997/linux-amd64/go1.13.4

coinbase: 0x5c56bf111b3f894efae992e34a7be5be38950399

at block: 3078 (Mon, 06 Jan 2020 17:23:04 IST)
 datadir: /home/sama/Desktop/Navjeet/ethereum-private/Network/ethdata
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

Theese are the  personal methods provived by web3:

personal:
      Personal {
        currentProvider: [Getter/Setter],
        _requestManager: [Object],
        givenProvider: null,
        providers: [Object],
        _provider: [Object],
        setProvider: [Function],
        BatchRequest: [Function: bound Batch],
        extend: [Object],
        net: [Object],
        defaultAccount: [Getter/Setter],
        defaultBlock: [Getter/Setter],
        getAccounts: [Object],
        newAccount: [Object],
        unlockAccount: [Object],
        lockAccount: [Object],
        importRawKey: [Object],
        sendTransaction: [Object],
        signTransaction: [Object],
        sign: [Object],
        ecRecover: [Object] },

Still Not able to unlock account from node using web3 and also not able to create account using web3.personal.newAccount. I am ble to create new account using web3.eth.accounts.create(),but it is not showing in Geth console.I am using web3 version 1.2.4.  Please help.


texts: Error occurs when I attempt to run `npm install drizzle` (Truffle product)

texts:
I am having an issue using Drizzle. When I run the command npm install drizzle I get the following error:

How can I fix this?


texts: How do we use watch with an event in geth?

texts:
I have a geth client running (private) and I have a simple test contract to test events.

> con4.changedAge().watch()
{
  callbacks: [undefined],
  filterId: "0x3cf5f07c90dd95c5d97276659bf78d0f",
  getLogsCallbacks: [],
  implementation: {
    getLogs: function(),
    newFilter: function(),
    poll: function(),
    uninstallFilter: function()
  },
  options: {
    address: "0xa6b4017e8437ace3301f9751735e84836cfc0b21",
    from: undefined,
    fromBlock: undefined,
    to: undefined,
    toBlock: undefined,
    topics:
["0x25d30a71a6b93533225c97277375c3d49d3451741fad4852f106d04a5f083b5a"]
  },
  pollFilters: [],
  requestManager: {
    polls: {
      0x3cf5f07c90dd95c5d97276659bf78d0f: {
        data: {...},
        id: "0x3cf5f07c90dd95c5d97276659bf78d0f",
        callback: function(error, messages),
        uninstall: function()
      },
      0x49268254732d941a071b3c422d35104e: {
        data: {...},
        id: "0x49268254732d941a071b3c422d35104e",
        callback: function(error, messages),
        uninstall: function()
      }
    },
    provider: {
      newAccount: function(),
      openWallet: function(),
      send: function github.com/ethereum/go-ethereum/console.    (*bridge).Send-fm(),
      sendAsync: function github.com/ethereum/go-ethereum/console.    (*bridge).Send-fm(),
      sign: function(),
      unlockAccount: function()
    },
    timeout: {},
    poll: function(),
    reset: function(keepIsSyncing),
    send: function(data),
    sendAsync: function(data, callback),
    sendBatch: function(data, callback),
    setProvider: function(p),
    startPolling: function(data, pollId, callback, uninstall),
    stopPolling: function(pollId)
  },
  formatter: function(),
  get: function(callback),
  stopWatching: function(callback),
  watch: function(callback)

}

Here is the contract -

pragma solidity ^0.4.18;

contract CollegeAdmin {
uint public studentAge=18;
event changedAge(uint age);
function setAge(uint age) public {
studentAge = age;
changedAge(age);
}

}

I just want to test when the event is triggered. I thought something like con4.setAge(19) could then trigger the watch. Has anyone any ideas?


texts:
How to prevent smart contract from the vulnerabilities? what are all the security measurements we need to consider before publishing our smart contract?

Regards
Mani


texts: Ethereum selection of peer nodes and centralization

texts:
How does Ethereum select peer nodes when it starts ?
I guess there should be a set of nodes hardcoded in geth that it tries to connect to and then gets list of other nodes from them.
How many of those nodes is hardcoded into geth ?
Are they hardcoded by IP address or domain name ?
How would Ethereum network survive if all these nodes are shut down by joint governments ban.

Comparing Ethereum decentralization to Bitshares 101 nodes centralization, if there are less than 101 hardcoded initial peers in Ethereum, then it seems like it is not more decentralized than Bitshares, but far slower. Is my understanding correct ?

If not done already, are there any plans to publish list of active nodes on the blockchain so that next time geth starts it can try to connect to latest list rather than hardcoded list.


texts:
What does fat_db option in parity do? I don't understand its description from docs:

Build appropriate information to allow enumeration of all accounts and
storage keys. Doubles the size of the state database.

What kind of information is meant here?
Which RPC requests become available if I run fatdb?

Is "Doubles the size of database" just an estimation or is it always two times bigger?

Thanks


texts: Whether mnemonic can be same for ether and tron wallet?

texts:
If the 12 mnemonic words are always same for both ether and tron wallet, I can use same 12 words to create two different type wallets
Thanks.


texts: Can you transfer money from a smart contract to an eth address without writing code?

texts:
I have an ethereum contract, which linked to a wallet that I control (i.e. I have the private key).

The contract has 241 Ether in it. Is there an easy tool available to get the ether out of the contract? Or do I need to use the command line and operate on the contract to get the money to transfer?

Metamask, MEW and Ledger tools have, so far, not let me operate on the contract. I have geth on my machines too, but I'd prefer something point and click so I don't transpose a digit or something and mess anything up..

Thanks,


texts: Get each transactions from response of txpool.getContent()


texts:
I am trying to deploy some contracts on Ropsten network. Here is my code

async function finalDeploy(r){

  for(i=0; i<constructorParams.length; i++) {

    const options = {
      data: '0x' + myBin[r]+constructorParams[i],
      gas: 5000000,
  };
  const signed = await web3.eth.accounts.signTransaction(options, privateKey1);
  const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction); // here error occured
  console.log("Contract: " +r+" is deployed at  " +receipt.contractAddress);
  contractAddressess.push(receipt.contractAddress)

  }

}

The above code is working perfectly on Ganache UI, but when i changed its provider from localhost to Web3.providers.HttpProvider("https://ropsten.infura.io/v3/7fb0bdc97cbe419...");  then i am receiving this error ;

UnhandledPromiseRejectionWarning: Error: Returned error: nonce too low
    at Object.ErrorResponse (C:\Users\aa\node_modules\web3-core-helpers\src\errors.js:29:16)
    at C:\Users\aa\node_modules\web3-core-requestmanager\src\index.js:140:36
    at XMLHttpRequest.request.onreadystatechange (C:\Users\aa\node_modules\web3-providers-http\src\index.js:102:13)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:289:61)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1143:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
(node:3816) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


texts: Same MetaMask account can live in two computers at the same time?

texts:
I want to have my metamask account in both home and work computers at the same time. Is that possible?

I have already tried restoring my account in my home computer, but when I reopen the browser and the extension, metamask always ask me again to restore my account or create a new one, like in a new installation.

But in the other computer, it's always fine and I can go through as usual.

The other thing that I don't understand is that when I create a new account in metamask in Computer A it gives me a new address, and when I do the same creation operation in Computer B, it creates the same address?!

How is that happening, how Metamask in Computer A can be aware of Metamask in Computer B, if it is supposed that every account within metamask is independent from the other even they both live in that extension.

I hope my explanation isn't very confusing, feel free to ask in the comments.


texts: Why solidity 0.5.0 not working in remix?

texts: When I select the solidity version 0.5.0 in the remix, it never loads. New version is already released, so why is it not loading in the remix?


texts:
I am trying to understand proof of stake consensus. I found some explanation about the "nothing at stake problem at the Ethereum wiki.

Here is the part about the "Slasher"-solution i don't understand:

  Note that for this algorithm to work, the validator set needs to be
  determined well ahead of time. Otherwise, if a validator has 1% of the
  stake, then if there are two branches A and B then 0.99% of the time
  the validator will be eligible to stake only on A and not on B, 0.99%
  of the time the validator will be eligible to stake on B and not on A,
  and only 0.01% of the time will the validator will be eligible to
  stake on both. Hence, the validator can with 99% efficiency
  probabilistically double-stake: stake on A if possible, stake on B if
  possible, and only if the choice between both is open stake on the
  longer chain. This can only be avoided if the validator selection is
  the same for every block on both branches, which requires the
  validators to be selected at a time before the fork takes place.

Can someone explain this in simpler terms and explain where those probabilities come from?


texts:
Is it possible to add a new header to ethereums block header without messing up go-ethereums core too much.. im looking at the block.go file specifically at this part... see the custom super header i have added I. Ive also added this new field to the genesis file but when syncing i get that the signer is unauthorized to do so. anyone have experience with doing this kind of heavy modification ?

    type Header struct {
        ParentHash      common.Hash    `json:"parentHash"       gencodec:"required"`
        UncleHash       common.Hash    `json:"sha3Uncles"       gencodec:"required"`
        Coinbase        common.Address `json:"miner"            gencodec:"required"`
        Root            common.Hash    `json:"stateRoot"        gencodec:"required"`
        TxHash          common.Hash    `json:"transactionsRoot" gencodec:"required"`
        ReceiptHash     common.Hash    `json:"receiptsRoot"     gencodec:"required"`
        Bloom           Bloom          `json:"logsBloom"        gencodec:"required"`
        Difficulty      *big.Int       `json:"difficulty"       gencodec:"required"`
        Number          *big.Int       `json:"number"           gencodec:"required"`
        GasLimit        uint64         `json:"gasLimit"         gencodec:"required"`
        GasUsed         uint64         `json:"gasUsed"          gencodec:"required"`
        Time            *big.Int       `json:"timestamp"        gencodec:"required"`
        Extra           []byte         `json:"extraData"        gencodec:"required"`
        MixDigest       common.Hash    `json:"mixHash"          gencodec:"required"`
        Nonce           BlockNonce     `json:"nonce"            gencodec:"required"`
        SuperCustomData []byte         `json:"superCustomData"        gencodec:"required"`
    }


texts: Ethereum - Exporting Accounts/Balances from full node

texts:
I have a Ethereum full node that I will be using to take a snapshot for an airdrop for a project I am working on. The node is running and syncing.

The issue currently is that there doesn't seem to be much out there to show how to export a list of accounts and their balances in a CSV I can use to then use for our airdrop.

I've tried using the web3 dumpBlock method, but it takes far too long. I did something similar for BTC and it took only a few minutes.

How can I can the 'worldstate' of the chain and output the accounts and balances into a CSV?

Any direction would be help! Thanks!


texts:
,/C/Users/juhne/ipfs-image-dapp/contracts/Migrations.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.23;
^----------------------^
Error: Truffle is currently using solc 0.5.16, but one or more of your contracts specify "pragma solidity ^0.4.24".
Please update your truffle config or pragma statement(s).
(See https://truffleframework.com/docs/truffle/reference/configuration#compiler-configuration for information on
configuring Truffle to use a specific solc compiler version.)
i change the specific version in truffle.js but the error still show i using 0.5.16 version...
compiler:{
solc :{
version : " 0.4.20"
}
},


texts:
I am trying to change source code in go-ethereum so that I can learn how it works.

Let's say in flags.go file, there's log.Info("Set global gas cap", "cap", cfg.RPCGasCap), so I change the string set global gas cap to My test.
Then I run make all ...
Then I run geth --ropsten console.

The problem is when it starts, it still shows the old string - set global gas cap instead of my test. It doesn't matter what I change in source code, the same issue happens.
What am I missing ?
UPDATE:

I have GOPATH set to /Users/jordan/go .
in /Users/jordan/go, There's bin and pkg folders and also there's src folder and my ethereum code is placed in /Users/jordan/go/src/github.com/ethereum/go-ethereum.
I change the code and do make all. I also try another approach - I go to cmd/geth and I do go build ./ and then use the built geth.
I run geth --ropsten console and my changed code still doesn't take any effect at all.


texts: Is there any way to prevent copied DApps?

texts: I'm a game developer with an idea for Ethereum that would require players to pay a small fee to play. If the contracts are open-source, what would stop someone from duplicating the contract and replacing my address with theirs? Is there a better monetization scheme? If I didn't make my front end open-source, would anyone even trust it?


texts: Can the ethereum attach message like bitcoin in transaction?

texts: Can the ethereum attach a message in transaction? for example, l want attach the message "hello" in common transaction(not contract create). thanks


texts: What is the maximum number of validators in current PoC of Eth2.0?

texts:
In the current spec no maximum number of validators is mentioned: https://github.com/ethereum/eth2.0-specs/blob/master/specs/beacon-chain.md
but is there some implicit upper bound for the number of validators?


texts: Why is mstore not working here? (assembly)

texts:
function debug() returns (bytes) {
        bytes memory ret = new bytes(6);
        bytes memory word = new bytes(6);
        word = hex"61626f757400";
        assembly {
            mstore(add(ret, 32), word)
        }
        return ret;
}

returns 0x000000000000, desired outcome return 0x61626f757400


texts: Is authentication effectively decentralised?

texts:
I can't quite see the solution to this; so I'm questioning for clarity. My understanding from the docs is that it appears that the process is dentralised:

Generate your private key (according to certain recommendations).
Generate your public key from the secp256k1 implementation.
Generate your Ethereum address.

Is that how it works? If it is it looks decentralised.


texts: Fees distributed to token holders at point of sale

texts:
With the recent increase in deflationary 'meme tokens', which I won't name on here, I've noticed that whilst holding these tokens not only is the total supply increasing but a percentage of the fee, appears to be appended to all token holder balances based upon the % of total supply held by a wallet. In essence, my wallets token balance is increased whenever someone sells a token.
This was the first time I was exposed to something like this beyond the typical staking/withdrawal method described by Bogdan Batog, et al. in "Scalable Reward Distribution on the Ethereum Blockchain", which was my first thought for network fee redistribution/discount to network users who hold a token supply.
As I'm looking to redistribute network fees to my token holders I've been trying to chase down how this works exactly, not sure if it's related to the UniswapV2 interface, or if it's to do with increasing the allowance all token holders are able to spend upon the owners behalf, and during this time these tokens are held in escrow by the owner/contract? However, when I attempted to call and fetch my allowance, at least from the contracts balance I could not see that, nor did I see any references within the contract.
It seems that a raw call to blanaceOf(address holder) will always show the most up to date balance for that holder, and the contracts I have seen which enable this ability to append fees to balance do not appear to be appending the result of allowance(...) to the wallet's balance. Therefore I can only assume they are actually appending the balance of wallets from within the contract?
If someone in the know could point me in the right direction I'd really appreciate it. I understand I'm simply describing in text, if you feel it's helpful for me to further elaborate please let me know.


texts: Why does the transaction stay in queue from more than 240 second

texts:
I am running quorum nodes via the Quorum-maker script, and when trying to call functions from my already deployed smart contract, I get this error :

Transaction 0xe5f8c89e132ab29fa02702ea957318d7b45f788093086f1c452657c92f6e8f8c
wasn't processed in 240 seconds!

I admit I am calling the function in a for loop over 250 times, but that isn't supposed to interfere with the queue, right?
My function call is just a simple adding of a person in a person mapping nothing complex. What can the problem be?


texts: how to setup a ethereum private blockchain?

texts: Does anyone know how to set up a private blockchain in ethereum network? is that possible to run a private ethereum node? I have seen forking of public blockchain like EOS into a private blockchain.i wonder is that possible in ethereum also?


texts: How wallets and web3 find public key from private key?

texts: How is it possible for wallets like MetaMask or libraries like web3js to find public key by only providing private key? AFAIK this is not possible generally in elliptic curve.


texts: Can Contract Accounts send Messages to EOAs?

texts:
I often hear the following statement:

Contract Accounts cannot send Messages to EOAs. They can only:
  1. send Messages to other Contract Accounts
  2. send Ether to EOAs

... see, e.g., here: Are contracts able to send messages to EOA's?

This statement does not really make sense to me. According to the Ethereum Docs (see http://www.ethdocs.org/en/latest/contracts-and-transactions/account-types-gas-and-transactions.html#what-is-a-message) a message contains:
1. the sender of the message (implicit)
2. the recipient of the message
3. VALUE field - The amount of wei to transfer
4. an optional data field
5. STARTGAS value

So when a Contract Account sends Ether to an EOA, it does so by sending a Message with an empty data field and containing the amount of Ether/Wei to be transferred in the VALUE field, right?

That is, Contract Accounts do send Messages to EOAs but the data field of these messages is empty, correct?


texts:
I initialize a node on my private test net passing only the eth interface in the ipcapi parameter expecting that I won't have access in the other interfaces such as admin etc.. However, when I attach a terminal to the node I have access to all apis. What is the puprpose of the ipcapi parameter then?

this is how I initialize start the node listening to ipc connections

geth --datadir ~/ethereum/localnode --ipcapi eth --networkid 1234 console


texts: Out of gas only when transferring ICX token

texts:
I get the following error

Warning! Error encountered during contract execution [Out of gas]

ONLY with $ICX token, it works fine with all other tokens I am transferring. Is this even possible and how do I troubleshot it?


texts: JavaScript console on Parity: How could I import account's private key, which I would like to unlock?

texts:
In native geth applicaton, I was able to unlock accounts with only account address and its passphrase.

How to open the JavaScript console on Parity? guide us to open a console for communicate with Parity.

When I use JavaScript console on Parity, I was not able to do the same. Please see following JavaScript console on Parity: unable to unlock account. Error: Method not found.

I have told that:

  You can't unlock an account without private key.

Based on that; using JavaScript console on Parity: How could I import account's private key(which was created using geth), which I would like to unlock?


texts: ConsenSys/eth-lightwallet - How does it work?

texts:
I am using example webwallet.html from https://github.com/ConsenSys/eth-lightwallet

It seems to work for me but I am confused on how does it actually work. Can someone explain to me please?

Here is what  tried, in webwallet.html, I use localhost:8545 as host. I do not even connect my computer to internet. I give seed and password and I get 3 addresses.

Now from totally different computer I go to https://lightwallet.io, give the seed and password and I get the same 3 addresses as I saw in my local webwallet.html

I wonder how does other computer able to restore and get same 3 addresses?

Please can someone explain me how does this webwallet.html working?


texts: From a technical perspective, is MultiSigna a decentralized exchange utilizing ethereum?

texts:
Does anyone know how we would be able to either view the Ethereum blockchain or inspect the code from Multisigna to confirm if it is a true ethereum decentralized exchange?

Source: https://www.multisigna.com/login.php#

This is pulled from their FAQ:

MultiSigna is a market established in the internet that sets in contact users interested in exchanging fiat ($,€) or crypto (Ethereum) currency for Bitcoin and vice versa. MultiSigna role is to offer the proper structure that allows monitoring and managing step by step the exchange process between the users, keeping the seller’s bitcoins in a multisignature address until the seller has received the counterpart ($,€,ETH). In that moment the bitcoins are transferred to the buyer and the buy/sell operation comes to an end. The protocol developed by MultiSigna allows performing those exchanges in a secure and agile way.


texts: What is the most common 3rd party KYC provider to use for an ICO?

texts:
I am looking for some 3rd party KYC options to use for an ICO. What are the typical companies used by successful or respected ICOs?

Also how do these companies work for KYC if the investor later changes their passport or address?


texts: Web3 - How to determine when a transaction has been mined?

texts:
I am executing a transfer() function in a solidity contract, and want to know when the transaction is finished. I can get the transaction receipt immediately if the transaction is executed properly, but want a simple way of knowing when it's been mined. This is what I've tried (a bit messy):

deployedContract.transfer(transfer_to, transfer_value, { from:web3.eth.accounts[0], gas: 200000 }, function (error, result) {
      if (!error) {
        console.log(result + ' is the TxHash')
        var test = web3.eth.getTransactionReceipt(result, function (error, result2) {
          if (!error) {
            if (!result2) {
              console.log('waiting for transaction to be mined....')
              console.log(result + ' is still the TxHash')
            } else {
              console.log('transaction done')
            }
          } else {
            console.error(error)
          }
        })
      } else {
        console.error(error)
      }
    })

This will get to the console.log('waiting for transaction to be mined....') part but even after the transaction is definitely mined, won't get to the console.log('transaction done').

If it's relevant, when deploying a new contract I could easily see when the transaction was complete as follows - but doing the same thing isn't working for me for seeing if functions executed on a contract have completed:

let deployedContract = contract.new({ from:web3.eth.accounts[0], data:bytecode, gas: 1300000 }, function (error, result) {
        if (!error) {
          if (!deployedContract.address) {
            // transaction hasn't been mined yet
          } else {
            // transaction has been mined
          }
        } else { console.error(error) }
      })


texts:
I have a project in Infura and the project ID is 6f...3a. I'm having problem to start geth attach process with Infura.

I tried all protocols (http, https, ws and wss) but all failed.
Did I miss something here?


texts: How can I call transfer function of a ERC20 token contract from another contract?

texts: I want to exchange token for a commodity using smart contracts. I have deployed my token contract address in my private block chain network. How should I create another contract that exchanges a commodity using the transfer function from the deployed token contract?


texts: How get Ethereum address using phrase only in Android

texts:
I want to get Etherum address and private key by adding Phrase (or Password) everytime.
I tried by following many gihub code.It gives different private key everytime.
In Web3j, I found it is based on file.

I want to make a programme in such a way that it will create same wallet again (Based on password or phrase).

Is there any way.If yes than please share your knowledge.


texts: How to deploy more than one contract with Remix

texts:
I'm trying to deploy my contracts with Remix to Ropsten, but I don't know how to do it. Can you help me?
(I have a ERC20 token contract, and a CrowdSale contract)


texts: how to use MEW, (not geth or mist) to use a private key to recover access to some ERC20 tokenss

texts: I lost my jaxx backup phrase. I have private keys to two ERC20 tokens (ICN and SALT). I want to use MEW to regain access/link to my tokens on the blockchain. What are the exact steps in MEW to use private key to relink/pair MEW to these tokens. I've looked for an hour at help and googled it. (I'd use JAXX's 'paper wallet transfer' function to do this, but that function is broken/buggy.)  I can only find geth or mist instructions, but i want to simply use MEW for this recovery.


texts: solidity return the mapping(struct) not work

texts:
pragma solidity ^0.4.4;

contract heheBox {

    struct DataBox {
        mapping(address => string) Data_01;
        mapping(address => string) Data_02;
    }

    mapping(address => DataBox) DataBox_hehe;

    function save(string _InputData_01, string _InputData_02) public  {
        DataBox_hehe[msg.sender].Data_01[msg.sender] = _InputData_01;
        DataBox_hehe[msg.sender].Data_02[msg.sender] = _InputData_02;
    }

    function display(address _address) constant public returns (struct) {
        return DataBox_hehe[_address];
    }

}

I wish the function display to display the mapping DataBox_hehe but it doesn't. Can anyone can teach me how can do this?

thank you very much!!


texts: How to retrieve all the values form the mapping?

texts:
Yield farming. Unaudited food token. Anon founder. Crazy APR%. Of course,  if it is  "too good to be true" it probably is...
I would like to "don't trust, verify" and verify who is authorized:
contract Authorizable is Ownable {

    mapping(address => bool) public authorized;

    modifier onlyAuthorized() {
        require(authorized[msg.sender] || owner() == msg.sender);
        _;
    }

    function addAuthorized(address _toAdd) onlyOwner public {
        authorized[_toAdd] = true;
    }

    function removeAuthorized(address _toRemove) onlyOwner public {
        require(_toRemove != msg.sender);
        authorized[_toRemove] = false;
    }

}

It is mapping. It is not an array. I cannot iterate. Adding a guy does not emit the event.
Do I need to write some code to analyze every single transaction to the smart contract?
Or maybe there is some tool / technique / quirk / workaround to the rescue?


texts: TransferHelper: TRANSFER_FROM_FAILED unable to swap token to token uniswap

texts:
I am trying to swap using WETH from my contract to DAI using swapExactTokensForTokens(amountIn, amountOutMin, getPathForETHtoToken(tokenAddress), address(this), deadline) with uniswap. First I approved large amount on both DAI and WETH address then I deposited 0.01 worth of WETH using:
function wrap() public payable restricted {
    if (msg.value != 0) {
      WETH.deposit{value : msg.value}();
      WETH.transfer(address(this), msg.value);
    }
  }

on my contract and now able to see the balance in WETH
Next on remix I filled out the parameters for my swap function
function Buy(uint amountIn, uint amountOutMin, uint deadline, address tokenAddress) external payable restricted {
    uniswapRouter.swapExactTokensForTokens(amountIn, amountOutMin, getPathForETHtoToken(tokenAddress), address(this), deadline);
}

// amountIn = 10000000000000000, amountOutMin = 4029840000000000000, etc

And when I execute I get this error
Fail with error 'TransferHelper: TRANSFER_FROM_FAILED'

How do I resolve this issue?


texts: Getting "no key for given address or file" error when trying to unlock account in geth

texts:
I'm trying to unlock an ethereum user account using geth, but am getting an error message that doesn't make sense to me.

Here's what I do:

1) I start the geth console connected to the ropsten network:

geth --testnet console

2) Then I try to use the personal.unlockAccount method:

personal.unlockAccount('<account address>', '<key phrase>', 1000);

Then I get the error:

  Error: no key for given address or file

I'm not sure why I might be getting this message or what it means exactly. Can anyone help?


texts:
I am trying to do subtraction operation using the SafeMath library. The following is my code:

pragma solidity ^0.5.1;
library SafeMath {
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    assert(b <= a);
    return a - b;
  }
}
contract Underflow1 {
using SafeMath for uint;
    uint8 num= 0;
    function testf2() public returns (uint8){
    //val--;
    num= num.sub(1);
    return num;
    }
}

I am getting following error message:

  browser/UF8-SM.sol:13:10: TypeError: Member "sub" not found or not
  visible after argument-dependent lookup in uint8. num= num.sub(1);
  ^-----^

Somebody please guide me.

Zulfi.


texts: How does Ethereum work as a decentralized computing platform?

texts:
As far as I understand, gas is paid out to the miners, but every node
in the network runs each and every contract that is submitted to the blockchain.
Doesn't this mean that other ethereum nodes are running lots of code for free?  Also if every node is running all of the code all of the time, doesn't that mean that the combined computing power of ethereum is equal to that of just one computer?

If this is truly the case, then why is it being talked about as if it could replace things like AWS?
If this is not the case, then how is the result of running a smart contract verified?

All of the resources I've been able to find on Ethereum are very hard to follow especially regarding this question.


texts: crowdsale contract on my Ethereum Wallet for windows

texts:
I first created a token without difficulty with Ethereum Wallet can be see here: https://etherscan.io/address/0x926351469a1a97Ca5AB9b80928a0Ba01493d39F9#readContract.

Now I'm trying to do a crowdsale contract with the code that I have find on this link https://www.ethereum.org/crowdsale

But I can't see on the right column of My Ethereum Wallet the "Select contract to deploy" option.

it says No visibility specified. Defaulting to "public".
    function transfer(address receiver, uint amount);
^-----------------------------------------------^,

I guess I got it wrong, I'm not a developer or coder, but curious to learn.

Can someone tell me what did I do wrong ?

Thanks,

Benj


texts:
Sometimes, when I use the ganache specific evm_increaseTime method and advance to the next block, the next timestamp is NOT:

current timestamp + advanced time

But instead:

current timestamp + advanced time + 1 second

Where does this second come from? Is it the core compute time of the transaction? Leap seconds?

RPC logs:

eth_sendTransaction

  Transaction: 0x9cc8e2006d13f3349594a284a8f9ec8489c8bff6d57022143bb4457b30ee50b1
  Gas usage: 224072
  Block Number: 226
  Block Time: Fri Aug 09 2019 11:01:40 GMT+0200 (Central European Summer Time)

eth_getTransactionReceipt
evm_increaseTime
evm_mine
eth_getBlockByNumber
eth_getBlockByNumber
eth_getBlockByNumber
eth_call
eth_getBlockByNumber
eth_call
eth_getBlockByNumber
eth_sendTransaction

  Transaction: 0x2126e0a1ac901864c7dacabb7a6228f6753e5ad3ceb65f1957ecaaa395bc8569
  Gas usage: 72408
  Block Number: 228
  Block Time: Fri Aug 09 2019 11:02:46 GMT+0200 (Central European Summer Time)

eth_getTransactionReceipt
eth_getBlockByNumber
eth_call
eth_getBlockByNumber
eth_call

And you can see, the second time stamp is "11:02:46" whereas it should be "11:02:45", because the code that I'm executing in the tests is this:

web3.utils.advanceTimeAndBlock(new BigNumber(65));


texts: In a clique consensus private network, what happens when a sealer (signer) stops mining

texts:
I create a private network with two sealers running on two separate nodes. I found that if one node stops signing by miner.stop(), the other one start to wait for it and stoped signing blocks too. The info log is like

INFO [11-22|14:38:26.031] Signed recently, must wait for others

What happens when a sealer (signer) stops mining if there are several sealers in a network.


texts:
I'm using Infura as my provider. From what I've read online, it seems that using a websocket with infura instead of http is the first step to being able to hear events however I only get an empty list when I retrieve all the latest events

I have a script that causes the contract to emit an event every 20 seconds.

This is what I'm using to test hearing events

    events = contract_ws.events.Transfer.createFilter(fromBlock="latest", toBlock="pending").get_all_entries()
    if (len(events) != 0):
        break
    else:
        print("Not yet.")
        time.sleep(3)

But it never breaks out of the loop so therefore never hears an event. What am I missing?

I'm using the web3py library but I don't think that'll effect the solution.


texts:
I am using Phoenix Miner - Ran it for around 8 to 10 hours as a trial - I setup my Public Wallet ID as My wallet ID, I have yet to see anything pending into my account - I am wondering If I am missing something? It's been around 12 to 14 hours since I have ran it.
I am using Meta Mask as the wallet - from what I have heard this is good for short term for the funds to go into the account . I can upload my setup file later in case I am missing something as well but no errors the miner runs just fun I just haven't seen anything and do not want to continue until I get that sorted.
Thanks in advance for any help given .


texts: Getting an error cannot read property "encodeParameters" of undefined

texts: I am running a node.js server but while running it, i am getting following error. what could be the possible reason?


texts:
I want my website users to have a new ethereum address after registration into my website.

How is it possible with web3 to generate new ethereum address for each user of my website?

Does it require password too while creating new address?

Can i have some sample code?


texts:
At some point, the local Geth node reported tx 2e7a57c55a7cb28d0e233d7745210dba93c09f14c5df4e879db1a530a79a842a in the block 1369316 on testnet. It then disappeared from the chain at some point during the next 1-12 blocks.

That same tx reappeared after 90 blocks on the block 1369406 and now is part of the blockchain.

How can this happen and what edge case we are not handling properly? We were in the understanding that waiting for 12 blocks would be sufficient.

Is this caused by a fork or a replay attack? If yes, how should this be handled?


texts:
Infura has a testnet: https://explorer.infuranet.io/.  I don't see anything in the docs about getting testnet ether on their testnet.

Does anyone know how to?


texts: Is it possible to import a Jaxx walet into Mist?

texts:
I have installed Jaxx on my smartphone and have some ETH in it, I've sen a small amount to the DAO address. If I at a later stage want to intereact with the DAO and Jaxx doesn't allow for this, is it possible to import my Jaxx wallet into Mist?

Jaxx is a deterministic wallet right? A bit like MultiBit HD is for Bitcoin? So does Mist allow for importing a wallet with a mnemonic key? Or is that feature planned? Or can I assume another wallet will come along in the future that has full capabilities and will be able to i;port my Jaxx wallet?


texts: Which smart contract should I use to wrap Eth

texts:
I need Weth for my dapp. So I looked at how AirSwap converts ETH to Weth. On the Rinkeby testnet, AirSwap calls this contract and uses the "deposit" function. I see from the code how this would work. Also I can see that this contract is owned by 0x.

My question is: Can I just call that exact contract for my Dapp too? Is this the recommended way to exchange Weth for Eth?


texts: get amount of transferred tokens from transaction receipt

texts:
Can someone explain to me how to get the amount of tokens that have been transfered from a transaction receipt? I came across some posts that said I can get it out of the data property from the receipt. But how can I turn the data value into a readable amount of tokens? Some others said it can be found in the logs. The transaction itself has a value of 0 on erc20 token transfers, so I need using the receipt is what I understood so far.
Thank you