texts: Peer discovery not working on private network

texts:
I'm running 3 nodes with the following command:

geth --verbosity 4 --autodag --nat any --genesis /opt/blockchain/genesis.json \
     --datadir /opt/blockchain/data --networkid 4828 --port 30303 --rpc \
     --rpcaddr 10.48.247.25 --rpcport 8545 --rpcapi db,eth,net,web3,admin \
     --rpccorsdomain '*' --fast --mine --ipcdisable

The genesis.json file is the same for every node (I've checksumed them to be sure).

What happens is the nodes can't find each other alone, I have to manually connect them throw admin.addPeer.

To test it, I've created a interval loop in the console to print admin.peers every 1 sec.:

var interval = setInterval(function(){console.log(admin.peers)}, 1000);

If if connect node 1 to node 2 (1--2), they keep connecting to and disconnecting from each other. But node 3 is not able to connect to any of them.

Why is this happening?


texts: Cancelled Transaction in MetaMask USDC leads to loss of funds

texts:
I had attempted to transfer 992 USDC from MetaMask to a Ledger Account but had decided to cancel the transaction. On cancelling, MetaMask reports that the cancellation succeeded, but my MetaMask USDC account now says it has 92 USDC. What happened to the 900 USDC? Can anyone tell me what's going on? I am thinking it could be a Meta<ask problem.
Transaction IDs as follows:
https://etherscan.io/tx/0xd6fa8a8ca403e81730adc0e0757630f9cc23ba7c5968d557e896094911a83756
Copying and pasting the transaction log from Meta<ask as follows:
Send USDC Details
From: 0xED3Aa978586ed... > To: 0x95dd8c9653EBAD7...
Transaction
Nonce   4
Amount  -992.570199 USDC
Gas Limit (Units)   21000
Gas Used (Units)    21000
Gas Price (GWEI)    79.2
Total   0.001663 ETH    $2.40 USD
Activity Log

Transaction created with a value of 0 ETH at 05:10 on 3/1/2021.
Transaction submitted with gas fee of 0.012 ETH at 05:11 on 3/1/2021.
Transaction resubmitted with gas fee increased to 0.006 ETH at 10:57 on 3/1/2021
Transaction cancel attempted with gas fee of 0.002 ETH at 10:58 on 3/1/2021
Transaction successfully cancelled at 10:58 on 3/1/2021


texts:
I have the following problem, one of my function has a variable where the uint can be negative but I don't know of that before the user enter in the form the integer. How do I settle this problem ?
Here is the smart-contract:
// SPDX-License-Identifier: MIT
pragma solidity  >=0.5.16;

contract SupChain{
    //List of events
    event orderCreated(uint _orderID, address _counterparty);
    event orderShipped(uint _orderID, address _counterparty);
    event orderStored(uint _orderID, address _counterparty);
    event orderOutOfCompliance(uint _orderID, address _counterparty);
    event orderCompleted(uint _orderID, address _counterparty);

    // List of variable

    // Possible state of the order
    enum StateType {Created, InTransit, Stored, OutOfComplicance, Completed}

    // An order of the supply chain
    struct Order{
        // ID of the order
        uint orderID;
        //Number of time the order has been shipped/stored
        uint correspondingUpdate;
        // State of the order
        StateType state;
        // Barcode of the corder
        string barcode;
        // User starting the supply chain by introducing an order
        address initiatingCounterparty;
         // List  the products inside the order
        string productsList;
        // Temperature minimal of the recommended environment
        uint temperatureMinimal;
        // Temperature maximal of the recommended environment
        uint temperatureMaximal;
        // Expiration date of the products
        uint expirationDate;
        // Last destination of the order
        string finalDestination;
        // Date of creation/Shipping/Storage of the order
        uint date;
    }

    // Number of created order
    uint public orderCount = 0;

    mapping (uint => Order) public orders;

    function createOrder(string memory _barCode, string memory _productList, uint _min, uint _max, uint _expDate, string memory _fDestination) public{
        orderCount ++;
        orders[orderCount] = Order(orderCount, 1, StateType.Created, _barCode, msg.sender, _productList, _min, _max, _expDate, _fDestination, block.timestamp);
        emit orderCreated(orderCount, msg.sender);
    }

I thank in advance anybody who will take the time to help me.


texts: How do I unlock the Parity Ethereum Ethash prefunded account?


texts:
I created a private net within a folder in Documents. It works fine. I tried connecting ethereum wallet with private net...But ethereum wallet created another node in .ethereum folder and shows corresponding node.

When I moved private net folder to .ethereum ...wallet was connected and was able to see accounts in it.

Does ethereum wallet connects only to the geth in .ethereum folder?
Is there any way by which wallet will connect to the geth in any folder?


texts: Unable to buy erc20 tokens from a smart contract

texts:
very new to solidity development. I'm trying to buy ERC20 tokens from a smart contract but all my transactions are reverted.
I'm doing these tests on ropsten network.
Here is a part of the contract :
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

contract Contract {
    address internal constant UNISWAP_ROUTER_ADDRESS =
        0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    IUniswapV2Router02 public uniswapRouter;
    constructor() {
        uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
    }

    function swapEthForTokenWithUniswap(uint256 ethAmount, address tokenAddress)
        public
    {
        // Verify we have enough funds
        require(
            ethAmount <= address(this).balance,
            "Not enough Eth in contract to perform swap."
        );

        // Build arguments for uniswap router call
        address[] memory path = new address[](2);
        path[0] = uniswapRouter.WETH();
        path[1] = tokenAddress;

        // Make the call and give it 15 seconds
        // Set amountOutMin to 0 but no success with larger amounts either
        uniswapRouter.swapExactETHForTokens{value: ethAmount}(
            0,
            path,
            address(this),
            block.timestamp + 15
        );
    }

    // important to receive ETH
    receive() external payable {}
}

I'm able to send the eths to my contract but not buying a token. I'm running this piece of code :
const createTransaction2 = await web3.eth.accounts.signTransaction({
    from: MAIN_WALLET,
    to: CONTRACT_ADDY,
    gas: 210000,
    data: web3.eth.abi.encodeFunctionSignature('swapEthForTokenWithUniswap(0.001, 0xaD6D458402F60fD3Bd25163575031ACDce07538D)'),
    gasPrice: web3.utils.toHex(web3.utils.toWei('220','gwei')),
    chainId: 3

}, KEY);

const receipt2 = await web3.eth.sendSignedTransaction(createTransaction2.rawTransaction);

Here is the hash in case it could help
https://ropsten.etherscan.io/tx/0x86d166bb2cda4aa4ebe7ab6ceb1ce0fabfb2ad0005bf2d915d7faa3d931312b9
Thanks for your help !


texts: About a week ago I completed an online course from a reputed university. When I got the certificate, at the bottom I noticed a 'Blockchain Hash' followed by a long string of characters. When I clicked on it, it took me to a 'transaction details page'. My question is why is this here? Is this to authenticate the certificate?


texts: Did cryptokitties have a negative effect on Ethereum?

texts: I received a comment from a professional Bitcoin exchange where the person said that cryptokitties have had a negative effect on the ether. What could that mean? Is it true?


texts: Where is the ethLogObservable method in Web3j?

texts: I can´t find where is the Web3j ethLogObservable method. I can´t find in GitHub repo


texts:
I'm trying to benchmark geth full sync. Here are my current machine specs:

Google Cloud
16 vCPU
14 Gb RAM
700 Gb NVMe SSD RAID 0
772k read/258k write IOPS
6+ Gbps network

Launching with following docker-compose.yml

version: '2'
services:
  geth:
    image: ethereum/client-go
    command: "--syncmode full --nat=extip:x.x.x.x --cache=12288 --nousb"
    restart: always
    stop_grace_period: 4m
    stop_signal: SIGINT
    ports:
      - 30303:30303
    volumes:
      - /mnt/disks/ssd:/root/.ethereum

So far none of the resources seem to be maxed out:

loadavg 3/16
network 0.3/750 MB/s
iops (r+w) 20/1000000

The machine appears to be mostly idle. How do I find out what is currently limiting sync speed?

Current speed at block 2M is ~300 blocks/sec


texts: Why should (if at all) one consider EOS instead of Ethereum for smart contracts and dapps?

texts: Now that EOS testnet has been live for almost a month, what are your views on the capabilities of EOS(advertised vs actual). If one has to build a distributed application today then should EOS be considered a serious candidate?


texts: What is the advantage and disadvantage of deploying Erays on Ethereum?

texts:
I have read this paper, Erays: Reverse Engineering Ethereum's Opaque Smart Contracts. They proposed this reverse engineering tool for Ethereum smart contracts. it will take as input a compiled EVM smart contract without modification from the blockchain, and returns high level pseudocoded suitable for manual analysis.
What really is the use of this Erays? what drawback it has?


texts: solidity binary code with multiple "stop"

texts: I find some sol contains multiple "stop" instr. For example, this address has binary "0000000000000000", which means they have a lot of "stop". Anybody know what is the source code can cause this situation?


texts:
It seems like Etherscan can detect failed token transfer even though the transaction itself is successful and the gas isn't used completely.

Like in this transfer of Huobi Tokens

Is there a way to detect token transfer failures via RPC on a full non-archive Geth node? eth_getToken and eth_getTokenReceipt seems to produce nothing useful in that regard.


texts:
I'm trying to develop a weighted probability selection algorithm on BSC and I think I need an algorithm that can generate a random number within a given range for that.
What would be a "good enough" way to achieve that?
I know there's a lot of problems with RNG in smart contracts, but is there a solution that's practically safe enough for BSC?
For example if I'm not mistaken the miners all belong to Binance there, so as long you trust Binance (I know that this goes against the philosophy of crypto..) there shouldn't be mining attacks.


texts:
I want to transfer ETH from an individual address to another address. So is there any API provider who can send ETH from single Address to another address.

Also If I setup Web3 in windows machine using node npm then it download all nodes (I think node size is nearly 80 GB)?


texts: how to use import "@openzeppelin" in remix or import "https://github..." in truffle?

texts: I can do import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; in truffle and import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"; in remix but I need a solution that works for both. I can't maintain 2 sets of files, it makes no sense.


texts: How to execute smart contract code without gas or ether?

texts: I have been trying to execute my code on remix or ethereum wallet. But to deploy my smart contract, how can I execute the code without any gas and ether. I dont need it to be online. I just need to deploy for my project and it would be good if its offline and limit to local host to my computer.


texts: Are there any API to get real money value equivalent of a transaction?

texts:
I know that etherscan shows the total cost of a transaction both in eth and in US dollars.

Is there any api of any kind to be able to get instant value of eth when I send a transaction?


texts: how to call a human readable timestamp through solidity?

texts:
how to get human readable timestamp through solidity ?
I know there is block.timestamp to get the unix time. But i want it in human readable format like Mon Jun 19 11:51:19 IST 2017.

Please suggest.


texts: Gas Estimation Failed error when scheduling Aion call

texts:
I am trying to understand the Aion scheduling system, so I tried their code example from here.

Below is the code snippet:

pragma solidity ^0.4.24;

// interface Aion
contract Aion {
    uint256 public serviceFee;
    function ScheduleCall(uint256 blocknumber, address to, uint256 value, uint256 gaslimit, uint256 gasprice, bytes data, bool schedType) public payable returns (uint,address);

}

// Main contract
contract MyContract{
    uint256 public sqrtValue;
    Aion aion;

    function schedule_rqsr(uint256 number) public {
        aion = Aion(0xFcFB45679539667f7ed55FA59A15c8Cad73d9a4E);
        bytes memory data = abi.encodeWithSelector(bytes4(keccak256('sqrt(uint256)')),number);
        uint callCost = 200000*1e9 + aion.serviceFee();
        aion.ScheduleCall.value(callCost)( block.number+15, address(this), 0, 200000, 1e9, data, false);
    }

    function sqrt(uint256 number) public {
        sqrtValue = number**2;
    }

    function () public payable {}

}

The contract is deployed successfully at ropsten address 0x91FDda60342d55B249A05083A5e9cB8102674D05

I am facing an issue while initiating the function schedule_rqsr. When this function is triggered, I face this error of "Gas Estimation Failed"

Gas Limit: 3,000,000

Find the error screenshot here:


texts: How to sign a transaction using nodejs crypto?

texts:
I have a js client, web API

Js client send some data in JSON format, API prepare a transaction to be send to a smart contract, than it returns transaction raw to client to be signed locally,

and finally the client sign the transaction (using crypto) and post it again to API which send it to blockchain.

So how to sign transaction with standart crypto library (client will not use web3) ?


texts: Using a crowdsale contract, how to mint token in another token contract?

texts:
I'm trying to create a crowdsale contract with open-zeppelin. I'm using SampleCrowdsale.sol. I believe the following line of code creates a token contract and mints the token upon receiving ether.

function createTokenContract() internal returns (MintableToken) {
    return new SampleCrowdsaleToken();
  }

However, I rather want the crowdsale contract to mint a token in another mintable token contract. Is there any way the crowdsale contract can interact with an external token contract? Any suggestion or code snippet would be really helpful.


texts: differents between web3.eth.signTransaction And web3.eth.accounts.signTransaction

texts:
I don't understand the differents between these methods

web3.eth.signTransaction
and
web3.eth.accounts.signTransaction

And when I have to use.
If I try to use web3.eth.signTransaction with ganache or infura I get this error

Method eth_signTransaction not supported / The method eth_signTransaction does not exist/is not available


texts: Regarding Adding Peers on two local machine nodes

texts:
I am new to Ethereum and tried everything to connect testnet from two local machine nodes.

I have a geth node running on a small server. I want to connect to it via geth attach from my local computer. I can’t figure out how to do it:
I tried starting it will all different kinds of configs, like:

geth --rpcapi --wsapi --rpc

but when I locally do:

geth attach http://IP_ADDRESS:8545

I always just get this:

Fatal: Unable to attach to geth node - Invalid endpoint

Any idea how to start the node on the server?


texts: self-aware smart contracts using multi-agent system

texts:
My question is:

What can be the role and working of multi-agent system in smart contract to make it self-aware smart contracts that ensure legal enforcement??


texts:
Will gas be free in ETH 2.0?
More generally, will gas ever be free? Is it feasible in near decades?


texts: Listen to a solidity event from a smart contract function

texts:
I have the following event:

event WaitingPlayer2(address indexed player2);

Which I call through:

function partecipateAsPlayer2(address player2) public{
        emit WaitingPlayer2(player2);
}

Is it possible to wait in a smart contract function for that even to be fired?
Like this:

function startGame(address requiredPlayer2){
    //get the WaitingPlayer2 event with requiredPlayer2 address
}


texts:
I'm about to create an exchange and I want to trade ether on it.  But I'm quite confused of how to handle my clients' wallets.

I see that some exchanges like Poloniex receive the ether in my deposit address and withdraw it to their cold wallet, ok, but how can I implement this on my server?

Is there an easy way to automatically create new user's account and redirect its transactions to my cold Ethereum wallet?


texts: Error: Returned values aren't valid, did it run Out of Gas?

texts:
I got this problem when follow the instruction,

here my two contract:
1) token sale contract:

pragma solidity ^0.5.0;

import "./DappToken.sol";

contract DappTokenSale {

    address payable admin;
    DappToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor (DappToken _tokenContract, uint256 _tokenPrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;
    }
    function multiply (uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x);
    }

    function buyTokens (uint256 _numberOfTokens) public payable {

        require (msg.value == multiply(_numberOfTokens, tokenPrice));
        require (tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        require (tokenContract.transfer(msg.sender, _numberOfTokens));

        tokensSold += _numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);
    }
        function endSale () public {

            require (msg.sender == admin);
            require (tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
            selfdestruct(admin);
        }

    }

2) token contract:

