texts: Why am I Getting: Transaction Error. Exception thrown in contract code in Rinkeby?

texts:
I'm creating a token that generates new tokens every time ETH is sent to it. It takes those newly generated tokens and sends them to the wallet address that sent the ETH. The maxTokens is 40mil. The RATE is 20mil (trying to keep things simple for my test). It's pretty straightforward.

The issue I'm encountering with my test contract is that trying to send 1 ETH is fine and the transaction goes through. Trying to send a greater amount, like say 1.5, produces this warning: "Transaction Error. Exception thrown in contract code.
Gas limit set dangerously high. Approving this transaction is likely to fail."

After playing around for a while I realized that I could send smaller amounts of ETH that would go through after sending the 1ETH. However, the closer I got to the max tokens I would get the above mentioned error.

Can anyone explain why I am getting this error? I can't understand why an error is producing when someone sends an amount of ETH that is relatively close to the maxTokens.

Edit: I have successfully been able to buy up to 39,999,700 of the tokens. However, I have to keep buying smaller amounts each time or else I get the above mentioned errors.

pragma solidity ^0.4.11;

import './IERC20.sol';
import './SafeMath.sol';

contract ChekOutToken is IERC20 {

using SafeMath for uint256;

uint public _totalSupply = 0;

string public constant symbol = "CHEKS";
string public constant name = "ChekOut Token";
uint8 public constant decimals = 18;

// 1 ETH = 1000 CHEKS
uint256 public constant RATE = 20000000;

// Sets Maximum Tokens to be Created
uint256 public constant maxTokens = 40000000000000000000000000;

address public owner;

mapping (address => uint256) public balances;
mapping(address => mapping(address => uint256)) allowed;

function () payable{
    createTokens();
}

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

function createTokens() payable{
    require(msg.value > 0);
    require(_totalSupply.add(tokens) <= maxTokens);
    uint256 tokens = msg.value.mul(RATE);
    balances[msg.sender] = balances[msg.sender].add(tokens);
    _totalSupply = _totalSupply.add(tokens);
    owner.transfer(msg.value);
    require(_totalSupply.add(tokens) <= maxTokens);
}

function totalSupply() public constant returns (uint256 totalSupply) {
    return _totalSupply;
}

function balanceOf(address _owner) public constant returns (uint256 balance) {
    return balances[_owner];
}

function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value && _value > 0);
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
}

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
    require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
    balances[_from] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
    Transfer(_from, _to, _value);
    return true;
}

function approve(address _spender, uint256 _value) public returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
}

function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
}

event Transfer(address indexed _from, address indexed _to, uint256 _value);

event Approval(address indexed _owner, address indexed _spender, uint256 _value);

}


texts: Transactions Stuck. Offline transaction cancelling is not working either

texts:
Transaction is stuck pending, so I used Myetherwallet to generate an offline transaction with the same nonce as the pending transaction, YET once the transaction is posted, I see that the nonce generated is higher than the chosen number.

The first pending transaction with nonce 12. (While the block explorer says its pending, metamask labels it as cancelled)
https://etherscan.io/tx/0x506bc1cded5cca7fac98a75dca45a0590cc6b7ade7f195ee16beed6b35bb490d

The second transaction used to cancel the previous one - https://etherscan.io/tx/0x6749f3c4a2603df1b910b30f5aee8c246975f347e62eabf119b9e8d02d0fffc1


texts: Accessing/Modifying Options Parameters in Contract

texts:
I'm using truffle and metamask to deploy a very simple contract that enables the transfer of ether from one test account to another.

How do I use my JavaScript file to access the options parameters that were passed in during deployment? Can the constructor parameters passed in during deployment be modified afterwards?

Here's the line in 2_deploy_contracts.js:

deployer.deploy(EscrowPayment, web3.eth.accounts[1], web3.eth.accounts[2], {gas: 4400000, value: web3.toWei(20, 'ether')});

The options parameter would be {gas: 4400000, value: web3.toWei(20, 'ether')}

Here's the constructor in the contract:

function EscrowPayment(address _seller, address _judge) payable {
    buyer = msg.sender;
    seller = _seller;
    judge = _judge;
}

I read this documentation but wasn't able to do something like "myContract.options"


texts: Getting key from Solidity mapping by value

texts:
I want to store a key-value pair in a Smart Contract.
For example:

mapping(uint => address) public myMapping;

And I would like to have public access to both:

value by key
key by value

I can get value by key in web3js by this way:

contract.myMapping.call(key, function(err, val) {
   ...
});

Is it possible to get key by value from mapping using web3js, or access in both directions can be done only with creating of 2 mappings?


texts: How to compile Solidity ^0.5.5 contract with Node.js?

texts:
I am terribly new in Solidity and now I try to learn how to compile a contract in Solidity ^0.5.5 (No versions below).

I have the contract as follow (UsersContract.sol)

pragma solidity ^0.5.5;

contract UsersContract {

    struct User {
        string name;
        string surname;
    }
    mapping(address => User) private users;
    mapping(address => bool) private joinedUsers;
    address[] total;
    event OnUserJoined(address, string);

    function join(string memory name, string memory surname) public {
        require(!userJoined(msg.sender));
        User storage user = users[msg.sender];
        user.name = name;
        user.surname = surname;
        joinedUsers[msg.sender] = true;
        total.push(msg.sender);

        emit OnUserJoined(msg.sender, string(abi.encodePacked(user.name, "
    ", user.surname)));
}

    function getUser(address addr) public view returns (string memory,
string memory) {
        require(userJoined(msg.sender));
        User memory user = users[addr];
        return (user.name, user.surname);
}

    function userJoined(address addr) private view returns (bool){
        return joinedUsers[addr];
    }

    function totalUsers() public view returns (uint){
        return total.length;
    }
}

Next the compilator called (compile.js):

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const contractPath = path.join(__dirname,'../contracts','UsersContract.sol');
const source = fs.readFileSync(contractPath, 'UTF-8');

const input = {
    language: 'Solidity',
    sources: {
        'UsersContract.sol': {
            content: source
        }
    },

    settings: {
        outputSelection: {
            '*': {
                '*': [ '*' ]
            }
        }
    }
}

function findImports (path) {
    if (path === 'UsersContract.sol')
        return { contents: source }
    else
        return { error: 'File not found' }
}

const output = JSON.parse(solc.compile(JSON.stringify(input), findImports));
module.exports.output = output;

And finally the file where I execute the tests before to run them (UsersContract.test.js)

const assert = require('assert');
const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"); // GANACHE RPC SERVER
const web3 = new Web3(provider);
const { interface, bytecode } = require('../contracts/compile.js');

let accounts;
let usersContract;

beforeEach(async() => {

    accounts = await web3.eth.getAccounts();
    usersContract = await new web3.eth.Contract(JSON.parse(interface))
        .deploy({ data: bytecode })
        .send({ from: accounts[1], gas: 1000000});

});

describe('The UsersContract', async() => {

    it('should deploy', () => {
        console.log(usersContract.options.address);
        assert.ok(usersContract.options.address);
    });

});

The main problem is, everytime I execute npx mocha to try the test I get the next error:

The UsersContract
    1) "before each" hook for "should deploy"

  0 passing (59ms)
  1 failing

  1) "before each" hook for "should deploy":
     SyntaxError: Unexpected token u in JSON at position 0
      at JSON.parse (<anonymous>)
      at Context.beforeEach (test/UsersContract.test.js:24:54)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:182:7)

Any help? Any idea? I don't know where or what I am doing wrong right now.

PD: I let here the package.json information. Hope it helps.

{
  "name": "compile-and-deploy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "mocha": "^5.2.0",
    "solc": "^0.5.5",
    "web3": "^1.0.0-beta.35"
  }
}


texts:
I am trying to measure chain insert rates in a Geth node.

In a deprecated Go-ethereum blog, it says I can use debug.metrics(false) to get all available metrics (so I can use debug.metrics().chain.inserts to get insert rates).

However, that no longer holds. When I tested on the console, even with --metrics flag added in starting a Geth node, the console continues to complain the debug object "has no member 'metrics'".

Here is my output when I type "debug. ", and by the way, it shows a lot more than the options listed here.

I then went to the codebase, and see metrics objects are still there. I am wondering how can I get some metrics reports as the outputs in the deprecated blog.

Any help is appreciated!


texts: Is there a way to cap CPU usage in Parity?

texts:
I have a non-useless Macbook Air running High Sierra. I've tried using both Mist & Parity, but alarmingly, I've found that both Ethereum clients have no respect for my CPU load when syncing. Parity maxes out every core and grinds the system to a halt constantly. The only solution is to turn off syncing or kill Parity entirely. Since I'm a developer, this is unacceptable -- I need the JSON-RPC interface and I absolutely can't live without it.

Two issues on Parity's GitHub are triaged for different versions and closed, but I don't see any results from these issues. Does that mean they were never actually solved?

Closed issues:

https://github.com/paritytech/parity/issues/6978
https://github.com/paritytech/parity/issues/6300

Is there any way to tell Parity to cap its CPU utilization to a certain threshold?


texts: Is using oraclize to schedule using execution of a function asynchronous?

texts: I am looking for ways to automatically execute a function call every 24 hours in my smart contract and came across this answer. Is the solution here asynchronous, i.e. can the contract execute other functions while it's waiting for the callback?


texts: Can erc721 belong to another erc721 token?

texts:
I learnt somewhere today that an erc721 token doesn't have to belong to an account, it could belong to another erc721!

How can this be implemented? where can I read more of this?

Thanks


texts: Restrict ERC20 transfer and reception to owners of a particular NFT

texts:
I need to create an ERC20 token which transfer and reception is restricted by a membership, indicated by an NFT (ERC721) in the sender's and receiver's address/wallet.
How can I check in the ERC20 transfer() function whether the sender and receiver are owner of that particular NFT (ERC721, membership)?


texts:
When I run ./parity under /target/release it automatically connects to the public Ethereum blockchain. (It starts syncing with the actual Ethereum blockchain of 900,000 blocks.)

I want to connect into my local Ethereum blockchain that I have created.

[Q] How could I make Parity connect with my local Ethereum blockchain?

I have an ongoing local Ethereum blockchain.

I am running my server as:

geth --rpc --datadir "/Users/avatar/Library/MyEthereumEbloc" --dev --unlock 0
--minerthreads 1 --targetgaslimit "994712388"
--ipcpath "/Users/avatar/Library/MyEthereumEbloc/geth.ipc"  --bootnodes
enode://8cc3166d6e3ca794d95a00ba7d42127bffe5cd08a89d08ff6adfd
2f552b7309702110ee3f10996cdeca0b792922e1cc257
c4f9f6fd62eb2c2987231e39e5761f@78.120.155.145:3000
--port 3000 --networkid "23444" console