pragma solidity ^0.5.0;

contract DappToken {
    string public name = "Dapp Token";
    string public symbol = "DToken";
    string public standard = "DToken v1.0";
    uint256 public totalSupply;

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

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

    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    constructor(uint256 _initialSupply) public {
        balanceOf[msg.sender] = _initialSupply;
        totalSupply = _initialSupply;
    }

    function transfer (address _to, uint256 _value) public returns(bool success) {
        require(balanceOf[msg.sender] >= _value);
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;

        emit Transfer(msg.sender, _to, _value);
        return true;
    }

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

    function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) {

        require (_value <= balanceOf[_from]);
        require (_value <= allowance[_from][msg.sender]);

        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;

        allowance[_from][msg.sender] -= _value;

        emit Transfer( _from, _to, _value);
        return true;
    }

}

how could i fix this ?

This is my migrate scripts:

const DappToken = artifacts.require("./DappToken.sol");
const DappTokenSale = artifacts.require('./DappTokenSale.sol');

module.exports = function(deployer) {
  deployer.deploy(DappToken, 1000000).then(function() {
    var tokenPrice = 1000000000000000;
    return deployer.deploy(DappTokenSale,DappToken.address, tokenPrice);

  });
};


texts: Is it possible to create false positives, aka "throwing exception" on purpose in solidity?

texts:
I've been playing with this over the past weekend and it seems impossible, I guess since it's considered a big security issue if it was possible. Example to illustrate what I am trying to achieve:

msg.sender sends something;
contract waits for confirmation if tx succeeds;
if tx does/doesn't: do something

Challenge: claim tx failed despite success...example of one of my attempts so far:

// this is the contract that we call
contract richkid{

function buy_ceo_place() public payable returns (bool)

{

if(msg.sender.send(this.balance))

{

return false;

}
sorry-failed() //some function that handles in case send above had failed
return true;

}

}

this is the 'malicious' contract on the msg.sender side that we used to call the contract above, this is a contract with payable fallback:

contract receiver{

function () external payable //fixed on suggestion by @goodvibration

{

//try to forward to someone
address someone = 0x.......
someone.send(msg.value);

//claim it failed using assembly because why not:

assembly

{

invalid

}

}

}

In this case the invalid assembly opcode simply reverts everything to the EOA, that is no state changes only gas seems to be wasted (not sure about the gas). I've tried with delegatecall to the contract and with throw or currently think what will happen if the fallback calls back using zero gas after the send say: call.gas(0).value(0) - will likely fail since gasless txes will not be mined? Thanx!


texts: Ballot contract: Why `voters[chairperson]`?

texts:
In the Ballot contract from the Solidity documentation, the Ballot function assigns

voters[chairperson].weight = 1

What does that mean? Out of the set of voters, we find the chairperson (like in a dictionary call) and assign it weight 1?


texts: Usage of the account part of a derivation path to generate Ethereum addresses

texts:
I recently read that Ethereum doesn't use the part of the BIP44 derivation path dedicated to accounts. What happens if I still use it?

I just tried generating addresses under this path m/44'/60'/1'/0/n, opened MyCrypto with my Trezor and I can access such derivation path. Also, I can see and send funds from these addresses.

Should I worry about some future consequence?


texts:
I am trying to declare array of structure but its not accepting. I got this
      program from internet.

    pragma solidity ^0.5.1;
      contract NaiveBank {
      struct Account {
         address addr ;
        uint balance ;
      }
      Account accounts [];
      function applyInterest () returns ( uint ) {
         for ( uint i = 0; i < accounts . length ; i++) {
            // apply 5 percent interest
            accounts [i]. balance = accounts [i]. balance* 105 / 100;
         }
         return accounts . length ;
      }
   }

I am getting following error message:

  D:\SolidityContractsSelf\Remix\From Remix Site\Struct>solc
  NaiveBank.sol NaiveBank.sol:8:18: Error: Expected ';' but got '['
  Account accounts [];

             ^

D:>

Some body please guide me.

Zulfi.


texts: What is the best practice to deploy local contracts for testing?

texts: I am trying to developing smart contracts let use some Tokens and DeFi protocols like USDC, Compound, Uniswap, etc. Then if I need to testing locally, I need to deploy them in localhost blockchain (Ganache). I currently can't find a good way to do this. Please help.


texts:
I ussing this function to transfer, but it working with value  0 wei

function send(address _from, address _to) public payable {
    require(msg.sender > 0);
    _from.transfer(msg.value);
    emit Payment( _from, _to, msg.value);
}

How can I implement this with another wei value?


texts: "Connection not open" error when subscribing to address with websocket

texts:
I'm trying to subscribe to transactions sent to or from a particular ethereum address. I also want to test this in a local private network, which is why I'm not using etherscan or something like that.

I start geth with this command: geth --ws --mine --minerthreads=1 --datadir ./test/testDataDir/ --networkid 15

I connect to the geth console with this command: geth attach ipc:./test/testDataDir/geth.ipc

Then I unlock the account and submit a transaction, like this:

web3.eth.sendTransaction({from:eth.coinbase, to:"0x3e1127Bf1A673D378a8570f7a79cEA4F10E20489", value: 100})
"0xe122a9fa56068f9c10802bf607b572d57de83022f6b46238b6a96629c5a0478e"

This is the output of the miner:

INFO [07-03|11:18:04] Successfully sealed new block            number=1846 hash=fe4bcc…c4eea9
INFO [07-03|11:18:04]  block reached canonical chain          number=1841 hash=a45268…7aee1b
INFO [07-03|11:18:04]  mined potential block                  number=1846 hash=fe4bcc…c4eea9
INFO [07-03|11:18:04] Commit new mining work                   number=1847 txs=0 uncles=0 elapsed=160.998µs
INFO [07-03|11:18:05] Submitted transaction                    fullhash=0xe122a9fa56068f9c10802bf607b572d57de83022f6b46238b6a96629c5a0478e recipient=0x3e1127Bf1A673D378a8570f7a79cEA4F10E20489
INFO [07-03|11:18:14] Successfully sealed new block            number=1847 hash=76f3ee…169d0f
INFO [07-03|11:18:14]  block reached canonical chain          number=1842 hash=d170fb…84b87e
INFO [07-03|11:18:14]  mined potential block                  number=1847 hash=76f3ee…169d0f
INFO [07-03|11:18:14] Commit new mining work                   number=1848 txs=1 uncles=0 elapsed=233.923µs

Here's how I connect to web3 from my code:

const Web3 = require('web3'); //1.0.0-beta.34
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
}
else {
    web3 = new Web3('ws://127.0.0.1:8546');
}

And here's where I subscribe to the logs. I want to have a callback whenever a transaction is sent to a particular address.

var options = {
    fromBlock: '0x0',
    address: '0x3e1127Bf1A673D378a8570f7a79cEA4F10E20489'
};
var subscription = web3.eth.subscribe('logs', options, function(error, result){
    if(error || result == null){
        console.log('Error when watching incoming transactions: ', error.message);
        return;
    }
    console.log('Got something back: ', result);
    // code continues...
}
subscription.on('data', function(log){
    console.log(log);
});

But this is what gets printed on the console from my code:

connection not open on send()
Error when watching incoming transactions:  connection not open
connection not open on send()
Error when watching incoming transactions:  connection not open
connection not open on send()
Error when watching incoming transactions:  connection not open
connection not open on send()
Error when watching incoming transactions:  connection not open

Anyone have any idea what could be causing this? Perhaps I'm not connecting to the websocket correctly.


texts: Obtain token transfer data from an address

texts:
I would like to obtain token transfer data from an address via Rest API

For example, take this address:
https://etherscan.io/address/0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98#tokentxns

(Etherscan doesn't answer support questions about their API "because its free and presented as is", and they don't seem to have an API endpoint to show that same data.)

That link shows all of the token transfers for that address.

I would like to see all token transfers of X for that address. X being a token of my choice.

What is involved with obtaining that data via API?


texts: How do I send part of a transaction to all token holders?

texts:
Here is the code for someone performing a transfer of my token

function transfer(address to, uint256 value) public returns (bool) {
    require(value <= _balances[msg.sender]);
    require(to != address(0));

    uint256 tokensToBurn = value.div(100000).mul(7);
    uint256 tokensToDividend = value.div(100000).mul(3);
    uint256 tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDividend);

    _balances[msg.sender] = _balances[msg.sender].sub(value);
    _balances[to] = _balances[to].add(tokensToTransfer);

    _totalSupply = _totalSupply.sub(tokensToBurn);

    emit Transfer(msg.sender, to, tokensToTransfer);
    emit Transfer(msg.sender, address(0), tokensToBurn);
    emit Transfer(msg.sender, ?, tokensToDividend);
    return true;
}

As you can see, 0.007% of the tokens are burned, and I want 0.003% to be sent to everyone who holds the token. I've put a '?' where I want the holder addresses to go. How do I go about giving out the tokensToDividend value equally among all holders?


texts:
What is the cheapest way for storing string in contract?
I'm looking at this transaction https://etherscan.io/tx/0xb92d030c914254473b41af12309c6ccfaf8fe7388b0d0d8a0ac53545df3f773e
and wonder that it used only 25851 gas. I have tried other datatypes like bytes, string and can't get same value.


texts: how to replicate bytes32 to uint256 conversion in javascript

texts:
I am attempting to replicate a bytes32 to uint256 conversion in nodejs. I would like to get the same result as this example contract

pragma solidity ^0.4.23;

contract TestContract {

    bytes32 internal lastHash;

    constructor() {
        lastHash = keccak256(abi.encodePacked(msg.sender, now));
    }

    function getHash() public view returns(bytes32) {
        return lastHash;
    }

    function getHashNum() public view returns(uint256) {
        return uint256(lastHash);
    }
}

In a truffle test I've tried the following(along with many others):

const TestContract = artifacts.require('TestContract.sol');
const BigNumber = web3.BigNumber;

require('chai')
  .use(require('chai-as-promised'))
  .use(require('chai-bignumber')(BigNumber))
  .should();

contract("TestContract", function(accounts) {

    it('can convert bytes32 to BigNumber in node', async function() {
        let contract = await TestContract.new({from:accounts[0]});
        let hash = await contract.getHash();
        let hashNum = await contract.getHashNum();
        let result = new BigNumber(hash);
        result.should.be.equal(hashNum);
    });

})

Basically I am not sure how the type conversion happens or how to replicate it in node. Any suggestions would be awesome!

Edit

The code above does work except for the last line. I needed to use the big number methods for compairing e.g.

assert(result.eq(hashNum) == true, "Result should be equal to hashNum");


texts:
I want to understand the concept of reentrancy attack in a smart contract. I know that a Malicious contract starts executing the code of another contract and this results in reentrancy attack. It can happen when in a contract a function receives ether. In this case a fallback function comes into play. But I can't understand how a contract gets control of another contract and recursively calls its functions like withdraw(). Kindly explain me this concept using the following two contracts, i got from a research paper:

contract Malicious {
   uint balance;
   MyBank bank = MyBank(0xdeadbeef8badf00d...);
function Malicious(){
   balance = msg.value;
   bank.Deposit.value(balance)();
   bank.Withdraw.value(0)(balance); // forwarding gas
}
function (){ // fallback function
   bank.Withdraw.value(0)(balance);
}
}

I can see that the contract has a Deposit() function and an unnamed fall back function(). This fall back function is calling

Withdraw.value(0)(balance);

What does the above call mean (particularly why it has two set of parenthesis?)  and how it becomes recursive?

I am also showing the bank contract:

contract MyBank {
   mapping (address=>uint) balances;
function Deposit() {
   balances[msg.sender] += msg.value;
}
function Withdraw(uint amount) {
   if(balances[msg.sender] >= amount) {
      msg.sender.send(amount);
      balances[msg.sender] -= amount;
   }
}
function Balance() constant returns(uint) {
   return balances[msg.sender];
 }
}

Zulfi.


texts: How to initialize a mapping of structs with a mappings?

texts:
I have a mapping of a struct, which has a mapping to another struct:
uint256 public questionIdCounter;
mapping(uint256 => Question) public questions;

    struct Question {
        uint256 answerCounter;
        mapping(uint256 => Answer) answers;
    }
    struct Answer {
        address answerer;
    }

And I'm looking to add a new Question, which can have Answers added to it.
function askQuestion() public {
        questions[questionIdCounter] = Question();
        questionIdCounter = questionIdCounter + 1;
    }

And then people can add answers
function answerQuestion(uint256 questionId) public {
        // Add new answer
        questions[questionId].answers[questions[questionId].answerCounter] = Answer({answerer: msg.sender});
        // update answer counter
        questions[questionId].answerCounter = questions[questionId].answerCounter + 1;
}

However, when I look at kbase_questions.questions(0) I only get to see the answerCounter and not the answer mapping.
Why is my empty mapping not being initialized?
I've looked at How to initialized struct with member variable type mapping and How to initialized struct with member variable type mapping, which seem to be the closest to what I'm looking to do, but they are declaring their struct outside the function, which I can't do because I have many structs.


texts:
I am trying to bid on a domain. However it says "Initializing ENS Registrar" ...

So ... I check the JavaScript Console (as recommended) and here is what it says:

However I don't know what to do now...

Thank You for your help.


texts: Getting a contract's fallback payable function to fire from another contract?

texts:
My contract (contract A) is meant to send txs to another contract (Contract B).  I want to end up having the fallback payable function of Contract B get called.  I try to accomplish this by making a function in Contract A to take in an address (contract B address) and then transfer 0 eth to contract B from contract A.

function txTest(address recipient_addr) payable external
{
  recipient_addr.transfer(0);
}

However this currently does not work even if the contract address I put in as the recipient_addr has a fallback payable function.

If I use another non contract address as the recipient_addr then transfer will go off without issue.

Is it possible to have Contract A manage to call Contract B's fallback payable function?

Thank you for the help.

EDIT:  The actual fallback function that should be called.

 function () external payable {
    buyObject(msg.sender);
}

function buyObject(address _beneficiary) onlyValidPurchase
onlyBuyer(_beneficiary)
onlyValidAddress(_beneficiary) public payable {
    uint numTokens = calculateTokens();
    shopSettings.fundsRaised = shopSettings.fundsRaised.add(msg.value);
    object.mint(_beneficiary, numTokens);
    ObjectPurchase(msg.sender, _beneficiary, msg.value, numTokens);
    forwardFunds();
}


texts: Which parts of function are executed externally and which are executed "on chain"?

texts:
I am still a solidity noob, so I apologize if the question is too basic.