I am running my client as:

geth --datadir "/Users/avatar/Library/MyEthereumEbloc"
--dev attach ipc:/Users/avatar/Library/MyEthereumEbloc/geth.ipc

Thank you for your valuable help.


texts: Truffle web3.eth.sign produces wrong signature

texts:
Somehow truffle produces an invalid signature.
To clarify this I imported the private key of the first Ganache account to metamask and compared the results.

The following code used in a chrome console returns the following (verifiable correct) signature:

// frontend
let msg = web3.sha3("truffle"); // => 0x28610e27d085e348e6ebd0da2c982947eddf7d308b82e951a896432cdac99a74
let sig;
web3.eth.sign(web3.eth.accounts[0], msg, (err, res) => {
  if(!err) {
    sig = res;
  }
})

// sig => 0xb453386b73ba5608314e9b4c7890a4bd12cc24c2c7bdf5f87778960ff85c56a8520dabdbea357fc561120dd2625bd8a904f35bdb4b153cf706b6ff25bb0d898d1c

Here's the code in truffle which should produce the same signature - but doesn't.

// Truffle:
let first = accounts[0];
let msg = web3.sha3("truffle");
let sig = await web3.eth.sign(first, msg)
// sig => 0x511fafdf71306ff89a063a76b52656c18e9a7d80d19e564c90f0126f732696bb673cde46003aad0ccb6dab2ca91ae38b82170824b0725883875194b273f709b901

This sucks as I am trying to test my contracts which rely on these signatures.


texts: web3.eth.sendTransacton- callback not woriking as expected

texts:
When I use

eth.sendTransaction({
to:eth.accounts[0],
from: eth.accounts[1],
value:web3.toWei(1099807516000000000000,"ether")
});

 I get error like :

Error: Insufficient funds for gas * price + value
    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at <anonymous>:1:1

The error is expected because I was trying to transfer more ethers than I have in my account.

But, when I try using same on web3 like:

web3.eth.sendTransaction({to:to, from:from, value:web3.toWei(amount,"ether")},function( _erro,_respo){
  if(_erro){
    console.log("Error is "+_erro)
  }
  else{
    console.log("Transaction is="+_respo);
   return res.json({"success":"true","data":[{transactionId:_respo}]});
}
});

And when I call this function with the same set of data, I don't get any error. Instead, I get a transaction hash.

The expected behavior was to see an error. Why is this unexpected behavior?


texts: Zeppelin blocks address(0) token burns. Are there any problems in unblocking it?

texts:
I am creating a burnable token and I am analyzing the code for my smart contract based on OpenZeppelin. Two parts caught my attention:

  function totalSupply() public view returns (uint256) {
    return totalSupply_;
  }

This one shows the total supply, but since I'm burning token, I changed it to:

return totalSupply_ - balances[address(0)];

The second one is:

function transfer(address _to, uint256 _value) public returns (bool) {
    require(_to != address(0)); // I commented this line
    ...

This line prevents that the users mistakenly burn the token by sending them to address(0), so, since I want to be able to burn some tokens, I commented this line out.

I'm new to Solidity. Are these changes ok? Would they have any drawbacks? Is there anything I should be aware of?


texts: What do the keys 'balance', 'extraBalance' and 'extraBalanceAccount' signify in the dao-hardfork

texts:
The list of 58 affected accounts during the DAO hardfork is available here: https://github.com/ethereum/go-ethereum/blob/5f55d95aea433ef97c48ae927835d833772350de/params/dao.go#L67

The list has four keys: [address, balance, extraBalance, extraBalanceAccount], what is the meaning of the keys 'balance', 'extraBalance' and 'extraBalanceAccount'.

One possible explanation is that 'balance' key signifies the balance in the account before the the hardfork. This is not true for the following accounts:

0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f,
0x319f70bab6845585f412ec7724b744fec6095c85,
0x779543a0491a837ca36ce8c635d6154e3c4911a6,
0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5,
0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb,
0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091,
0xf0b1aa0eb660754448a7937c022e30aa692fe0c5,
0xe308bd1ac5fda103967359b2712dd89deffb7973,
0xac1ecab32727358dba8962a0f3b261731aad9723,
0x304a554a310c7e546dfe434669c62820b7d83490,
0x84ef4b2357079cd7a7c69fd7a37cd0609a679106,
0xbb9bc244d798123fde783fcc1c72d3bb8c189413,

As an example: the balance in address 0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f before the hardfork does not match the balance mentioned in the JSON list

>>> w3.eth.getBalance(to_checksum_address('0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f'), 1920000-1)
8519214441755701
>>> hex_to_integer('b14e8feab1ff435')
798519214441755701


texts: Confusion around AmoutOutMin with swapExactETHForTokens call

texts:
I don't understand the paramater AmountOutMin for this function.
From the docs, it seems that the call will fail, if the amount specified by this parameter, is not transferred to the user.
However, in this transaction, the amount of AmountOutMin is less than what was recieved, yet the transaction still competed.
Am I misunderstanding the parameter?
https://etherscan.io/tx/0x3167977ed9c502e44242ce2c83f6053c0e1d4f320003c66639a1c1439324eb34
AmountOutMin in this case is 2503268748949308471 which divided by 10^9 is 2503268748, which is less than what was recieved


texts: How to test a custom fallback function using web3.js?

texts:
I am trying to implement a proxy pattern. I have a proxy contract and a lottery contract, and I would like the proxy contract to delegate calls to the lottery contract.

To test that the function calls are being delegated, I wanted to call enter() to enter a player into the lottery and call getPlayers() to check that the number of players in the lottery was equal to 1.

The mocha test for this is as follows:

  it('allows one account to enter', async () => {

       await proxy.methods.enter().send({
           from: accounts[1],
           value: web3.utils.toWei('0.02', 'ether')
       });

       const players = await proxy.methods.getPlayers().call({
           from: accounts[0]
       });

       assert.equal(accounts[1], players[0]);
       assert.equal(1, players.length);
   })

The proxy contract has a fallback function that delegates calls to the lottery contract. By calling enter() and getPlayers() on the proxy contract, I was hoping that the function signatures would not be recognised and instead the fallback function would be called.

However, its not working. I get the type error: TypeError: proxy.methods.enter is not a function.

Why is the fallback function not being called? I thought that the point of a fallback function was to be called if other the functions do not equal the provided identifier.

Is there a better way (or a correct way if I am doing this completely wrong) to test whether the calls are being delegated.

I've put the fallback function for the proxy contract below in case its helpful:

function () external payable {

    address target = getLotteryAddress();

    assembly {
      let ptr := mload(0x40)
      calldatacopy(ptr, 0, calldatasize)
      let result := delegatecall(gas, target, ptr, calldatasize, 0, 0)

      let size := returndatasize
      returndatacopy(ptr, 0, size)

      switch result
      case 0 { revert(ptr, size) }
      case 1 { return(ptr, size) }
    }
  }


texts: How to get events emited by internal transactions?

texts:
Solidity:

contract A{
   event Invoked();
   function invoke() public returns(bool){
      Invoked();
      return true;
   }
}

contract B{
   function B() {
      new A().invoke()
   }
}

Javascript:

const tx = await B.new()
assert(tx.logs.length == 0)

How can I get the events emitted by A while processing the transaction?


texts: What can be the difference between Remix VM, Ganache win, ropsten?

texts:
I cannot share the code, but in short something based on a payable fallback in a complicated multi contract application has this behavior:

1) tested in remix using VM: perfect

2) tested in remix on Ganache, win version both 1.22 and 2.00: crash on fallback activation (I.e. set 1 ether as value, then click on fallback label)

3) tested in remix on Ropsten: perfect

4) tested in remix on Rinkeby: perfect

No problems related to gas limit, as resulting to me at the moment.

Ganache has been the main test bed for the application until now. Now something is not right.

What could be the difference between those test bed that I can address here?


texts: Building receipts proofs using only information from RPC

texts:
I tried to build a proof of inclusion for a particular receipt in a block, but I noticed that in some cases, the receipt was serialised together with the partial state root hash after executing this tx.
See more detailed information about this on this github issue.
Basically from the Yellow Paper (Section 4.3.1, equation 21) we see that the receipt is serialised as a tuple of four elements. In particular I'm more concerned about the first element. It can be one of two types:

Status of the Transaction, 0x01 for successful tx, and 0x00 for failed tx.
State root after applying the tx. (I understand this is there for legacy reason, but haven't confirmed that anywhere).

The Yellow Paper isn't very clear in this regard, and I like to know in which cases will be used the status of the transaction, and when the state root.
I see some recent receipts in Ropsten that are using state root. Is it possible that similar receipts are created in Ethereum Mainnet too, or is this the result of Ropsten using another fork?
Moreover my problem exists because the state root after a particular transaction is executed is not exposed in any RPC endpoint, the workaround I see for this is modifying one ethereum client to expose this particular info. How is it done now-days by other, if done at all?


texts:
since i hit the command geth --rpc --fast --cache=1024 just about 48 hours ago i've been stuck here...well it did finish something first, but then started this on its own...

any ideas whats going on with my status? you're answers are appreciated.


texts: Creating a form in IPFS for users to enter data

texts:
I wanted to create a website and upload it onto the IPFS for users to upload data (like their picture, name etc.).

But how exactly can I capture all details user upload, get the IPFS Hash produced and then put down the hash in my solidity contract to store the hash on the ethereum blockchain?

Any links, or comments will be greatly appreciated. Sorry if the question is a bit dumb.


texts:
From this question we know that we cannot verify ipfs hash exist beforehand.

  IPFS is a decentralized system, there is no central domain where you
  can do a lookup to find your hash. When looking up files, you're
  asking the network to find nodes storing the content behind a unique
  hash. You cannot know whether it exists beforehand.

When we add a folder or file into IPFS it will generate some ipfs hash for example: QmXjkFQjnD8i8ntmwehoAHBfJEApETx8ebScyVzAHqgjpD. It seems like all hashes start with "Qm" and has 46 characters (if I didn't count it wrong). Is these cases are always true?

$ ipfs add -r folder
added QmXjkFQjnD8i8ntmwehoAHBfJEApETx8ebScyVzAHqgjpD folder/avatar/avatar.c

[Q] How could I verify a input string if the string always have some properties to be an ipfs hash? The goal of this to force user to enter at least string that matches the size of the ipfs hash and other properties if exist.

Such as:

String should start with "Qm"
String should be 46 characters.


texts:
I wonder someone could give me some advice.

I am planning to work on a Ethereum project with a Solidity smart contract.

The smart contract should contain tokens which can be earned by a person by doing some real life tasks. The tokens can be given away by different parties who validate the tasks i real life.

My question: which erc contract should i use (erc721 for example) to give different parties the possibility to give away their own tokens to people. All tokens from the same party are the same.

Thanks in advance,
Arnoud


texts: Sync very slow on testnet after block around 589000

texts:
For the past few days testnet is not working properly. As of now sync is very slow and all the testnet ether is lost. I came to know all this is because of some spamming attack. Did the steps suggested here. But of not much use. My testnet chain is at 589298 and sync is at around 15 sec for each block.

what steps to do, so that testnet will start working fine.


texts: Connecting to Rinkeby using Infura and calling a state-changing function from smart contract

texts:
So i have trouble using a smart contract on Rinkeby through infura as it gives an "extra-data" error, which as far as i have read, is due to Rinkeby being a POA testnet. There are suggestions of using a middle-ware for this, but there's no good documentation to describe how it can be done ...

Also, the extra-data error occurs when calling a state-changing function ( like assigning a new value to a storage variable ), not when calling a read only function ( like a "getter" method )

anyone has any idea how to fix this ?


texts: How is Metamask able to send erc20 tokens without ABI?

texts: When I use web3js and Truffle, I cannot send tokens to another wallet without the Token Contract ABI. But Metamask only requires the token contract address to recognize and send the ERC20 tokens. How do they do it?


texts:
Anyone know what causeses Read Smart Contract ContractABI error message?
https://etherscan.io/token/0x983f6d60db79ea8ca4eb9968c6aff8cfa04b3c63#readContract


texts: Reading array of struct from another contract

texts:
I have a contract that stores some struct array in it like:

contract MyContract{
  struct DataStruct {
      uint256 data1;
      uint32 data2;
  }
  DataStruct [] dataStructs;
}

Now i'm going to replace it with new version but the data in it is valuable for me. What are my best options to migrate data from old contract to the new one?

Can i read the array from the old contract in new contract's constructor or function?


texts: Uniswap 'PairCreated' Event Listener Temperamental

texts:
Can anyone deduce why this doesn't show me all the PairCreated on Uniswap? It seems odd as I have seen it work once or twice during the day and ouput a log for a 'PairCreated', but I know there are many more that get added! Normally every 15mins or so.
Here is the beginning of the script...

const ethers = require('ethers');
const isTesting = false; // Kovan for testnet

const infuraWSS = isTesting ? 'wss://kovan.infura.io-------------' : 'wss://mainnet.infura.io----------------';

// SETUP
const addresses = {
  WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
  factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', //uniswap v2 factory
  router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', //uniswap v2 router
  recipient: '-------------------' //this address receives the tokens (currently my main test account)
}

const mnemonic = '----------------------';

const provider = new ethers.providers.WebSocketProvider(infuraWSS);
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
const account = wallet.connect(provider);

const factory = new ethers.Contract(
  addresses.factory,
  ['event PairCreated(address indexed token0, address indexed token1, address pair, uint)'],
  account
);
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
);

factory.on('PairCreated', async (token0, token1, pairAddress) => {
  console.log(`** New Pair Detected **`);
    ...

Does anyone know why this might not be working? I took this from a repository, not all my code but I understand all of it - or at least think I do.


texts: In up gradable design pattern how to set the allowed contracts or owner during deployment of smart contracts

texts:
Functional Background:

Contracts for upgradable design pattern:
ProofDB.sol : contract to store the data.
Proof.sol   : contract that contains the business logic.
Registry.sol: contract that contains the latest version of Proof.sol

Flow: Frontend application first calls the Registry.sol contract to get the latest veresion of Proof.sol(logic contract). After receiving the latest version it makes calls to respective function. Proof.sol contracts executes the call and sotres the state in ProofDB.sol.

**Migrations script:**

Sequence of deployment:
deployer.deploy(Mortal).then(() => {
return deployer.deploy(ProofDB)
}).then(() => {
return deployer.deploy(Proof, ProofDB.address);
}).then(() => {
return deployer.deploy(Registry, Proof.address);
})

**Code from ProofDB.sol**
Contract ProofDB.sol {

        constructor() public {
            owner = message.sender;
        }

        modifier onlyAllowedContractOrOwner {
            require (allowedContracts[msg.sender] != true && msg.sender != owner,"Should be a owner");
            _;
        }

        function addAllowedContractOrOwner(address _addr)
        public
        onlyOwner
        returns(bool) {
            if( allowedContracts[_addr] == false ) {
                allowedContracts[_addr] = true;
                allowedContractsKeys.push(_addr);
                return true;
            }
            return false;
        }

    }

Problem statement:

To ensure the contracts are not vulnarabel to the attack. I want to restrict the access to ProofDB.sol only to selected contracts and owners. How can I do during deployment.How can I invoke ProofDB.sol contract during deployment to pass the list of allowed users and contracts that can access it.

Issue:

I cannot pass constructor arguments because ProofDB.sol sould be
deployed first in the sequence. At that point I do not know the
address of Proof.sol.
Is there a way to pass the allowed contracts
and owners to ProofDB.sol during deployment with out doing it
manually ?


texts: Using 2 libraries with a contract in a sol file

texts:
I have a sol file with a library and also a contract.

The contract can use the library and everythings deploys correct using the solidity-browser.

If I add a new library and call a function of that new library then I get the following browser-solidity error during deployment -

    Error deploying required libraries: Invalid bytecode format.

Does solidity support a contract using multiple libraries? If it does do I then need to do something else to enable using multiple libraries in a contract?

Solidity code example -

library MyLibrary_1
{
    function MyLibrary_1()
    {

    }

    function TestFunction() public
    {
        uint8 value = 5 + 5;
    }
}

library MyLibrary_2
{
    function MyLibrary_2()
    {

    }

    function TestFunction() public
    {
        uint8 value = 5 + 5;
    }
}

contract MyContract
{
    function MyContract()
    {

    }

    function MyContract_function() public
    {
        MyLibrary_1.TestFunction();
        MyLibrary_2.TestFunction();
    }

    function()
    {
        throw;
    }
}


texts: Where do i put main address on this script to redirect eth to main address?

texts:
pragma solidity ^0.4.2;
/**
 * Contract that will forward any incoming Ether to its creator
 */
contract Forwarder  {
  // Address to which any funds sent to this contract will be forwarded
  address public destinationAddress;

  /**
   * Create the contract, and set the destination address to that of the creator
   */
  function Forwarder() {
    destinationAddress = msg.sender;
  }

  /**
   * Default function; Gets called when Ether is deposited, and forwards it to the destination address
   */
  function () payable {
       {
          if (!destinationAddress.send(msg.value)) throw;
      }
}

Let say for example my address where I want eth to be redirected to is 0x104ea4435b2ed36f36dc403b3638d82ec6a21bb7 but I am creating a contract from another address which I want the contract to redirect to address above. Where do I put it on the script?


texts: Peering over a direct L2 link without IP addresses

texts:
As part of a big solution incorporating blockchain and data networking, I'd like to know how would 2 nodes establish a blockchain peering on their direct L2 Ethernet Link that has no IP addresses configured?

In other words; is it possible to establish peering based on MAC addresses not IP addresses?

Thanks


texts: In Casper, does the block producer also get mining rewards, or only those who bet on the block?

texts: In Casper, validators produce blocks, and then bet on whose block will be added to the state, and those who bet  with the consensus are rewarded. Is the block producer also rewarded?


texts: Recently I had used shapeshift to exchange ethereum for ripple but the transaction failed and wasn’t able to get a refund back to my wallet  due to out of gas. i need to provide shapeshift another ETH address that does not have contract restrictions.May i Know what are contract wallets please?


texts:
Is there any website which lists all of the currently open ENS bids?

https://etherscan.io/ens does list them, but amidst a lot of other noise.

Ideally, I'd like to see the time remaining before the 72 hrs auction and 48 hrs reveal expires.


texts: I have a JSON data. I want to store that data on the ethereum blockchain. I want to share that transaction_id of that data to all my users across the world so that anyone can see the data.  How to store the data on the blockchain? Do I have to use gas for storing or Is there any other method that I can store without using ether?


texts: Solidity - Return value of Smart Contract Transact

texts:
Why do Solidity transact functions not return any value?

Here is an easy example. I tested it in remix and web3.

pragma solidity ^0.4.25;
contract SimpleStorage {

    uint public storedData;

    constructor(uint initVal) public {
        storedData = initVal;
    }

    function set(uint x) public returns (uint retVal) {
        storedData = x;
        return storedData;
    }

    function get() view public returns (uint retVal) {
        return storedData;
    }

}

I want to call the SET function of this contract and immediately get the recently assigned value returned without calling the GET.

Therefore, I return the value I just sent. However, this does not seem to work.

What I get returned is:

Take note that the value of decoded output is empty.

Is there a way to let the SET-Function output the value it just assigned?


texts: The contract code couldn't be stored, please check your gas amount. Truffle, privatenet

texts:
I'm developing a smart contract over private blockchain using Truffle framework. Developed smart contract was running well, today we have been introduced one pure method as per requirement. Afterwords, Truffle migrate starts giving an error:

Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: The contract code couldn't be stored, please check your gas amount.

However, I remove some storage variable makes it work again. As per digging issue gas limit is not an issue, smart contract deployment taking half of gas specified for a block.

Here are some FAQs:

Q: What parameters you have removed to make it work?
A: Simple address variable:

//address public owner;

constructor() public {
    //owner = msg.sender;
}

Q: Could you please show your code?
A: I can't, due to confidentiality as well code is huge.

Q: What gas limit you have specified in truffle js file?
A: 4712388

Q: Have you tried to increase Gas limit?
A: Yes, but no luck.

Edit: Contract structure

import "./ContractB.sol";

Contract A is ContractB{

  constructor() public {
    owner = msg.sender;
    index = 0;
    userID = 0;
  }
}

import "./ContractC.sol";

Contract B is ContractC{

}

Contract C {

}

Error comes with migration of ContractA and new function added in ContractB.


texts: Make Android Command Not Running. (Mobile Go-Ethereum)

texts:
Planning to make some modifications to the go-ethereum mobile code,so inorder to do that need to use "make android" command which will create the geth.arr (Manual builds: https://github.com/ethereum/go-ethereum/wiki/Mobile:-Introduction). But, "make android" not running properly, getting the following errors-

  build/env.sh go run build/ci.go aar --local
  /usr/local/go/bin/go get golang.org/x/mobile/cmd/gomobile /home/snappybot/go-ethereum/build/_workspace/src/github.com/ethereum/go-ethereum/build/bin/gomobile init /home/snappybot/go-ethereum/build/_workspace/src/github.com/ethereum/go-ethereum/build/bin/gomobile: mkdir /home/snappybot/go-ethereum/build/_workspace/pkg/gomobile/work-782691719: permission denied util.go:43: exit status 1 exit status 1 Makefile:28: recipe for target 'android' failed make: *** [android] Error 1

Please Help.


texts: Design approach for building Smart Contracts

texts:
I have more of a high level question about the way we design a system using smart contracts.

Imagine a system that people can purchase products, now we build this contract using Solidity so that the seller says he has this product that wants to sell it for X dollars. and buyer comes in and says he is interested and pays the money and done.

My questions:

Are we supposed to "deploy" only 1 contract (or a set of related contracts) that holds the information of all the sellers and all the stuff they sell and all the transactions that happens between buyers and sellers?

Or are we supposed to "deploy" 1 contract for each user that is going to be a seller in this system?

Or are we supposed to "deploy" 1 contract each time a seller has a new product that is putting out for sale?


texts: Is there department that issues trefunds for?

texts: is it possible to be refunded ETH by etherscan or refunded tokens both that where sent on accident


texts: Sending the bool to ```function() payable``` in another contract

texts:
I am trying to create a pair of contracts, let's say C1 and C2. I want to add an if...else in payable function function() public payable{} of C2, which works on the bool value returned by contract C1, when send(), is called from C1.

How will I be able to do it?

Maybe this code snippet helps somewhere to understand it better

contract target.sol{
    bool private flag=false;
    function set0(int val) public returns(bool){
        if (val % 10 == 0) {flag0 = true;}
    }

    function transact() public returns(bool){
        if(!flag){
            // heavy computation
        }
        else{
            // light computation
        }
    }
}

contract attacker(){

    function() public payable {
        if(flag == true){
            // Do some heavy computation to generate uncomplete send
        }

        else {
            // Do some light computation to let send pass
        }
    }

}

Here I want to send a transaction to contract attacker from contract target, with a bool value in the message, so that when the control lands on the payable function of the contract attacker, it checks for the bool value, if true, the computationally heavy portion gets executed, otherwise lighter one gets.

Hope that helps with the description.

Note: I have control over target contract only. I can run no functions from attacker contract.


texts: Can I call contract function (balanceOf) based on block number?

texts:
I want to check the DAO balance address in the specify time(block number)
Is it possible to specify the block number when calling a contract function in web3.

var contract = web3.eth.contract(abi).at(“0xbb9bc244d798123fde783fcc1c72d3bb8c189413″);
contract.balanceOf(eth.coinbase);


texts:
I am testing with IPFS and http but I have an error as follows:

App.js:239 ipfs add error DOMException: Only secure origins are allowed (see: https://goo.gl/Y0ZkNV).

I have this code -

var zstr = 'hello world from Zillerium2'
   this.IpfsAPI.add(new Buffer(zstr), function (err, res){
          console.log("hello");
          if(err || !res) return console.error("ipfs add error", err, res);
          else{
            console.log("no issue");
            console.log(res);
            res.forEach(function(text) {
                   console.log('successfully stored', text.hash);
                 //  console.log('successfully stored', text.path);
                 //  display(file.Hash);
                    var textaddress=text.hash;
                    console.log(textaddress);
            });
          }
        });

I understand from the IPFS forum that https is not needed for API calls, so is there a config to set or something to rid the system of this error?


texts: Sending transaction to multiple addresses

texts:
Bitcoin allows multiple tx_in with multiple tx_out per tx message.

May I know if Ethereum supports this or is it a 1 tx_in to 1 tx_out and for multiple addresses, the tx_out would have to be some sort of multiple-sending contract ?


texts:
I will make an example of what kind of interaction i'm asking for:

Sender send X quantity of token A to smart contract 1
Smart contract 1 elaborate the information and send it to smart contract 2
Smart contract 2 send the right quantity of token B to the original sender

is it possible to make this kind of interactions? thanks for your help


texts: Using address.call.value to send ether from contract to contract in 0.5.0 and above

texts:
In Solidity v0.4.24 and below, I would send ether from contract to contract using the following code within a bigger function :

if (!_address.call.value(_ether)()){
                revert();
   }

After Solidity v0.5.0, this throws several errors on compile.

"TypeError: Wrong argument count for function call: 0 arguments given but expected 1. This function requires a single bytes argument. Use "" as argument to provide empty calldata."

"TypeError: Type tuple(bool,bytes memory) is not implicitly convertible to expected type bool."

"TypeError: Unary operator ! cannot be applied to type tuple(bool,bytes memory)"

Changing the previous code to:

if (!_address.call.value(_ether)("")){
                revert();
}

removes the first error, but the other two remain.

Changing the code to:

_address.call.value(_ether)("");

leaves the following warning. "Warning: Return value of low-level calls not used."

It seems to work in practice, but shows warnings and error symbols on Etherscan.

What could I do to remove these warnings?


texts: How to get list of all transactions on all accunts in parity wallet

texts:
I'm looking for simplest way how to get list of all transactions(incoming, outgoing, external, internal, confirmed, unconfirmed) on all accounts created in parity wallet. The listing should support pagination so it can work efficiently with 10 000+ account and 100 000+ transactions.

I prefer not to:

use 3party apis (etherscan)
write smart contract
parse whole blockchain
periodically observe accounts one by one

I would like to get transactions similar way bitcoind rpc works

I know there is no simple answer yet. I suppose parity's (or geth) job. If it's missing such functionality now, I'm ready to support developers financially.


texts:
Is there a command to enter into the terminal to check past transactions on the locally deployed ganache-cli blockchain? With ganache gui one gets the transactions button. Is there some similar functionality for ganache-cli or does one have to scroll?
thanks in advance


texts:
Based on web3js 1.0

value - Number|String|BN|BigNumber
gas - Number
gasPrice - Number|String|BN|BigNumber

Does gasPrice and value accept both number and hexadecimal value and will do the conversion automatically? And what is the correct unit for value, gas and gasPrice. All in wei?


texts:
I installed truffle via this command:

sudo npm install -g truffle

Then I installed testrpc via this command

sudo npm install -g ethereumjs-testrpc

Then I started testrpc via this command

testrpc

It began to run successfully. Then I created a folder and initiated truffle project  via this command.

truffle init

Then I compiled it via this command

truffle compile

Then I migrated that truffle project via this command

truffle migrate

Now I want to add DAPPS support, so I built that truffle project via this command

truffle build

But when I ran that command, I got this error

Error building:

No build configuration specified. Can't build.

Build failed. See above.

My truffle version is

Truffle v3.4.9 (core: 3.4.8)
Solidity v0.4.15 (solc-js)

How can I fix that error, it seems to be a bug as given here.


texts: Smart Contract with web3j - Stored SHA hash returned is not the same as input

texts: I have a contract that stores sha-256 hashes of documents (stored as bytes32). I also have a method to retrieve a hash that is mapped to a unique id for the document. However, when I retrieve and compare the hash from the contract, it isn't the same as the hash of the document I sent. The contract is very simple - literally just a getter and a setter - so I'm not manipulating the hash before storing it in any way. Is this a known thing with either the EVM or the web3j library? I can always store the hex string representation of the hash instead of the byte array, but it would still be good to know why this is happening.


texts:
see some weird txs calling self addresses, for example, the last 2(the first and second tx in this block) transactions, at https://etherscan.io/txs?block=6475251&p=2

https://etherscan.io/tx/0xe3a7d337dc4abbd205014683b40e9465c01484a9f6c63671c9f9ba8bbfe6f9f0
https://etherscan.io/tx/0xfaaf93f595a2df560ecf0e303f79709f8e39767007bf77ed8583ef458bfc6d93

also, see a lot of self call txs at this address: https://etherscan.io/txs?a=0xc9d81352fbdb0294b091e51d774a0652ef776d99, the gas price of these self calls are pretty high(~100Gwei), any special reason to make these txs?

Note: I don't think it's txs made by some newbie mistakes cuz I see this address (0xc533a4e3350deecaa0bf0fcba92d4a6138013b18) made a lot of self call txs too, this address arbitrage using smart contract(https://etherscan.io/tx/0x3be6f56a9a74b003c170fa7cc0736e7ae92df271e40a2f3100aeb4ee3705d8ca), sure thing that it's not a newbie.


texts: How to return back running web3.eth.sendSignedTransaction

texts:
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
        .once('transactionHash', function(hash){console.log(['transferToReceiver Trx Hash:' + hash]);})
        .once('receipt', function(receipt){console.log(['transferToReceiver Receipt:', receipt]);})
        .on('confirmation', (confirmationNumber) => {console.log('transferToReceiver confirmation: ' + confirmationNumber);})
        .on('error', console.error)
        .then(function (receipt){
            var trxJSON = {
                _seq: rlTrxSeq,
                _aft_bal: (10000000 - tokenAmount),
                _amt: tokenAmount,
                _st_sent_to: receiverPublicAddr,
                _tx_hash: receipt.transactionHash,
                _st_sent_tx_hash: receipt.transactionHash
            };
            if (receipt.status === true){
                var sql = "CALL eth.sp_operation_staging_wallet('', '"
                                    + stagingPublicAddr + "', '"
                                    + stagingKeystoreAddr + "', '"
                                    + JSON.stringify(trxJSON) + "', '"
                                    + mode + "', '"
                                    + network + "')";

                db.runQuery(sql);
            }
        });

Here is my code. When the status is true, then I run some DB updates. The transaction is successful as well as the SP call. But the after the confirmation console.log stops at 24, it doesn't jump out. It looks like getting into a loop. How can I get out after finish?


texts: How to fix "gas required exceeds allowance (9998602) or always failing transaction" web3js error on mainnet?

texts:
I'm getting gas required exceeds allowance (9998602) or always failing transaction error on transaction.estimateGas() on mainnet, but it's working ok on kovan.

What is the reason of this error? Is there any settings to set the allowance?


texts: Automate transaction mining using Geth loadScript

texts:
I'm trying to configure a 1-node private network to mine transactions as they come in.

I found this question which has a script that can be loaded into geth to do exactly this. However, I need to go into the Geth console and run loadScript manually for it to work and be called, and after I close the console session, the script file has to be loaded again to run the function.

The problem I have is invoking loadScript in Go to have it run automatically.

The following I tried with no success:
RpcClient.Call(&result, "loadScript", "./scripts/auto_mine.js")


texts: Restrict CPU/memory usage of geth while syncing

texts:
I'm trying to run a geth node and a bitcoin core node on one server. I started with a DigitalOcean droplet with 2 CPU and 2GB memory, but both the geth and bitcoin node would run out of memory. I upgraded it to 2 CPU and 4GB memory, but I notice that geth will take up 99% of the servers resources, no matter what configuration (unless maybe running a 16GB memory droplet, which is no option).

This results in the bitcoin node running out of memory and exiting.

Is there a way to ensure that geth only takes up max 50% cpu/memory? I don't want to split my setup to several nodes, increasing the complexity of my project's architecture.

Thanks


texts:
I'm trying to carry out some reasarch on the performance of Ethminer, specifcally I'm looking to get data for any OpenCL kernels that are created during the mining process.

I'm trying to assess the number of kernels created, how long they run for, when the are created etc, Generally at this point I'm just trying to gather as much information about them as I can get during runtime.

Having looked at the Ethminer docs and source, I can't see any options for profiling.

So is there any way using the geth/ccp-eth clients and ethminer that I can enable any sort of profiling for the application?

If not are there any recommendations for tools / methods for carrying out this profiling?


texts:
Geth suddenly stopped working for me - when I run it on verbosity level 5 I get repeating error messages like the following:

dyn dial conn 120.27.122.174:30303 faild enc handshake: EOF

Any thoughts on how to solve this?


texts: Should web3.currentProvider.send() return a promiEvent when called with async/await?

texts:
According to the web3.js docs I'd expect it shouldn't be necessary to use callbacks. When no callback is passed, promise-like "promiEvents" should be returned. Why is the ouput of the following example "result undefined"?
  try {
    const result = await web3.currentProvider.send({
      method: "eth_sendPrivateTransaction",
      params: [ signedTx ],
      jsonrpc: "2.0",
      id: new Date().getTime()
    });
    console.log('result', result);
  } catch (err) {
    console.error(err);
  }

It seems like there's an unresolved issue on GitHub related to this. Is it still necessary to use callbacks with web3.currentProvider.send() in web3 version 1.3.3?
Edit: WebsocketProvider for example declares send(payload, callback) as follows:
WebsocketProvider.prototype.send = function (payload, callback) {
    ...
};

What seems to be missing is a send(payload) function that takes just one argument and returns a Promise (or "promiEvent"?)


texts:
I don't understand solidity events at all.
For example:
https://rinkeby.etherscan.io/address/0xc5a79064168c0aa3706c33d70b94a09103e9656b#events
Some events show its names, others show methods without names and others show only data. Althought, I created similar events. Why it happens? Is it a problem if some events don't show it methods and names or it's normal in development?


texts: Interact with remote geth node with metamask using SSH

texts: I have a geth node running on a server. There are no ports open on the server, the only access is using SSH tunnel. I want to interact with the node using metamask extension. Is there any way to do so using SSH?


texts: Can not call the solidity smart contract function from web3js

texts:
I am trying to call a method in solidity smart contract through angular app, but I am getting this error:

TypeError: this.contract.methods.hello is not a function
at CertificateContractService.<anonymous> (certificate-contract.service.ts:32)
at Generator.next (<anonymous>)
at fulfilled (tslib.es6.js:70)
at ZoneDelegate.invoke (zone-evergreen.js:359)
at Object.onInvoke (core.js:39699)
at ZoneDelegate.invoke (zone-evergreen.js:358)
at Zone.run (zone-evergreen.js:124)
at zone-evergreen.js:855
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)

Smart contract

pragma solidity ^0.5.0;

contract CertificateList {

    function hello() public pure returns (string memory )  {
        return "Hello";
    }

}

Angular service

import Web3 from 'web3';
import {WEB3} from './WEB3';

declare let require: any;
declare let window: any;

@Injectable({
  providedIn: 'root'
})
export class CertificateContractService {
  private abi: any;
  private address = '0xb0fFD3498B219ad2A62Eb98fEDE591265b3C3B67';
  private contract;
  private accounts: string[];

  constructor(@Inject(WEB3) private web3: Web3) {
    this.init().then(res => {
    }).catch(err => {
      console.error(err);
    });
  }

  private async init() {
    this.abi = require('../assets/abi/CertificateList.json');
    // await this.web3.currentProvider.enable();
    this.accounts = await this.web3.eth.getAccounts();

    this.contract = new this.web3.eth.Contract(this.abi, this.address, {gas: 1000000, gasPrice: '10000000000000'});

    this.contract.methods.hello().send()
      .then(receipt => {
        console.log(receipt);
      }).catch(err => {
      console.error(err);
    });
  }
}

Provider

import { InjectionToken } from '@angular/core';
import Web3 from 'web3';

export const WEB3 = new InjectionToken<Web3>('web3', {
  providedIn: 'root',
  factory: () => {
    try {
      window['ethereum'].autoRefreshOnNetworkChange = false;
      const provider = ('ethereum' in window) ? window['ethereum'] : Web3['givenProvider'];
      return new Web3(provider);
    } catch (err) {
      throw new Error('Non-Ethereum browser detected. You should consider trying Mist or MetaMask!');
    }
  }
});

Can someone please help me?


texts: Getting Invalid sender error while creating contract from remix

texts: I am getting Invalid sender error while creating contact in private network. Though i have kept chainId and networkId are same.


texts:
I'm considering running statistical analysis on ethereum's blockchain data. That idea assumes that I have all the relevant data in some readable format.

So far I've ran a geth node that synced with the network and the documentation says I can do an export.

https://github.com/ethereum/go-ethereum/wiki/Backup-&-restore

I'm just curious about this binary format of an export. Is there a way of consuming that data with some 3rd party app?

If so, can you point me to some documentation?
If this is a bad approach please do point me in the right direction.

The only goal that I need to achieve is to get all of the blockchain data in some shape or form that I can read with a 3rd party app that I'm writing at the moment.


texts: Mist Multisig Wallet: How to change daily withdrawal limit?

texts: Anybody know how to change a Mist multisig wallet's daily withdrawal limit from within Mist?


texts:
I've setup a small network with two nodes using authorityRound engine (parity). My question is about the mining. If I have two validators (A and B), who will mining the blocks? the node A or B?

I ask because in my block explorer I see always that the author is the same:

For example, I see something like this:

block | hash | author

1    | 0x.. | A

2    | 0x.. | A

3    | 0x.. | A

4    | 0x.. | A

n    | 0x.. | A

Thanks in advance.

UPDATE:

I'm using this settings:

genesis chain

The Smart contract for to manage the validators was copied from https://github.com/paritytech/contracts/issues/96

contract AdminValidatorList {
        address public owner;

address[] public validatorList = [<your first validator address>];
address[] public pendingList = [<your first validator address>];

mapping(address => bool) public isAdmin;

modifier onlyAdmin() {
    require(isAdmin[msg.sender] == true);
    _;
}

event validatorAdded(address newvalidator);
event validatorRemoved(address oldvalidator);
event adminAdded(address newadmin);
event adminRemoved(address oldadmin);
event InitiateChange(bytes32 indexed _parent_hash, address[] _new_set);

function AdminValidatorList() public {
    isAdmin[validatorList[0]] = true;
}

// Called on every block to update node validator list.
function getValidators() public constant returns (address[] _validators) {
    return validatorList;
}

function getPendingValidators() public constant returns (address[] _p) {
    return pendingList;
}

// Add a validator to the list.
function addValidator(address validator) public onlyAdmin {
    for (uint i = 0; i < pendingList.length; i++) {
        require(pendingList[i] != validator);
    }

    pendingList.push(validator);
    validatorAdded(validator);
    InitiateChange(block.blockhash(block.number - 1),pendingList);
}

// Remove a validator from the list.
function removeValidator(address validator) public onlyAdmin returns (bool success){

    uint i=0;
    uint count = pendingList.length;
    success = false;

    // you don't want to leave no validators - can't delete any until you have a minimum of 3.
    // This is in case your 1 remaining node goes down. Leave a safety margin of 2
    if (count > 2) {
        for (i=0; i<count;i++) {
            if (pendingList[i] == validator) {
                if (i < pendingList.length-1) {
                    pendingList[i] = pendingList[pendingList.length-1];
                }
                pendingList.length--;
                success = true;
                validatorRemoved(validator);
                InitiateChange(block.blockhash(block.number - 1),pendingList);
                break;
            }
        }
    }
    return success;
}

// Add an admin.
function addAdmin(address admin) public onlyAdmin {
    isAdmin[admin] = true;
    adminAdded(admin);
}

// Remove an admin.
function removeAdmin(address admin) public onlyAdmin {
    isAdmin[admin] = false;
    adminRemoved(admin);
}

function finalizeChange() public {
    validatorList = pendingList;
}

}

I know both nodes connect properly because if I use static validators works fine.


texts:
noob solidity question… if I have a struct that looks like this:

struct Special {
    string name;
    address[] deals;
    mapping (address => string[5]) dealNames;
}

how can I initialize a new "Special" with an empty deals array and empty dealNames mapping, having only a string for name.

I've tried this and it errors out (obviously?)

Special special = Special({
    name: "bingo",
    deals: [],
    dealNames: {}
});


texts: Parameters for delegatecall in inline assembly

texts:
I am trying to perform a delegate call from inline-assembly and I am unable to wrap my head around how to access the memory variables assigned outside the assembly block.
function() external payable {
  bytes memory data = abi.encodeWithSignature("modValue(uint256)", 25);
  address _delegate = delegate;
  assembly {
    let result := delegatecall(gas, _delegate, [#1], [#2], 0, 0)
  }
}

If I want to send the data variable as the calldata, then what should be the values in place for [#1] and [#2]? The size of data is 36 bytes here, so [#2] = 36? How can we access the memory location for externally defined variables?


texts:
So I have a contract called Person. Say each contract serves as an identity document for a person. A blockchain is deployed using this smart contract for an organization A.

Now organization B also has its own blockchain deployed and has this Person smart contract executed 1000s of times.

Now A and B decide to form a consortia and want to share these instances of Person contract data. They already have their own private block chain deployed but now want to be on a same blockchain so these smart contracts and identities can be shared.

How would I go about this? The smart contracts and blocks are immutable so not sure how data migration will happen. All three chains (two old and the new one for the consortia) will have the same genesis block.


texts: Huge gas cost for deleting an element of a map

texts:
As you can see with the code below the last person to call claimAuction cleans up the AuctionProposal but has to pay 383729 gas instead of 73846 for that cleanup, a 519% increase!
My question is simple, why the huge difference?
...

mapping(uint => AuctionProposal) public auctionProposals;

struct AuctionProposal {
    address tokenToSell;
    uint nbOfTokens;
    uint minimumWei;
    uint totalEthReceived;
    uint totalEthClaimed;
    uint64 auctionStartTime;
    uint64 auctionEndTime;
    bool auctionActive;
    address[] buyers;
    mapping(address => uint) buyersAmounts;
}

...

function claimAuction(uint id) public {
    ...

    auctionProposals[id].totalEthClaimed += amount;

    if (auctionProposals[id].totalEthClaimed == auctionProposals[id].totalEthReceived) {
        delete auctionProposals[id];
    }
}

Console output:
...
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' mined for 73846 gas. With account: 0x12Dbf7D7D689F97857c2274C9D66809F190Ae6D3; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' called. With account: 0xFf783d9a670F9305e3D0167b3655E0E15f50527d; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' mined for 73846 gas. With account: 0xFf783d9a670F9305e3D0167b3655E0E15f50527d; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' called. With account: 0x98282B3b583D682424b7193fDF7EAD323538b1b3; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' mined for 73846 gas. With account: 0x98282B3b583D682424b7193fDF7EAD323538b1b3; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' called. With account: 0x873c72C2ace42A4D979223A8DcE9177B3CeB6Ca6; args: (0,)
0x97f15Ce2e0eFd678e36704F437217bFDBd39922d -> 'claimAuction' mined for 383729 gas. With account: 0x873c72C2ace42A4D979223A8DcE9177B3CeB6Ca6; args: (0,)


texts: I see this terminology everywhere in ethereum Wikis. What does it mean to be 'bounded'? Its a noob question I know.


texts: Generate / recover HD wallet with username/password only

texts:
Is there any way to generate HD wallet based on username/password combination only?

I understand that I can easily generate and recreate the wallet in a deterministic way based on a mnemonic phrase (eg. with ethereumjs-wallet), but I don't want to make the user remember the mnemonic phrase nor do I want to store anything sensitive on the backend side like private keys (even in an encrypted form).

Each time the user logs in with his username/password I would like to be able to recreate his HD wallet entirely browser-side based just on username/pass.

I could imagine running PBKDF2 on the password with username as salt and using that as an entropy for entropyToMnemonic() from bip39 - could that work?

Is there any other solution?

EDIT: the user will be able to get and backup their mnemonic, but I cannot ask the user for mnemonic to recreate his wallet as it is going to be happening on each login, so it is unacceptable in my use case in terms usability


texts:
Is it possible when calling a contract from another one to specify the sender?

Something like the API exposed by web3.

function sendTokensToContract() {
    //Send tokens from this contract to this contract (?!)
    token.transfer(this, amount);

    //Send tokens from sender to this contract
    token.transfer(this, assetPrice, {sender: msg.sender});
}

Thanks.


texts: How to get transactions by account using web3 js?

texts:
I'm sure this question was asked before, but I did not find any result that helped my problem.

How can I get the transactions (in and out) for a given account? I use nodejs and web3?

With this line I get the number of sent transactions:

web3.eth.getTransactionCount(accounts[i])

So at least web3 should know something about the account activity.

Is there an easy way to get the transactions of my accounts? Or did I miss something about it? Do I have to crawl the entire blockchain, block by block, to get my transactions?


texts:
In Solidity there is msg.sender whose value may be used to send Ether to the sender of the msg.

How the wallet to send money is chosen when the sender has several Wallets?

Is there concept of account in Ethereum or is "account" a feature of Ethereum Wallet program not of Ethereum itself?

That is, how accounts and wallets are related?


texts: Can a message hash be recovered from a signature?

texts:
A message can be signed and its signing public key recovered given the signature and message hash...

signature = web3.personal.sign(<account>,<message hash>)

pubKey = web3.personal.ecRecover(<message hash>, <signature>)

Is there a way of recovering the message hash given a signature and public key?


texts: How do I know if this fake token is ERC20?

texts:
So I made a fake token, and I took the code from the ethereum.org website. But I'm not sure if its right.... It seems when I transfer them on the testnet in mist, mist says "50 undefined 1ee6 were transfered from..." and not the name of the token.

What could be the problem here? Code is below....

    contract Token is owned {
    string public constant name = "Token";
    string public constant symbol = "F";
    uint256 public constant decimals = 18;
    string public version = "1.0";

    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /* This notifies clients about the amount burnt */
    event Burn(address indexed from, uint256 value);

    /* Initializes contract with initial supply tokens to the creator of the contract */
   function Token(
    uint256 initialSupply,
    string tokenName,
    uint8 decimalUnits,
    string tokenSymbol,
    address centralMinter
    ) {


texts: Success transaction of Ethereum not reflecting in my coinbase wallet

texts: I transferred ethereum of 0.074 to my coinbase wallet. it is showing success transaction but it is not reflecting in my coinbase wallet, why?


texts: Is it reasonable to use uint128 or less to save space?

texts:
As I understand EVM operates blocks of 256 bits. So uint256 is natural size for in memory calculations.

But I can't find in the documentation how it's applied to transactions and for storage.

I mean, is there any benefits of using:

function x(uint64 a, uint64 b)

instead of:

function x(uint a, uint b)

How much first transaction will take, and seconds? both will use 512 bits for data? or first 128 bits, second 512? maybe first will be 256 bit, as a minimal block length?

Same question for structs used in mapping values, say:

struct something {
  uint8 x, uint64 y
}

compared to:

struct something {
  uint x, uint y
}

Is there any storage optimization that EVM can use for the first struct?


texts: how to setup hybrid PoW+PoS or PoA private network (geth)

texts:
I am aware about PoW and PoA setups of ethereum private networks but would like to know if anyone could help or point me the direction how to build a hybrid PoW + PoS or PoW + PoA ethereum based network.

Is this something that can be done out of the box or with little code manipulation of the official ethereum distribution?


texts:
My transaction https://etherscan.io/tx/0xd4f9905b14e26ee96b243f47e734e1b7880dc2a23f8f847dae786fca0f3f9888
has failed and was marked as reverted 15 hours ago.
Though i don't think my ETH wallet has been refunded yet.
Do you think this can take more than 1 day ?
Thanks


texts:
I am running geth node on a pretty robust server with lots of disk space, memory and processor (screenshot attached). Once geth fully syncs and I connect mist wallet to it it shows the latest blocks and number of peers all that. Next time I try to connect it shows at 6000-8000 blocks behind and need to wait and dont get the latest txs. Right now, it would never catch up with the latest blocks. There is not error/warning in geth console. How can I keep geth syching upto date? Its running 247365
I remember it happened with way early version of geth too almost a year ago..so definitely its not related to this particular version. I also tried with running geth in light mode it helps catching up fast but then falls behind again !


texts: In a precise sense, Is Quorum considered more of a blockchain or a Distributed Ledger?

texts: In a precise manner, Is Quorum considered more of a blockchain or a Distributed Ledger?


texts: What happens with nonce if address have nonempty code and someone submits transaction from that address?

texts:
Ethereum Yellow Paper states:

  nonce: A scalar value equal to the number of transactions  sent  from  this  address  or,  in  the case of accounts with associated code, the number of contract-creations made by this account.  For account of address a in state σ, this would be formally denoted σ[a]n.

This statement does not describe situation where there is a private key for address with code.
Also, I haven't found any statements to forbid existence of private key for a contract.
Intuition says that in both cases nonce just incremented but I need to know this for sure from an authorized source.


texts: How can you add a certain number of months to a timestamp (uint)?

texts:
I am writing a contract that will calculate interest on a periodic basis using the exact number of days in each period. So, for example, if I use Jan 1st 2018 to March 31st 2018 as an example, there would be 90 days in that period. I then need to move the period forward by 3 months to capture the next quarter of interest.

The specific code I am using now is:

function nextPeriod() public {
    lastPeriodDate = currentPeriodDate;
    currentPeriodDate += 1 years/4;
}

This works but it is approximate.

Anyone have any suggestions?

Thanks!

Phil


texts: Do Solidity smart contract symbols support unicode?

texts:
In a smart contract where the token name and symbol are defined, is unicode supported or should these be ASCII only characters?
As below, would it be a valid contract or token symbol?
    constructor() public
    ERC721("✕ray Ýour ℤen", "✕Ýℤ")
    {
        _setBaseURI("https://foo.foo");
    }


texts: MetaMask cannot connect to "localhost 8545"

texts:
When I choose localhost 8545 in MetaMask, apparently it is not able to connect. Please see screen shot:

I tried with several internet connection, however the same result.

Whereas, I can easily connect to ex. Ropsten.

Do I need to run testRPC before connecting to localhost 8545 ?


texts:
I think I may have lost all of my ETC.

Following Vitalik's instructions laid out here: https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/

I created 2 new wallets on the same wallet client that was running on the Hard Fork - and ran the split contract between them. ETH got there but ETC never turned up and I assume the mistake is that the wallet was created only on the ETH chain.

Is there any way to recover these ETC funds?


texts: what does the UnimplementedFeatureError mean?

texts: I'm getting the following error in remix.UnimplementedFeatureError: Non-padded store for function not implemented.


texts: Cannot see the 'amount' field for no replay contract in Mist wallet v0.9.0

texts:
I have followed the instructions on these reference pages:
https://steemit.com/ethereum/@pauls/ethereum-fork-step-by-step-guide-to-safely-splitting-your-eth-etc

https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/

I have added ('+ WATCH CONTRACT' button) for both contracts to my Ethereum Mist wallet v0.9.0 but I do not see the expected 'Send ' field for either contract. Any help or advise would be appreciated.

Screen capture from this other reference question but I have the identical problem and I cannot see from that post what the resolution was either if the user was using the wallet already but says using the wallet was the solution! (Sorry in advance if I missed something very obvious, I am just not able to comment on existing answers till my reputation reaches 50 unfortunately).


texts: Create my first ERC721 Collectible collection (VS CODE) //Need Advice

texts:
I want to start developing with Solidity in my Visual Studio Code my first ERC721 Collectible collection so i installed Visuall Studio Code first, then nodejs and npm and in the end Truffles and Ganache.
-I work on Window 10 OS
-Nodejs Version is v14.16.0
-npm Version is 7.6.3
-Solidity v0.5.16
I want my collection to be like cryptokitties project.
Can anyone provide me some step by step advice, some links or youtube videos that can help me understand the process in that ?
Thank in advance!!


texts: Metamask Vs Parity. Which browser extension is good to access DAPP using browser?

texts: I am trying to develop a DAPP and requirement is end user should be able to use DAPP from browser. I have two options available Metamask and Parity. Are there any other better options available to access DAPP from web browser? What are advantages and disadvantages of Metamask and Parity?


texts: What’s the point of checking msg.sender≠0 ? Are there cases where msg.sender can be null?

texts:
In the Tron contract (a large ICO listed on many exchanges) lies this modifier which is used for all token transfers :

modifier validAddress {
    assert(0x0 != msg.sender);
    _;
}

I understand how a contract can write directly into the ledger that a token transfer is made from 0x0000000000000000000000000000000000000000, but in that case, the msg is still tied to a an existing contract or private key.
What does this means ? How msg.sender can be equal to 0 ? (excepted the hypothetical case where a keccak256 hash collision is found)

Or could it be because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-86.md#specification ? If yes, how to withdraw other unprotected ERC20 from the 0x0 ethereum account on next fork ?


texts: First Time Ethereum Wallet User Setup Questions

texts:
I will try to make this a fast post with just a few questions I cannot figure out the answers to:

I am trying to accept/send ETH payments and have downloaded, installed, and created a wallet using Ethereum Wallet 0.11.1.

I have my wallet created and address, but here are my noobie questions:

1) Does this Ethereum wallet accept ETH payments? (I saw something about ETC vs. ETH and I care about ETH)

2) What all does one need to send a payment? Just the user's Address hex?

3) When a payment is sent, how long does it typically take to reflect in the receiver's wallet?

4) Is there any risk of losing Ether funds if the wallet is unable or doesn't sync with the Network Node for say 1 week?

5) I understand with Ethereum Wallet there is a password (user-created) and keystore, but isn't there also supposed to be a private key to save/backup somewhere?

6) I'm confused about Ethereum ICO and something about ERC20 or other? I'm not really sure, but I just want to make sure I can accept ETH payments without issue using Ethereum Wallet 0.11.1.

Thank you so much any answers will really help put my mind at ease about getting into Ether transactions.


texts: How many transactions per second can be processed by commodity hardware?

texts:
I am running geth on a private network with the following command:

geth --datadir firstserver --mine --minerthreads 1 --networkid 1300 --rpcport 8000  --rpcaddr 127.0.0.1 --port 30303 --rpcapi="db,eth,net,web3,personal,admin" --rpc --maxpeers 3 --nodiscover  --cache=2048 --memprofilerate=100 --targetgaslimit 210000000000  console

I have 8 GB of RAM and a quad-core CPU. I am running 1 miner thread.

When I run 24 transaction per second from jmeter the system runs fine, but when I increase it to 28 transactions per second the system freezes.

The CPU use is 370%, memory use 90% and I am not able to do any work on that server. I want to get 200+ transactions per second, how can I achieve that? What should I do to achieve such speeds?


texts: Is it possible to hack an ethereum account?

texts: I want to know if is it possible to hack an Ethereum account?


texts:
How does data storage work in Ethereum? Do variables of a Smart Contract map to columns of a table? And an update to those variables creates a new record with their latest values?

So if 100 employees of an organization have updated their basic details on Blockchain by calling the Smart Contract 100 times - one call from each employee, how is the data stored? How can the calling program retrieve an existing record? Is there a primary key?


texts: Can we say ERC-1155 is the same thing than SFT

texts:
I have understood the differences between Fongible tokens and Non Fongibles tokens (NFT).
I have read a new kind of token called SFT: Semi interchangeable token.
It is supposed to be a mix between FT and NFT.
ERC-1155 is a mix between FT and NFT too, but i do not see people saying ERC-1155 is a SFT.
So are there some differences between ERC-1155 and SFT definition ?
Thanks


texts: How to create an HD wallet transaction in ethereum? How to sign a transaction for multiple addresses in ethereum?

texts:
Suppose I know the number of hd child addresses used by my ethereum account, i want to send ether from those addresses.
How to sign such a transaction using ethereumjs-tx?

I need to send all the private keys and the from address should be an array too.


texts: how to check instantly when a user charges amount to his address generated by our app

texts:
Our app needs to detect and create a charging order asap whenever a user charges an amount of ETH/USDT(ERC20).
Due to the limit of infura API, we decided to set up our own ETH nodes and use JAVA to periodically check each address. When the balance increases, we will create a charging order with newblance-oldbalance.
But there are several issues:
1.The ETH nodes we own may crash or not fully synchronized so the latest balance is not accurate.
2.There are a lot addresses to scan and check each balance every time so it consumes too much CPU and resources.
Is there any better solution on this?
public BigDecimal balanceOf(String address) {
    BigDecimal bigDecimal = new BigDecimal("-1");

    Integer factor = 18;
    String contract = 0xXXXXXXXXX;

    try {
        Function function = new Function(
                "balanceOf",
                Collections.singletonList(new Address(address)),  // Solidity Types in smart contract functions
                Collections.singletonList(new TypeReference<Uint256>() {
                })
        );

        String encodedFunction = FunctionEncoder.encode(function);
        org.web3j.protocol.core.methods.response.EthCall response = getWeb3j().ethCall(
                Transaction.createEthCallTransaction(address, contract, encodedFunction),
                DefaultBlockParameterName.LATEST)
                .sendAsync().get(10, TimeUnit.SECONDS);

        String balance = response.getValue();

        if (StringUtility.isBlank(balance) || StringUtility.isBlank(balance.substring(2))) {
            return bigDecimal;
        }

        bigDecimal = Convert.fromWei(String.valueOf(Numeric.toBigInt(balance)), getEthUnit(factor));
    } catch (Exception e) {

    }
    return bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP);
}

public String getBalance(String address) {
    try {
        String balance = "0";
        BigDecimal bigDecimal = BigDecimal.ZERO;
        BigInteger prevNonce = BigInteger.ZERO;

        CryptoBalance cryptoBalance = CryptonBalanceAccessor.findBalanceByAddress(address);
        if (cryptoBalance != null) {
            balance = cryptoBalance.getBalance();
            prevNonce = new BigInteger(cryptoBalance.getNonce());
        }

        BigInteger latestNonce = getLatestNonce(address);
        if (!connect() || !isSynchronized(latestNonce, prevNonce)) {
            return balance;
        }

        for (int i = 0; i < 3; i++) {
            bigDecimal = balanceOf(address);
            if (bigDecimal.doubleValue() >= 0) {
                break;
            }
        }
        if (bigDecimal.doubleValue() < 0) {
            return balance;
        }

        Double walletBalance = Double.valueOf(balance);
        Double blockBalance = bigDecimal.doubleValue();

        if (blockBalance == walletBalance) {
            return balance;
        }
        COOSPayUtility.updateDigitalCoinBalance(address, Double.toString(blockBalance), latestNonce.toString(), "");
        if (walletBalance < blockBalance) {
        }
        return Double.toString(blockBalance);
    }
    catch (Exception e) {

    }
    return "0";
}


texts:
Excuse me, what data should I pass in _data bytes when I call tokenFallback and transferAndCall and approveAndCall?
 function transferAndCall(address _recipient, uint256 _amount, bytes _data)

 function tokenFallback(address sender, uint256 _value, bytes _extraData)

 function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)


texts:
I understand how to create contracts in Solidity, and how to create a Coin using Openzepplin. I do not understand how to integrate both.

Let say that every transaction on contract (MyContract), will use a coin (MyCoin). The value of Mycoin is based on ether.

Any link that provides a simple implementation for this kind of intergration would be helpful.


texts:
Whenever I try to use a Web3 Provider on Remix it says

Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

I have testrpc running, is there anything else required?


texts: Is our smart contract required gas,every time it executes.

texts: form my understandings, after the first execution of a smart contract, the network will return the remaining gas to the contract sender. if so, how will the contract  obtain  gas for future execution??


texts: Why I am not able to decompile this contract?

texts:
I wanted to decompile this, contract but for some reason the output saying only:

No regular functions. That's it.

Here is the full output:
#
#  Panoramix v4 Oct 2019
#  Decompiled source of bsc:0xa01aF66c02c5bc9320036cC2E8665a35D7051161
#
#  Let's make the world open source
#
#
#  I failed with these:
#  - _fallback()
#  All the rest is below.
#

#
#  No regular functions. That's it.
#

I don't understand how that is possible because this contract is used to execute swaps on PancakeSwap so there has to be at least one function... any ideas?


texts: How to calculate OHCL for a pair traded on a DEX exchange?

texts:
I understand the inputs of OHLC, which are:

[..] open, high, low, and close price for a given period.

I also understand how to get a pair price using getReserves of a pair contract.
It will give us something along the lines of:
Result {
  _reserve0: '3219645034999541693795',
  _reserve1: '86735629384854886759666',
  _blockTimestampLast: '1621295406'
}

Assuming my understanding is correct, then I should be able to query getReserves any time Swap event takes place, e.g.
web3.eth.subscribe(
  'logs',
  {
    address: '0x804678fa97d91B974ec2af3c843270886528a9E6',

  },
  async (error, data) => {
    const pairContract = new web3.eth.Contract(
      PANCAKESWAP_PAIR_ABI,
      '0x804678fa97d91B974ec2af3c843270886528a9E6',
    );

    const logEvent = parseLogEvent(data);

    const event = await pairContract.methods.getReserves().call();

    console.log({
      logEventName: logEvent.name,
      _reserve0: event._reserve0,
      _reserve1: event._reserve1,
      _blockTimestampLast: event._blockTimestampLast,
    });
  },
);

However, looking at the log, I don't see the _reserve0 / _reserve1 changing after every Sync or Swap event.
{
  logEventName: 'Sync',
  _reserve0: '3128242699498542739033',
  _reserve1: '89389256838727640360249',
  _blockTimestampLast: '1621313856'
}
{
  logEventName: 'Sync',
  _reserve0: '3128242699498542739033',
  _reserve1: '89389256838727640360249',
  _blockTimestampLast: '1621313856'
}
{
  logEventName: 'Swap',
  _reserve0: '3128242699498542739033',
  _reserve1: '89389256838727640360249',
  _blockTimestampLast: '1621313856'
}
{
  logEventName: 'Swap',
  _reserve0: '3128242699498542739033',
  _reserve1: '89389256838727640360249',
  _blockTimestampLast: '1621313856'
}
{
  logEventName: 'Sync',
  _reserve0: '3126796222989857156249',
  _reserve1: '89430712536412823566116',
  _blockTimestampLast: '1621313862'
}
{
  logEventName: 'Swap',
  _reserve0: '3126796222989857156249',
  _reserve1: '89430712536412823566116',
  _blockTimestampLast: '1621313862'
}
{
  logEventName: 'Sync',
  _reserve0: '3121479813474346848116',
  _reserve1: '89583410110976613586594',
  _blockTimestampLast: '1621313880'
}
{
  logEventName: 'Swap',
  _reserve0: '3121479813474346848116',
  _reserve1: '89583410110976613586594',
  _blockTimestampLast: '1621313880'
}
{
  logEventName: 'Sync',
  _reserve0: '3121479813474346848116',
  _reserve1: '89583410110976613586594',
  _blockTimestampLast: '1621313880'
}
{
  logEventName: 'Swap',
  _reserve0: '3121479813474346848116',
  _reserve1: '89583410110976613586594',
  _blockTimestampLast: '1621313880'
}
{
  logEventName: 'Sync',
  _reserve0: '3126884388024315500953',
  _reserve1: '89428958636355370725119',
  _blockTimestampLast: '1621313886'
}
{
  logEventName: 'Swap',
  _reserve0: '3126884388024315500953',
  _reserve1: '89428958636355370725119',
  _blockTimestampLast: '1621313886'
}
{
  logEventName: 'Sync',
  _reserve0: '3123400514276372620992',
  _reserve1: '89528958636355370725119',
  _blockTimestampLast: '1621313930'
}
{
  logEventName: 'Swap',
  _reserve0: '3123400514276372620992',
  _reserve1: '89528958636355370725119',
  _blockTimestampLast: '1621313930'
}

Therefore, what's the correct way to determine price of every trade?


texts: How to build a raw transaction to interact with a contract, with web3.py

texts:
Thanks to the support of this community I am able to create transactions on the network using the guidance provided in this post:
 How to send a transaction to myetherapi.com with Web3.py

To send a transaction I need to reference the allowed methods shown at http://www.myetherapi.com/.  With that in mind I am able to sign a transaction locally and use the sendRawTransaction method to broadcast it to the network.

My question now is how would I create a transaction that invokes a function within a contract that is already deployed on the network. How would you modify the transaction arguments to invoke a specific contract and call a specific function within that contract.

This is the example of a simple transaction. What is needed to create the raw transaction that calls an existing contract?

transaction = {
        'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
        'value': 1000000000,
        'gas': 2000000,
        'gasPrice': 234567897654321,
        'nonce': 0,
        'chainId': 1
    }

I am having trouble because the typically contract API methods in web3.py are not available through MyEtherAPI. Also I am okay with using v4 of web3.py if that is critical.


texts: How to store lots of private keys on a server?

texts:
I am building a web app where I have to keep track of a private key associated with each user. For the sake of this discussion let's assume that it's an exchange and users can send their ETH to this address and ignore all the complexities of cold storage.

So far I have managed to cobble together this code for web3.py:

from web3 import *
web3 = Web3(IPCProvider(ipc_path='/path/to/geth.ipc'))
random_private_key = '0x71a7f0e2ef1b7ff501b65a1650d48b8d5521fadc9539eec146d4faa6f5ca9ccc'
random_password = 'qwertyuiop'
address = web3.personal.importRawKey(random_private_key, random_password)

# address -> '0x930198a4bdd322ee3305fcf0bcb106064b38754b'
# web3.eth.accounts -> [..., '0x930198a4bdd322ee3305fcf0bcb106064b38754b']

What is the correct way to generate and store these private keys? In the above example I just pulled something from the internet and modified it a bit.

My plan is to generate random private keys, dump them in a DB and import them whenever ETH from those accounts have to be transferred. Since there is no web3.personal.deleteAccount I'd have to delete the json file from the keystore after I've finished the transfer and call importRawKey again if I need to make a transfer.

I am not sure if my plan is a good one and am looking for feedback or better ways to handle this.


texts:
Suppose I have access to a full archive Node and I want to fork from a specific block using Ganache.
Using ganache-cli, I can specify where to fork using the --fork parameter
by passing it the Node access point and appending the block number after the symbol @.
For example if I want to fork from the block 11267664:
ganache-cli --fork=http://myNode@11267664

My question is:  are the transactions mined inside the block 11267664 included that fork or not?


texts: Where can I get a contract review in Solidity? How much would it cost?

texts: Basically, I want to deploy a lottery contract, which by default should be very precise and secure, as all balance will be stored on the contract, and I have to track winner balances there as well. I have read some security issues and race conditions problems, but yet would be good to have some review from outside of my head.


texts: Why transaction cost for same function differs even though content of function is same?

texts:
I have written following contracts to test the gas used by a simple function depends on what parameters. As described here the four use cases, each gives different transaction cost even though content of function is exactly same. I tried to know the impact of const function to reduce gas.

The content of 2 functions is just a = constantFnA(); and a = a=5, but it results in different transaction cost. As you can see Case 1 and 2 are exacly same, just the function name and Case 1 and 3 are same just case 3 has some addition functions added. But transaction cost is still different.

Why transaction cost for same function performing same computational steps is different?

Case 1:

pragma solidity ^0.4.16;
contract TestConst{
    uint public a = 10;

    function constantFnA() constant returns (uint) {
        return  a+5;
    }

    // Transaction cost: 26658 gas.
    // Execution cost: 5386 gas.
    function const_NonConst_A(){
        a = constantFnA();
    }

    // Transaction cost: 26644 gas.
    // Execution cost: 5372 gas.
    function nonConst_A(){
        a = a+5;
    }
}

case 2:

pragma solidity ^0.4.16;
contract TestConst{
    uint public a = 10;

    function constantFnA() constant returns (uint) {
        return  a+5;
    }

    // Transaction cost: 26636 gas.
    // Execution cost: 5364 gas.
    function NonCosntUsesConst(){
        a = constantFnA();
    }

    // Transaction cost: 26644 gas.
    // Execution cost: 5372 gas.
    function nonConstantFn(){
        a = a+5;
    }
}

Case 3:

pragma solidity ^0.4.16;
contract TestConst{
    uint public a = 10;

    function constantFnA() constant returns (uint) {
        return  a+5;
    }

    // Transaction cost: 26676 gas.
    // Execution cost: 5404 gas.
    function const_NonConst_A(){
        a = constantFnA();
    }

    // Transaction cost: 26684 gas.
    // Execution cost: 5412 gas.

    function nonConst_A(){
        a = a+5;
    }

    uint8 public b = 10;

    // Transaction cost: 27097 gas.
    // Execution cost: 5825 gas.
    function constantFnB() constant returns (uint8) {
        return  b+5;
    }

    // Transaction cost: 26995 gas.
    // Execution cost: 5723 gas.
    function const_NonConst_B(){
        b = b+5;
    }

    function nonConst_B(){
        b = constantFnB();
    }
}

Case 4:

pragma solidity ^0.4.16;
contract TestConst{
    uint public a = 10;

    function constantFnA() constant returns (uint) {
        return  a+5;
    }

    // Transaction cost: 26654 gas.
    // Execution cost: 5382 gas.
    function NonCosntUsesConst(){
        a = constantFnA();
    }

    // Transaction cost: 26662 gas.
    // Execution cost: 5390 gas.

    function nonConstantFn(){
        a = a+5;
    }

    uint8 public b = 10;
    function constantFnB() constant returns (uint8) {
        return  b+5;
    }

    // Transaction cost: 26973 gas.
    // Execution cost: 5701 gas.
    function nonConstUisngB(){
        b = b+5;
    }

    // Transaction cost: 27053 gas.
    // Execution cost: 5781 gas.
    function NonConstUsingConstB(){
        b = constantFnB();
    }
}

So pints that needs to addressed are:

Does transaction cost depends on:

function name?
number of other functions in contract?
using uint or unit8 as function parameter?

Does using constant function to perform calculation decreases/increases gas consumption (as used 2 functions in every case results different gas)?

If the transaction cost depends on them, then WHY and HOW?


texts: What is the maximum computation a query or constant function in solidity can perform?

texts:
Since query or constant functions are just executed on single node there is no dependency on gas or gas limit.
I am performing Quicksort in query/constant method. EVM can sort an array of length up to 50000. The function returns zero if array size increases.


texts: Error creating Transaction with pyethereum: Can only serialize integers

texts:
I'm following the instructions found here to create an offline Transaction. When executing, the following line, I get "Can only serialize integers" exception raised by rlp. I did import pdb;pdb.pm() and the address is a string, not an integer (obviously). Any idea what's going on?

t = ethereum.transactions.Transaction(nonce, 60 * 10**9, 21000, to, value, '').sign(k)


texts: What is the tech stack behind the Lighthouse client?

texts:
What are Lighthouse's major components?  What databases did it consider and decide on?

Are there elements in its architecture that are particularly differentiated from how other beacon chain clients are designed and implemented?


texts: How would I exchange ETH for DAI in uniswap directly from sbt-ethereum?

texts:
Firstly, i love sbt-ethereum. It is zippy and an absolute pleasure. Having completed the contract-interaction portion of the tutorial, I wanted to test out a live contract.

I would like to interact with the uniswap.io ETH-DAI-exchange contract directly from sbt-ethereum to obtain 2 DAI.

I found the dai-token address by scrolling on etherscan
Then used the Uniswap docs to get the uniswap-factory contract address
Called ethTransactionView uniswap-factory getExchange dai-token
This returned the uniswap-dai-exchange address (0x09cabec1ead1c0ba254b09efb3ee13841712be14)
I verified that the Contract ABI on etherscan matched the github version
Then I tried to obtain 2 DAI with a timer of 5 minutes. Varying combinations of input parameters (See A to E), including some with the [ETH to pay, optional] field, failed with the same error.
I checked the dai contract, which seems to be 18 decimals, so I changed the DAI input to 2e18. I tried the optional payment in ether and in finney denominations. I also had a go with the ethToTokenSwapInput, specifying the amount of ETH rather than DAI, same outcome.

  [error] com.mchange.sc.v2.jsonrpc.package$JsonrpcException: gas required exceeds allowance or always failing transaction [code=-32000]: No further information

I'm sure it's something simple I'm doing. The sending wallet is funded with >5 DAI worth of ETH.

Any ideas?

Note: I wasn't able to create the new sbt-ethereum tag as intended as reputation <150.

A: ethTransactionInvoke uniswap-dai-exchange ethToTokenSwapOutput 2 300

B: ethTransactionInvoke uniswap-dai-exchange ethToTokenSwapOutput 2 300 15 finney

C: ethTransactionInvoke uniswap-dai-exchange ethToTokenSwapOutput 2000000000000000000 300

D: ethTransactionInvoke uniswap-dai-exchange ethToTokenSwapOutput 2000000000000000000 300 15 finney

E: ethTransactionInvoke uniswap-dai-exchange ethToTokenSwapOutput 2000000000000000000 300 0.015 ether


texts:
I have some questions that need clarification.

Lets say if I create a trade-in website using blockchain technology,

First, do I store all sort of data into blockchain such as user credentials, user info, product info, etc? I'm sure trade data between the users need to be stored in the blockchain, but what about other data I mentioned above?

Second, since user credentials are private data, shouldn't they be stored in other database like sql-server?

Third, if they can be stored and retrieved from other database, does ethereum dapp provide any functionality to pull those APIs? (ex: .Net Core API)

Last but not least, is it also a good approach to store other data such as each product information into blockchain? (worried about too much data in blockchain?)

Thanks in advance.


texts: Ethereum/Blockchain versioning and update

texts:
I've noticed the hard fork, there's some mechanism in the code to ensure and enforce the node to run the updated version. The mechanism is so called "consensus challenge".
What is this indeed? Some math computation? I read that there will be a timeout and forced cutoff if one can't respond with correct challenge message. Can someone explain how it works?

Since in the devcon 2, people suggest Ethereum is at its early stage, which still subjects to some changes in the future, how do we envision the changes?

What is the method used to ensure the nodes are running the same set of rule/protocol, or some mining software? How to enforce an update? Is such thing as the "consensus challenge" commonly happened in other blockchain when they have "new version"?


texts: Unable to understand how smart contracts work

texts:
I'm reading several articles about privacy in ethereum smart contracts but still I don't understand how everything in the smart contract is visible to anyone?

What does this mean?