I am trying to write a contract which saves the hash of a (potentially) large bunch of data on chain.

For this reason, I would like to write a function which performs the hash externally (i.e. on the caller machine, something like a view function), and then it saves back the result on the chain. Is it possible? A code example here:

contract Test {
  bytes32[] hashes;

  function extCall(bytes _data) external view {
    bytes32 hash = keccak256(_data);
    _intCall(hash);
  }

  function _intCall(bytes32 _hash) private {
    hashes.push(_hash)
  }
}

The intention here was to exclude the possibility to save the hash on the chain without having the original data. For this reason, the only way to call the function _intCall would be by means of calling it through extCall. But, it seems that by doing this trick, also extCall is called on chain and consumes gas. In particular, i get this warning while testing on truffle:

  Warning: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.

P.s. there is a (BIG) chance that I totally misunderstood the topic, so every help is really accepted!


texts: How long does it take to get the eth from Rinkeby after submitting to Twitter?

texts: I asked for the 3 day one, but I am not sure if that means I will get it in 3 days or that I can't get more in 3 days. It's been over 24 hours and my balance is still 0 and when I try and submit to get more it tells me I have to wait.


texts: How to get the value of the transaction?

texts:
I am using web3.py but I need help to know the value of the transaction sent.
I know that the information is stored in the input but how do I parse the string. I know nothing about ABI.
Here is the tx_hash = 0xb6a594e6e9579d76870d54618b8df25e6662a200f1d2f3c9e27f506e851fa092
and here is the input: 0xa9059cbb000000000000000000000000453a0961ed6badd98fc396b01ab9b5939d9e27f1000000000000000000000000000000000000000000000000000000000000000a

How do I get the value of the transaction in a simple value ?


texts: what is the transaction per second of hyperledger fabric with Kafka

texts: I want to know that how much transactions can be take place in one second over hyperledger fabric with Kafka protocol. I'm actually creating a network, as such project size is not as much big but if my product will do millions of transactions per second around the globe and want to log those transactions over hyperledger fabric so could it be possible that fabric can manage them all? If yes than how many nodes should i need to setup first and what should be the server specs to deploy the network. And if this is not the good idea of using fabric than kindly let me know which blockchain should i use to log the immutable and consortium ledger.


texts: Can't debug transactions that fail during the Web3.js estimateGas() call? No Tx Hash

texts:
NOTE: I am doing my work with the Ganache v1.2.2 GUI client on a Linux Ubuntu 18.04 station.

There are many revert errors that happen during the estimateGas() call that precedes the actual Web3.js send() call.  Unfortunately, as far as I can tell, you don't get back a Tx hash for transactions that revert during  the estimateGas() call, so you can't debug the problem with the Truffle debugger.

Instead, the Web3.js estimateGas() throws a promise rejection during that method call.  I also checked carefully the Ganache log window and it never shows a Tx hash.  However it does show a Tx hash for all the Ethereum transactions that concluded successfully before the one that reverts, and it does show reverted transactions that revert during the actual send() call.

When this happens, I make a temporary change to my code to skip the estimateGas() call and go straight to the send() call with an artificially high gas price to make sure the transaction does not revert due to insufficient gas.  This is all done just so I can get back a Tx Hashand debug the transaction with the Truffle debugger.

This workflow works but it is tedious.  Is there a better way to debug a transaction that reverts during the estimateGas()  than this?


texts:
I have installed geth on an offline-computer and created a account with ./geth account new. Than I have copied (USB-Stick) the resulting file from the offline-computers keystore/ to an online-computer, where I can check the balance of that account. Of course I will never type the passphrase for that account on the online-computer.

How can I transfer Ethers from the account using only geth? (I do not want to install any third-party software on the offline-computer.)

I have read other posts saying "using the unofficial RPC method eth.signTransaction". Unfortunately it's not clear to me, if this is related to geth or an other tool. I would very much appreciate to sign offline just with geth.


texts:
I am using Kraken to purchase Ether and now I want to use some third-party wallet to withdraw Ether and wallet should provide an API to transfer Ether from my wallet to another wallet.

MyEtherWallet does not provide any such API,is there any other wallet like MEW that exposes an API for transferring between wallets ?


texts: How can I copy Parity Browser UI favourites between computers?

texts:
On computer A I'm using the Parity Browser UI and here I have saved several of the the following:

Addresses (Addressbook, not Accounts)
Watched contracts

How can I move these to Computer B?

I've read about Backing up & Restoring, but have found nothing there about Addressbook or Watched contracts.

I've also tried copying /io.parity.ethereum/keys/<chain>/address_book.json from computer A to computer B but this hasn't copied my Addressbook.

What should I do?


texts: Numbers of Miners, Wallets and Contracts

texts: What's the best way to estimate or determine the approximate number of systems doing mining and maintaining the integrity of the ledger (there's https://ethstats.net/, but that doesn't show all miners, of course). Also curious about ways to know the number of smart contracts deployed on the mainnet.


texts: Pushing a struct to an array which contains an array itself

texts:
I was reading this article, which gives an example of a contract which won't work. Though they have fixed it in the article, I wanted to know why it doesn't work. I have copied a simplified version below:

pragma solidity ^0.4.18;

contract StructArrayInitWrong {
  struct Room {
    address[] players;
  }
  Room[] rooms;

  function createRoom() public {
    address[] adr;
    adr.push(msg.sender);
    Room memory room = Room(adr);
    rooms.push(room);
  }

  function getRoomsLength() view returns (uint) {
    return rooms.length;
  }
}

The strange thing is rooms array length increases by two each time createRoom is called in this contract. Can you explain this behaviour? Thanks.


texts: Are there any other providers for calling external APIs in Solidity other than Oraclize?


texts: Where does Ethereum Dapps go in known design paterns

texts:
I am doing a Dapp for a school project and I am supposed to choose a design pattern to work with.

I want to know the possibilities for design patterns concerning the ethereum dapps, or if they have some special design pattern of their own.


texts: Why do I get a bad instruction in the transaction?

texts:
Here is my withdraw dividend code :

  function WithdrawDividend(address) public {

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

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

        _totalSupply = _totalSupply.sub(DividendsToBurn);
                _RestrictedFromDividend[address(msg.sender)] = true;
        ClaimTime[address(msg.sender)] = now;

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

    }
    else {
        emit Transfer(address(this), msg.sender, 0);
    }

}

I used to have it so that people had to put in their balance in a value section as well as their address but I couldn't figure out how to stop people from claiming dividends worth more than their balance, so I did this. But now I get a bad instruction error in the transaction and I don't see what is wrong. Everything seems perfect to me.


texts:
I want to purchase some Ether from Kraken and then transfer some Ether(Real) to different accounts if they win(Using Kraken API).

Do I really need a blockchain for such scenario ? I don't want to mine anything. Just purchase and then rewards some users.


texts: Solidity - Calling parent payable not possible?

texts:
I'm trying to inherit and override a parent's payable function (and adding some modifier and logic) but so far seem unable to do so.

My first intuitive try was something like this:

contract foo {
    function test() public payable returns (uint256) {
        return msg.value;
    }
}

contract bar is foo {
    function test() public payable returns (uint256) {
        return super.test.value(msg.value / 2)();
    }
}

and received compile error:

TypeError: Member "value" not found or not visible after argument-dependent lookup in function () - did you forget the "payable" modifier?
    super.test.value(msg.value)();

Give the function a different name doesn't work either so it's not an overriding issue.

contract foo {
    function test() public payable returns (uint256) {
        return msg.value;
    }
}

contract bar is foo {
    function anotherTest() public payable returns (uint256) {
        return super.test.value(msg.value / 2)();
    }
}

I got slightly further by tricking compiler with a casting but this is obviously no good as would cause infinite loop at runtime:

contract foo {
    function test() public payable returns (uint256) {
        return msg.value;
    }
}

contract bar is foo {
    function test() public payable returns (uint256) {
        return foo(address(this)).test.value(msg.value / 2)();
    }
}

What works is combining the two, i.e. giving it a different name and casting:

contract foo {
    function test() public payable returns (uint256) {
        return msg.value;
    }
}

contract bar is foo {
    function anotherTest() public payable returns (uint256) {
        return foo(address(this)).test.value(msg.value / 2)();
    }
}

Now calling bar.test() with 6 wei returns 6 and calling bar.anotherTest() returns 3. But this isn't exactly what I want as it still exposes test() through bar.

So what am I doing wrong, or is this by design? Would really like to understand why Solidity behave this way and if there's a workaround to achieve what I want. thanks!


texts: DAPPS - Scope of what to put in your smart contract

texts:
As I'm learning more and more about developing Dapps, I'm having trouble understanding what needs to be stored in the smart contract (over our database etc..).

Let's take the case of a simple betting website. The way I picture creating a Dapp of a betting website would be the following and please correct me if I'm wrong.

Technology Used: Ruby on Rails (Back-End), React (Front end), Solidity(Smart Contract)

1) I would store in my database the following informations :

User (name, email, etc..)
List of available bets
List of user's bet

2) Upon creation of a user, I would create a new Ethereum Wallet with the same password as his credentials and store the public address of his wallet in the database.

3) I would store in the Smart Contract:

ID of the user (from the database)
ID of the bet (from the database)
amount bet
bet result/state
user ethereum wallet address
my website ethereum wallet address
and the code to execute the transaction based on the bet result (win : transfer his winnings to the user wallet, lose : transfer his
betting amount to my website wallet)

As a result, the smart contract would only contain information related to a betting transaction (bet results, amount bet) and the database will contain the rest.
To retrieve a user's history of bets, I would retrieve the list from the database and retrieve the results from the smart contract (linked by the ID of the bet and user).

Am I completely misunderstanding the Dapps/Smart contract concept ? Please advise, thanks !!


texts: Function, variable, struct or modifier declaration expected

texts:
I am using the following code structure;

pragma solidity ^0.5.0;

  contract TtdmToken {

    uint256 public totalSupply;

    function TtdmToken () public {
        totalSupply = 1000000;
    }
   }

But when compiling with truffle compile I am getting the following error,

I have seen similar issue here suggesting the change of contract name I changed the contract to the following but still getting similar results.

pragma solidity ^0.5.0;

  contract TtdmToken {

    uint256 public totalSupply;

    function TtdmToken () public {
        totalSupply = 1000000;
    }

    contract constructor_TtdmToken {
        function TtdmToken()

    }

   }

And this is the error after making the change;


texts: How can retrieve current contact value on specific blockNumber?

texts:
Let's we've got the following contract's source code with some interval variables like:

uint public feeMake;
uint public feeTake;
uint public feeRebate;

And corresponding methods that allow to change their state like:

function changeFeeMake()
function changeFeeTake()
function changeFeeRebate()

Is it possible to retrieve these internal variable values on specific block or transaction number?

Thanks in advance.


texts: Freezing ERC20 token for certain amount of time?

texts: Is there any functionality like randomly specifying freezing portion and freezing period .For example, we must transfer 100,000 ERC20 tokens to a users. We transfer 10,000 tokens with no restriction, 40,000 tokens with 3 months freezing, and 50,000 tokens with 5 months freezing.


texts:
I am using Remix IDE for my smart contract development. I am using the following import line
import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
But I am getting this error while compilation
DeclarationError: Undeclared identifier. setPublicChainlinkToken();
The entire code is:

pragma solidity ^0.6.0;

import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";

contract VersionControl {

    struct Asset {
        uint256 id;
        string name;
        string metadata;
        string ipfsHash;
        uint256 version;

        bool isPresent;

        mapping (address => uint256) contribution;
    }

    mapping (uint256 => Asset) assets;

    address tokenAddress;
    address owner;
    uint256 availabeId;

    address private oracle;
    bytes32 private jobId;
    uint256 private fee;

    constructor() public {
        owner = msg.sender;
        availabeId = 0;

        setPublicChainlinkToken();
        oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
        jobId = "29fa9aa13bf1468788b7cc4a500a45b8";
        fee = 0.1 * 10 ** 18; // 0.1 LINK

    }

    // function requestVolumeData() public returns (bytes32 requestId)
    // {
    //     Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);

    //     // Set the URL to perform the GET request on
    //     request.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");

    //     // Set the path to find the desired data in the API response, where the response format is:
    //     // {"RAW":
    //     //   {"ETH":
    //     //    {"USD":
    //     //     {
    //     //      "VOLUME24HOUR": xxx.xxx,
    //     //     }
    //     //    }
    //     //   }
    //     //  }
    //     request.add("path", "RAW.ETH.USD.VOLUME24HOUR");

    //     // Multiply the result by 1000000000000000000 to remove decimals
    //     int timesAmount = 10**18;
    //     request.addInt("times", timesAmount);

    //     // Sends the request
    //     return sendChainlinkRequestTo(oracle, request, fee);
    // }

}```

Ignore the requestVolumeData as it will be the place where I call the 3rd Party APIs


texts:
I am going through ethereum blockchain demo's and currently trying to call other contract deployed already on a local ethereum rpc in memory blockchain.

Using truffle and ethereum rpc i am testing this locally.

I create a contract compile and migrate it locally. then do the following command in powershell which gives me address

MyGameStore.deployed();

address:'0x1d6e1129725897cac1c332b1fcbcf4338d8f96c6'

now i copy above address i use it in my another contract like this

contract IScoreStore{
function GetGameScore(string name) returns(int);
}
 contract MyGameStore{
function showScore(string name) returns(int)
 {    IScoreStore store=    IScoreStore(0x1d6e1129725897cac1c332b1fcbcf4338d8f96c6);
return store.GetGameScore(name);
}
}

however when i do truffle compile , it gives me an error "this looks like an address but has invalid checksum"

My other contract is very much deployed and also it's method's work. then why above error? not sure what i am doing wrong. Can someone help.


texts: swapped eth for utk on uniswap- etherscan shows completed but uniswap still pending and i utk doesn't show in wallet!

texts:
help anyone?  i'm new to uniswap.  i swapped out eth for utk and my transcation was "dropped and replaced" by transaction hash 0xd167827dfe353c65b94c2a3673ea74deaa4f8762be771a87f7bf9942d06ef29a
i've tried restarting my browser and also restarting my metamask app and nothing.
It shows that the transaction was completed but on uniswap, it still says pending and i don't see my UTK coins in my metamask wallet!  thank you in advance for schooling a noob.


texts: java.lang.ClassCastException: org.bouncycastle to error while creating wallet using web3j

texts:
I am using web3j to create account.

String walletFileName = WalletUtils.generateFullNewWalletFile("
<password>",new File("some/path"));

But getting this error:

java.lang.ClassCastException: org.bouncycastle.jce.provider.JCEECPrivateKey cannot be cast to org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey

My setup in pom.xml is as follows:

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.54</version>
</dependency>

Please let me know where I am going wrong.


texts: How to reduce the gas price for complicated smart contracts?

texts:
This is my smart contract's calculateReward function:

function calculateReward(uint256 _amount, address _sender) internal view returns (uint256) {
        uint256 reward = 0;
        for (uint256 i= (depositor[_sender].time.sub(startTime)).div(timeWait);
        i<= ((depositor[_sender].time.sub(startTime)).div(timeWait)).add(now.sub(depositor[_sender].time)).div(timeWait);
        i++){
            uint count = penalty[i][0].totalPenaltiesInThisIndex;
            while(count != 0){
                if(penalty[i][count].time >= depositor[_sender].time && penalty[i][count].time <= now){
                    if (feePot > 0) {
                        reward += ((penalty[i][count].amount).mul(_amount)).div(penalty[i][count].deservers); // assuming that if feePot > 0 then also totalSupply > 0
                    }
                }
                count = count.sub(1);
            }

            if(count == 0){
                if(penalty[i][count].time >= depositor[_sender].time && penalty[i][count].time <= now){
                    if (feePot > 0) {
                        reward += ((penalty[i][count].amount).mul(_amount)).div(penalty[i][count].deservers); // assuming that if feePot > 0 then also totalSupply > 0
                    }
                }
            }
        }

        // if (feePot > 0) {
        //     reward = (feePot.mul(_amount)).div((_totalSupply.sub(balances[owner]))); // assuming that if feePot > 0 then also totalSupply > 0
        // }
        return reward;
    }

On withdraw, if tokens are sent to the contract address, contract address calculates his rewards and send back what ever the sender owe.

I am facing an issue that gas price kept increasing as more penalities are there.

Is there a way I can reduce the gas price?


texts:
So I recently purchased ether.pizza with the intention of setting it up so people can order pizza with ether just to use as an experiment in Dapp and contract development.

Initially I plan on just doing the ordering manually and letting users pick pizza places from Locu.  I'll just my own credit card and will either hang onto the ether or I might just use shapeshift to convert it to bitcoins.  Locu's API does have prices so I was planning on just trusting those and canceling the contract if the price turns out to be wrong.

Obviously I shouldn't get any money though until someone gets their pizza however I'm not sure the best way to handle the escrow.  Is this even possible?   What if I found an api that could tell me when the food was delivered?

I'm not looking for detailed instruction just a general design pattern for the contract.


texts: ETH sent to contract address, how to get it back?

texts:
Instead of transferring my ETH token to my wallet, I accidentally sent it to some contract address, this one: 0xE592427A0AEce92De3Edee1F18E0157C05861564.
Is there any way to get my ETH back?


texts:
I am trying to implement a Simplified World State Trie based on Merkle Patricia Tree.
Take the following image for example

there are four accounts

address  value

a711355   45
a77d337   1
a7f9365    2
a77d397   12

my question is, how do I generate the state root using programming language?
I was trying

const RLP = require('rlp');
const keccak256 = require('keccak256');
var nestedList = [0,"a7",
                    [
                        [],[2,"1335",45],[],[],[],[],[],[0,"d3",
                            [
                                [],[],[],[3,"7",1],[],[],[],[],[],[3,"7",12],[],[],[],[],[],[],[],[]
                            ]
                        ],[],[],[],[],[],[],[],[],[2,"9365",2],[]
                    ]
                 ];
var encoded = RLP.encode(nestedList);
console.log(keccak256(encoded).toString('hex'));

but clearly it's wrong, it comes out
09ac270191aa233ea294b2ffab5da5adf7620aef7739eb162ca6cacb245ebe63
where I believe the correct answer is
5838ad5578f346f40d3e6b71f9a82ae6e5198dd39c52e18deec63734da512055

Any comment or answer is appreciated!!
thanks for your valuable time


texts: What is a good alternative to `ContractTranslator.encode_abi`

texts:
Since the ethereum Python library has been deprecated in May 2019, the ContractTranslator.encode_abi function is probably not the best way to turn Python argument lists into calldata strings. In particular, it doesn't support functions with the same name but different argument lists.

What is a better way to do this? I've been digging into web3.py _utils but they don't have a single reusable function for this. Any alternatives to use in Python?

I'm looking for a function with an equivalent signature to this:

def encode_abi(abi, function_name: str, args: List[Any]) -> bytes:


texts: Access old transaction from a web react dapp

texts:
I have create a dapp react app with this command:
$ truffle unbox react

I have a sample web application in src/client/ folder.
This web application is able to communicate with Ethereum smart-contract through web3js library.
I want to get an history of all states for a given storage variable in my smart contract. Is it possible ?
Thanks


texts: Where is the ethereum network implementation?

texts:
I am new to ethereum and have been reading about all the new things in ethereum with respect to bitcoin's blockchain. I have read about the GHOST protocol for using secondary blockchains instead of throwing them away and the merkle-patricia tree. I dont really understand what exactly this new data structure is solving except that it stores each block's state as hash as a node. So the tree changes if any node has any changes in them.

What exactly are the problems in bitcoin's idea of blockchain that this new data structure is solving?
Where is the implementation for all this protocols and the data structures? Is it in mist or the clients that are available in various languages?


texts: can anyone explain why call, delegateCall, staticCall functions in solidity are called low level functions?

texts: As i have read at many resources, that these functions are low level functions. I want to know, should i use these methods to interact with already deployed contracts or not ?


texts: ERC20 vulnerability? Executing transferFrom undesirably

texts:
Say I have a contract called MyContract, and I require to send 100000 DAI to it. Ideally, I'd firstly call approve(<address of A>, 100000e18) in DAI's contract itself. Secondly, I'd execute, for instance, the function collectDAI(100000e18) from MyContract. This function will internally call transferFrom(msg.sender, address(this), 100000e18) in DAI's contract and update MyContract's state accordingly.

Well, in this scenario an attacker could detect my call to "approve" and immediately execute by himself the transferFrom function (with very high fee if needed) and this transaction could potentially arrive before mine. Whenever I would try to call the collectDAI function in MyContract, I wouldn't be able, since the allowance has decreased to zero. Furthermore, MyContract might not be prepared to handle undesired DAI, so those tokens might be lost forever.

So, is it just my imagination, or we are facing a HUGE vulnerability in ERC20 that could potentially disallow its usage in smart contracts?

Please note that I'm using DAI in this example for simplicity, but it's perfectly applicable to any ERC20.


texts:
I am trying to use a conditional (like an if statement) in assembly. The only assembly reference site I have ever been able to find says the opcode JUMPI is the way to do this.
Using solc 0.7.0, the latest version.
I wasn't sure how to specify the destination parameter for JUMPI, so I just put the word destination in there as a placeholder to test a compilation.
assembly
{
    jumpi (destination, eq (b_test, 1))
    mstore (t_byte, 1)
}

It didn't recognize the JUMPI command.
Error: Function not found.
     |
 165 |          jumpi (destination, eq (b_test, 1))
     |          ^^^^^

How can I implement conditional assembly code using solc 0.7.0?
Also, if anyone knows of any better assembly reference sites, I would be interested in knowing about them.


texts: Why 'web3.eth.syncing' (Truffle console) returns 'false' when actually the testnet is running?

texts:
I run the ethereum testnet using the following command

geth --testnet --syncmode "fast" --rpc --rpcapi db,eth,net,web3,personal --cache=1024  --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --bootnodes "enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303"

But truffle console returns 'false' for 'web3.eth.syncing'

user@user:~/voting$ truffle console
truffle(development)> web3.eth.syncing
false


texts: I am wondering if it’s possible to automatically withdraw eth from my trust wallet to my main wallet. I run a business and this would make things much easier for me. Basically if I receive eth from a customer it would then IMMEDIATELY transfer it to my main wallet. Is there a program that can do this ? Thanks !


texts:
I have seen similar questions here, but the answers didn't help so far.

I have a JS function in a React component that should parse all the past events of the contract. The function is invoked in componentWillMount(), and my intention is to get all the event results as objects, store them in the state and then render.

The function:

getAllEvents() {
    const contract = require("truffle-contract");
    const contract= contract(ContractOne);
    contract.setProvider(this.state.web3.currentProvider);

    var contractInstance;

    this.state.web3.eth.getAccounts((error, accounts) => {
      contract.deployed().then(instance => {
        contractInstance = instance;

        var events = contractInstance.EventResults({
          fromBlock: 0,
          toBlock: "latest"
        });
        events.watch(
          function(err, result) {
            if (err) {
              console.log("error!");
            } else {
              this.setState(prevState => ({
                eventData: [...prevState.eventData, result.args]
              }));
            }
          }.bind(this)
        );
      });
    });
  }

However, I get only the very last event object rendered with this function, instead having shown quite a bunch. What could be the issue here?


texts:
I'm working on a dapp and am running into a dilemma regarding how to balance trustlessness with the cost of transactions for users.

In order to reduce gas usage by users, I want to be able to able to delegate certain transactions to the contract owner (i.e., the contract owner address sends transactions that include the user's address as a parameter as opposed to transactions coming directly from the user and using msg.sender), however, the big sticking point is in ensuring that a user is who he claims to be so that one user who simply knows the address of another user does not generate fake transactions.

Here's a simple idea that I have to try to accomplish this:

Authorization Process

1) User first accesses the site with MetaMask and requests to begin authorization.  A request is sent to the contract owner's server that includes the user's public address.

2) The server generates a random string and records the string and user address in a database and sends the string back to user.

3) The user creates a password and, together with the string received from the server, creates a hash, which is then sent via a MetaMask transaction to the contract.  The contract records the association between the user's address and the hash in a mapping.

4) If necessary, the server listens for an event to indicate that the user has created a new mapping entry to associate his address with the hash.

5) After the previous steps are completed, the user can initiate transactions by sending requests to the server, which included the user's password as well as the other instructions necessary to complete the transaction.

6) When the server receives the transaction request and password in step 5, it can create a hash of the password and the secret string assigned to the user and then compare that to the hash mapped to the user's address in the contract.

7) Any functions delegated to the contract owner would include a modifier to restrict access to the contract owner.

Key Points

The password (or a pure hash of the password, not including the random string) is stored neither in the contract nor the contract owner's database
It may not be necessary to combine the random string with the user's password before hashing, but this provides an additional layer of security
The user could change his password at any time by repeating steps 1-3
If a user alters the hash mapped to him outside of the above process, the server will not allow him to delegate transactions (his fault)
Impersonating the user in server requests would require 1) knowing the user's address and 2) knowing the user's password.  This information could not be obtained by looking at previous transactions.

My knowledge of authorization patterns is still in the development stage, so apologies in advance if this has any glaring holes.


texts: eth.gasPrice is returning less value than expected

texts:
As mentioned in documentation eth.gasPrice returns the current gas price. The gas price is determined by the x latest blocks median gas price.

I was relying on this method to estimate current gas price that I send along with my transactions. But recently I faced an issue, most of my transactions are pending.

When I looked at the transactions, the gas price provided was 35 GWei, while on eth gas station, the safe low gas price is 57 GWei.

I checked the value of eth.gasPrice` on my node and this resulted to 25000000000 (25 GWei).

Why the value of eth.gasPrice is so low when the gas price of the network is increased to double.

I also checked some recent transactions on etherscan :
 0xf5ccc6ecc36b318c8ac9794e2b472fa2f9b3acc0b2adf662b4f858b76a69c278, 0x123789fd42ad2037fff8bfaca3caeb6bec179b4630588902ae95c9515c742432, 0xf78960adb886d9a31549a04154ce459e00896dac6c7156e749c63f6755c5a4c9

All of them has gas price of 60 Gwei. So why is eth.gasPrice is giving me 21GWei? Can I rely on this method to estimate current gas price? Are there any alternatives?

edit:
Recently the values returned by eth.gasPrice has been to 2 GWei, and the transactions (here) are pending for more than a day. While I can see the safe-low is around 12 Gwei.This function ditched me again.


texts:
I am having a dapp which is working perfectly in web browser using metamask wallet.Now I want to test my dapp in mobile browser using metamask mobile wallet.
I tried to make transactions in BC using mobile metamask but nothing happens(like no metamask poping-up to confirm transactions).
I am new to mobile metamask browser. Please help me to resolve this issue.
App.js Code
window.addEventListener('load', function () {

  if (typeof web3 !== 'undefined') {
    console.warn("Using web3 detected from external source.")
    window.web3 = new Web3(web3.currentProvider);
  }

else {
    console.warn("No web3 detected.");
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }

  ipfs = ipfsAPI({ host: 'localhost', port: '5001', protocol: 'http' });

  App.start();

});


texts: EhtosDistro Error Claymore for ETH mining (libOpenCL.so.1)

texts:
I'm trying use claymore for mining ETH but it get this error "/opt/miners/claymore/claymore error while loading shared libraries: libOpenCL.so.1: cannot open shared object file: No such file or directory"

I have 6 GPUs NVIDIA 1080 and EthosDistro. The config is:

# cat /home/ethos/local.conf

globalminer claymore
maxgputemp 70
stratumproxy enabled
proxywallet 0x0750a5C3daa7eacBA912F1cA581b37Ce7c0f7B8f
proxypool1 eth-us-east1.nanopool.org:9999
proxypool2 eth-us-west1.nanopool.org:9999
flags --cl-global-work 8192 --farm-recheck 200
globalfan 80
globalcore 1847
globalmem 5524
autoreboot 1

claymore.stub.conf

-colors 0
-dbg -1
-esm 1
-epool proxypool1 eth-us-east1.nanopool.org:9999
-ewal 0x0750a5C3daa7eacBA912F1cA581b37Ce7c0f7B8f
-epsw x
-eworker g1080-01
-allpools 1
-gser 2
-allcoins 1
-wd 0
-ethi 16


texts:
Could some one please

summarize the differences between V5 and V6
tell us where to find documentation - I could not find any although I understand this is in EIP 627
is it "production ready" ?
say whether the Go implementation in Geth is forward compatible: do I need to rewrite anything that I have done on top of Geth using V5

Many Thanks


texts: What is the exact data structure of each block?

texts:
is there any document / diagram describing Ethereum block structure in similar way as https://en.bitcoin.it/wiki/Block?

I know I can find implementation at https://github.com/ethereum/pyethereum/blob/develop/ethereum/blocks.py but I am still missing some information as bytesize and similar...


texts: Garbage collection of Stale/abandoned/disused smart contracts on Ethereum

texts:
What happens to stale/abandoned/disused smart contracts on the ethereum mainnet/testnets?

Is there some sort of a automatic Garbage collection method such as purge to purge these stale smart contracts? i.e., contracts with no longer active pointers


texts: Handling decimals in somewhat complex math

texts:
I'm a bit lost on what to do with the following calculation. The problem is that decimals are being round up/down, which obviously doesn't give me the result I desire.

int totalValue = 275000;
int percentage = 2;

for (uint i = 0; i < 30; i++) {
  totalValue += totalValue * percentage / 100;
}

With the above code, the result is:

498108

The expected result is:

498124.436

I know that normally you could simply use the following calculation to work with a predetermined amount of decimals like so:

value * 10**4 (4 decimals)

But I haven't gotten that to work in this case, often resulting in insanely high numbers due to the multiplication and division that "do not make sense" once I revert the above calculation using:

value / 10**4

Thank you very much for your time. Any help would be very much appreciated!


texts: Accepting transaction signature via web3 with metamask

texts: I am using uniswap swap functions on web3 and I wanted to accept the transaction directly on code without using the pop up prompt on metamask. Is there a way to do this? or other alternative/workaround to make it possible?


texts: Unable to execute contracts using 'Ethereum Wallet' on Etherum Private Chain due to out of gas

texts:
I have created Ethereum Private Network and mined sufficient ether.I have
deployed a Smart Contract 'Hello World' and tried to execute the functions in the deployed contract.

But the contract won't get executed due to low gas.

I have included the contract code for your reference.

pragma solidity ^0.4.2;

contract HelloWorld {
    uint public balance;

    function HelloWorld(){
             balance=1000;
    }
    function deposit(uint _value) returns (uint _newValue){
             balance += _value;
             return balance;
    }
}

I have successfully executed this contract using browsersolidity and truffle.
But it won't get executed using Ethereum Wallet.


texts: Deploy the ethereum contract token and transfer to other address using node js web3

texts: Deploy the ethereum contract token and transfer token from one address to other address using node js web3.Anyone please help me.


texts: Can you deploy a contract from a Ledger Nano S using Remix?

texts:
I have deployed a contract from a Ledger Nano S before by connecting to MEW and deploying using Bytecode and ABI of the contract.

However I do not know what compiler version MEW used and so cannot verify the contract on etherscan.

I have been able to verify contracts deployed on Rinkeby network using remix and metamask. Metamask automatically connects my wallet to remix to handle the deployment.

IS there a way to do this from a hardware wallet? I would like my wallet address in my ledeger nano s to be the msg.sender but I would also like to be able to verify the contract on etherscan.

Thanks.


texts: why a parameter must be "storage" or "memory"?

texts:
I am creating a token like this:

pragma solidity ^0.5.0;

import "../utils/math/SafeMath.sol";

contract ExampleDivisibleNFTs {
    using SafeMath for uint256;

    // Percentage of ownership over a token
    mapping(address => mapping(string => uint)) ownerToTokenShare;

    // If a token has been created
    mapping(string => bool) mintedToken;

    modifier onlyNonExistentToken(string _tokenId) {
        require(mintedToken[_tokenId] == false, "the NFT already exists");
        _;
    }

    modifier onlyExistentToken(string _tokenId) {
        require(mintedToken[_tokenId] == true, "the NFT doesn't exists");
        _;
    }

}

and I am testing with remix but I have the following problem

Data location must be "storage" or "memory" for parameter in function, but none was given.

modifier onlyNonExistentToken(string _tokenId) {
                              ^-------------^

why a parameter may to be a "storage", It is not always "memory" ?


texts:
This is really a two part question.
First, the only way I can get the error message thrown by a Smart Contract require statement is to call the function first with a call rather than a send. send does not return the message thrown by a failed require statement whereas call does.
Example. In Solidity I might have the following:
require (org._isUser(_user),'Error: User not registered');
In my React frontend I want to be able to display 'Error: User not registered'.
My function call in React is as follows:
async function createPO(e) {
    e.preventDefault()
    const poeacct = e.target.elements[0].value
    const ponumber = e.target.elements[1].value
    const podate = e.target.elements[2].value
    let callOK = true
    try {
      await contract2.methods
        .createOrder('0xd2c4895e24095f23277df168f94a6c035813fe5d', poeacct, ponumber, podate)
        .call({ from: accounts[0] })
    } catch (err) {
      callOK = false
      setMess(err.message)
      console.log(err)
    }
    if (callOK) {
      await contract2.methods
        .createOrder('0xd2c4895e24095f23277df168f94a6c035813fe5d', poeacct, ponumber, podate)
        .send({ from: accounts[0] })

      setpouAcct(pouacct)
      setpoeAcct(poeacct)
      setpoNumber(ponumber)
      setpoDate(podate)
      setMess('Transaction successful')
    }
  }

This works but it's kind of klugey so I'm wondering if there's a better way.
Second. The error returned by the 'catch' in the Web3 call is JSON but there's a prefix:
Error: [object Object]
{
  "message": "VM Exception while processing transaction: revert Error: Order already exists",
  "code": -32000,
  "data": {
    "0x270bb8ddea630f3fc42a4f6196d7710cc50779a34994fd534a8ce139976b0ef5": {
      "error": "revert",
      "program_counter": 21219,
      "return": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001b4572726f723a204f7264657220616c7265616479206578697374730000000000",
      "reason": "Error: Order already exists"
    }

The Error: [object Object] prefix prevents me from parsing out the 'reason:' node. If I remove the prefix manually (i.e. hard code it) it works.
I've tried substring,slice and JSON.parse etc. but I can't find a solution.


texts: Is the Ethereum blockchain a list/chain of transactions or a list of contracts?

texts:
Ethereum newbie here with some general programming knowledge including basic Solidity. Below is my current mental picture of how Ehtereum works (please correct me if wrong).

A contract is a class (in OOP term) contains a bunch of functions that can be called by anybody once deployed on the blockchain. Each function may or may not contain ether transactions.

So if I consider ether the same as bitcoin, then the Ethereum blockchain should contain a list of blocks, with each block containing a bunch of ether transactions including the reward for the miner of that block.

But sometimes I also got the impression that the Ethereum blockchain is actually a list of contracts, as each contract has an "address" and being immutable once deployed.

Which one is true (or neither)?


texts: Gas cost / ETH fee in order to send Golem?

texts:
I want to send Golem from myetherwallet to a friends wallet.

How much does the Ethereum network charge in gas / ETH fee for sending a token?


texts: Problem with first sync in revived Ropsten Ethereum

texts:
Hello everyone i would like to sync to Ropsten test network for the first time.I use linux mint.First i followed the instruction here and execute the commands

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update

I need to use geth1.5.9 that allows the command web3.eth.complile.solidity so i thought i should not execute the command "sudo apt-get install ethereum" and instead i downloaded geth 1.5.9 version from here. Then i extracted the .tar.gz in Downloads folder. After that i opened a new terminal and went to Downloads and in the folder i had extracted.Then i run the command

./geth --rpc --rpcapi="db,eth,net,web3,personal,web3" --rpcaddr="localhost"
--rpcport="8545" --rpccorsdomain="http://localhost:3000" --testnet --bootnodes
"enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1
510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:303
03,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9
216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30
303"

In order to sync in the revived Ropsten. I left it running and after 8hours in some blocks(number 589K) it wrote synchronization failed: state data download canceled..i left it running and it seemed to keep downloading blocks(but the block number was smaller 585K before the error was 589K) but with much slower pace. I left it running for another 8hours until i saw it downloaded every block very slowly(imported 1 block) and the number of the block was 588K very close to the number i left it 8hours ago(585K). I read in some forum that that means the sync failed.So:

are my steps for installation of ethereum and geth right? Because instead of the command "sudo apt-get install ethereum" i thought it would be the same to go to the folder containing geth 1.5.9 and execute the commands there with ./geth (command)
When i executed the command ./geth --rpc --rpcapi="db,eth,net,web3,personal,web3" --rpcaddr="localhost"...(as described above) i got a message: no etherbase set and no accounts found. How can i create an account in ropsten ethereum test network? Could that be the cause that sync failed?

I am sorry for the long post, i am trying to be as clear as i can.Also i am new to the forum so i am sorry if i accidentally violated any rules of the forum.


texts: I understand that each node has a transaction pool, which is used for adding transactions to the block. What happens to the transactions when a miner's block is declared invalid? Also, how are transactions removed from the local node's transaction pool once they are mined into the block?


texts: How to deploy compiled contract file using the geth cli?

texts:
So I've followed the greeter contract tutorial from here to deploy a contract to my private cloud. It works fine and all, but it is rather difficult that I need to create a string from my contract and then deploy that. It would be easier if I could create a contract.sol file and compile that.

So I put the greeter code into a file:

contract mortal {
    address owner;

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

    function kill() {
        if (msg.sender == owner) selfdestruct(owner);
    }
}

contract greeter is mortal {
    string greeting;

    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    function greet() constant returns(string) {
        return greeting;
    }
}

and ran the following command:

solc --optimize --bin contract.sol

This creates two new files:

greeter.bin
mortal.bin

But from here I'm kinda lost. Does anybody know how I can deploy this greeter contract using geth and these two bin files? All tips are welcome!


texts: I want to use power of Eth to enable payment and some rpc related operations to my app. Which version(1.0 beta or 0.+) of webjs I need to use. May I know why?


texts:
My dApp allows user to save their URL when purchasing each NFT token. The obvious design would define --

struct NFT {
    ...
    string url;
}

However, URLs can be long. To save gas for users, I modify the design to save only the hash of URL in each NFT and the actual URL in another mapping, which basically means --

struct NFT {
    ...
    uint urlKeccak256;
}
mapping(uint => string) private urlMap;

function saveUrl(string calldata _url) {
    ...
    uint _urlKeccak256 = uint(keccak256(abi.encode(_url)));
    urlMap[_urlKeccak256] = _url;

    NFT memory nft;
    nft.urlKeccak256 = _urlKeccak256;
}

While this design does save gas on average, my question is:

Since there is no (efficient or cheap) way to delete unused entries from urlMap, would there be a future concern if the onchain storage of urlMap keeps growing (to hundreds of MB and beyond potentially)?


texts:
I am developing pool software for ethash coins. I use a private chain and pool software running on VMs so I need a CPU miner with stratum support that I can run on on my laptop VMs.
Currently I was an ethminer fork which lacks stratum support. Does anyone have, or know where I can DL one?

Thanks


texts: How to use IPFS to get the hash of the document and store it on private blockchain (using go-ethereum )? consider truffle framework and solidity as contract oriented language.


texts: send a certain portion to a specific address with every transaction

texts:
i have created a Smartcontract.  now i want the functionality: where 2.5% of every transaction is transferred to a fixed address. say the address is 0x809341c1c1cba2d6accf8188bca463a119443d. i know it can be done from transfer() and transferFrom(). but could not able to sum up the code.
here is the contract
     `pragma solidity ^0.5.0;

contract ERC20Interface {
    function totalSupply() public view returns (uint);
    function balanceOf(address tokenOwner) public view returns (uint balance);
    function allowance(address tokenOwner, address spender) public view returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);

    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

safe math---------------------------------------------------------------------------
......................
/////////

contract me is ERC20Interface, SafeMath {
    string public name;
    string public symbol;
    uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it

    uint256 public _totalSupply;

    mapping(address => uint) balances;
    mapping(address => mapping(address => uint)) allowed;

    constructor() public {
        name = "me";
        symbol = "me";
        decimals = 18;
        _totalSupply = 250000000000000000000000000;

        balances[msg.sender] = _totalSupply;
        emit Transfer(address(0), msg.sender, _totalSupply);
    }

    function totalSupply() public view returns (uint) {
        return _totalSupply  - balances[address(0)];
    }

    function balanceOf(address tokenOwner) public view returns (uint balance) {
        return balances[tokenOwner];
    }

    function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
        return allowed[tokenOwner][spender];
    }

    function approve(address spender, uint tokens) public returns (bool success) {
        allowed[msg.sender][spender] = tokens;
        emit Approval(msg.sender, spender, tokens);
        return true;
    }

    function transfer(address to, uint tokens) public returns (bool success) {
        balances[msg.sender] = safeSub(balances[msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        emit Transfer(msg.sender, to, tokens);
        return true;
    }

    function transferFrom(address from, address to, uint tokens) public returns (bool success) {
        balances[from] = safeSub(balances[from], tokens);
        allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        emit Transfer(from, to, tokens);
        return true;
    }
}


texts: What log message an event generates to blockchain?

texts:
The following is a portion of a Ballot.sol. There is a event votingCompleted() defined and triggered in function vote. What is the detail message this votingCompleted is going to emit to blockchain?

I understand event could serve log but what is the log message looks like? The event code itself did not provide any details about what log it will emit when triggered.

pragma solidity ^0.4.0;
contract Ballot {

 ....

    event votingCompleted();

    uint startTime;
    modifier validStage(Stage reqStage) {
        require(stage == reqStage);
        _;
    }

    constructor(uint8 _numProposals) public {
        chairperson = msg.sender;
        voters[chairperson].weight = 2;
        proposals.length = _numProposals;
        stage = Stage.Reg;
        startTime = now;
    }

    function vote(uint8 toProposal) public validStage(Stage.Vote) {
        Voter storage sender = voters[msg.sender];
        if (sender.voted || toProposal >= proposals.length) return;
        sender.voted = true;
        sender.vote = toProposal;
        proposals[toProposal].voteCount += sender.weight;
        if (now > (startTime + 30 seconds)) {
            stage = Stage.Done;
            emit votingCompleted();
        }
    }


texts:
I want to know whether the bottom layer of Ethereum requires miners to verify blocks?
The reason for this problem is that I have been thinking about a scenario of blockchain transaction verification recently: If the api provided by chainLink is called in the smart contract, it is necessary that the contract address has enough tokens for payment. When the block containing this transaction is broadcast, other miners will verify the transaction in the block. When the miner verify the transaction in the new coming block, he need to call the smart contract. What if the contract address does not have enough tokens? Will miners continue to verify this transaction?
Hope you can give me some help, thanks!


texts: How to find out the number of blocks in Ganache?

texts:
I have tested a contract on truffle using the command:

 truffle test

I got following message:

D:\Funding4\contracts>truffle test Compiling .\contracts\Funding4.sol... Compiling .\contracts\Migrations.sol... Compiling .\test\Funding4Test.sol... Compiling truffle/Assert.sol... Compiling truffle/DeployedAddresses.sol...

  Funding4Test
    √ testSettingAnOwnerOfDeployedContract (169ms)

  1 passing (1s)

D:\Funding4\contracts>

After the execution, I checked Ganache, it shows me 8 blocks. I can't understand why it has 8 blocks. It has compiled 5 files. How its showing 8 blocks? It should show 5 blocks. Somebody please guide me.

I have attached the picture of Ganache.

Zulfi.


texts: "Cannot retrieve ENS addresses unless fully synced on main chain" message

texts:
I'm deploying a contract in the Ropsten tesnet and even it is deployed correctly (already checked tx in etherscan.io), I can't see it in my Mist Wallet. The command line after deploying the contract says:

"cannot retrieve ENS addresses unless fully synced on main chain"

What does that means? Sounds to me like I have to sync the real chain and not only testnet? I supposed that I wouldn't need to download main blockchain and just test net would be enough.


texts: I was following this guide for compiling my contracts How To: Compile a Solidity Smart Contract Using Node.js but "solc.compile(input, 1)" is not working anymore. I have problems understanding how to fix this...


texts: Is it possible to access an already deployed smart contract without using metamask?

texts: Suppose a user wants to access a contract on the blockchain hat was distributed by a company. Can it do this without the use of metamask? If so, how?


texts:
I'd like to help an organization accept Ethereum. However, they need a Bitpay-type service that sends them USD right away.

I know they can just manually sell on Coinbase daily/weekly, but they can't actually hold ETH at any point for various reasons so that seems to be out of the question.

Is there a service that lets you accept ETH and sends you USD?

An automatic-sell feature on an exchange might be sufficient, but doesn't seem possible with coinbase.


texts: Contract returns incorrect uint when it should fail

texts:
I have a simple contract that saves how many people payed, and, if you pay, you can see how many people payed. A simple idea to learn smart contracts.

The problem is that the return value doesn't change. When I first tried with a more complex contract, the method findHowManyPeoplePayed returned 3963877391197344453575983046348115674221700746820753546331534351508065746944 and now, this stripped down version returns 0. It shouldn't return such value. In fact, it should return an error because the address hasn't payed to have access to that information.

I payed with the stripped down version and it didn't update the value, it still returns 0.

Deploying the contract to ganache and running the tests works as expected.

This is my test contract:

pragma solidity ^0.4.19;

contract PayEther {
    mapping(address => bool) payedCustomer;
    uint64 private peopleThatPayed;
    address private owner;

    constructor(uint minimumAmount) public {
        owner = msg.sender;
        peopleThatPayed = 0;
    }

    function pay() payable public {
        require(msg.value > 0, "Address didn't send enough money.");
        payedCustomer[msg.sender] = true;
        peopleThatPayed++;
    }

    function findHowManyPeoplePayed() view public returns (uint64){
        require(payedCustomer[msg.sender], "Address never payed!");
        return peopleThatPayed;
    }
}

This is it's abi:

[
  {
    "constant": false,
    "inputs": [],
    "name": "pay",
    "outputs": [],
    "payable": true,
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "findHowManyPeoplePayed",
    "outputs": [
      {
        "name": "",
        "type": "uint64"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "name": "minimumAmount",
        "type": "uint256"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "constructor"
  }
]

I have this contract deployed to 0x6CD65D376104B404B74907029DAbd74B8736A06f in Rinkeby.

The original version used a simple uint but I decided to change it to uint64 to see if this helped in some way.

Am I missing something? Why isn't the contract working as intended? Why doesn't payContract.methods.findHowManyPeoplePayed().call() returns an error because the user hasn't payed?


texts: How to extract all event logs from the blockchain?

texts:
I'm trying to extract all event logs from the blockchain, this is how I called an Event in the smart contract.

function rateBook(uint id, uint rating, string comments) onlyMember {
    if (id > numBooks || rating < 1 || rating > 5) {
        throw;
    }
    Rate(id, msg.sender, rating, comments, now);
}

I fired Rate Event few times through test case then tried to fetch all logged events and wrote the test case like this  -

    it('should allow a member to rate multiple times', async function() {
        await lms.addBook("1984", "Orwell", "Classic Publishers", "image url", "description", "genre");
        let reviews = [
            {bookId: 1, rating: 5, comments: 'A must-read classic!'},
            {bookId: 1, rating: 4, comments: 'Great Book, I loved it'},
            {bookId: 1, rating: 3, comments: 'Decent book, not my types though'},
            {bookId: 1, rating: 2, comments: 'Hell No!, Boring book'},
        ]
        for (let i = 0; i <= 3; i++) {
            await lms.rateBook(reviews[i].bookId, reviews[i].rating, reviews[i].comments);
        }
        let rateEvent = lms.Rate({}, {fromBlock: 0, toBlock: 'latest'});
        let i = 0;
        rateEvent.watch(function(err, result) {
            rateEvent.stopWatching();
            if (!err) {
                assert.equal(reviews[i].bookId, result.args.bookId);
                assert.equal(reviews[i].rating, result.args.rating);
                assert.equal(reviews[i].comments, result.args.comments);
                assert.equal(result.args.reviewer, accounts[0]);
                i++;
            }
        });
    });

However, on Web3JS documentation, I found a function named - web3.eth.filter. I tried implementing using the filter but It did not work, then used the watch function as shown in the test case above. It works fine but I'm not sure if this is the correct way and it fetches all events logged or only those which are fired at the time of test case?

Please advise.


texts:
Lets suppose here are user A and smartcontract B and C.
A has no token but little ETH for gas, but B has enough tokens(Erc20).

A send TX to B
B send delegatecall to C
C receive tokens in B and give ownership to A

Is this logic possible? If not, how can I make it? Pls correct me.


texts:
How many concurrent RPC calls can a Geth client handle?

If it has a queue, is a sendTransaction counted against the concurrency limit until it's processed in a block? And are call transactions dropped from the queue as soon as Geth returns a value (so that Geth is not waiting for a whole block)?


texts: web3.eth.getBalance returns me the strange values ?

texts:
i am trying to get the balance of a wallet, the method is working but the returned result is a json object - { c:(2) [484895,26495000000000],e:19, s: 1}.

In which the value - 484895 corresponds to 48.4895 eth in account 1, value 26495000000000 cooresponds to 26.495 eth in account, my questionis why there is a big difference for the value in the array.  what is the semantics of e(19) and s(1).

the code is below

  getBalance (address) {
      return new Promise (function (resolve, reject) {
        web3.eth.getBalance(address, function (error, result) {
          if (error) {
            reject(error);
          } else {
            resolve(result);
            }
        })
      })
    }

   getBalance(account).then((result) => {
         console.log('getBalance',result);
         web3.utils.fromWei(result.c[0], 'ether')
    });


texts: How to get Pending Transactions of specific contract?

texts: Is there any way to get pending transactions of single contract instead of getting all pending transaction on node?