texts: Why does web3.getBalance sometimes return old value?

texts:
Can anyone please explain the following issue? I have a pretty simple code to fetch ETH balance using the web3 JS library. It's something like the following:

import Web3 form 'web3';

const web3 = new Web3(new Web3.providers.HttpProvider('https://api.myetherapi.com/eth'));
const batch = new web3.eth.BatchRequest();

batch.add(api.eth.getBalance.request('0x...', 'latest', (err, balance) => {
    if (err) {
        console.error(err);
    } else {
        console.log(web3.utils.fromWei(balance, 'ether');
    }
}));

...

batch.execute();

I call this code every N seconds, and it works fine most of the time. However, when some transaction changes the balance, a weird thing happens: getBalance may return either new balance or old one. I mean, one call will return a new value, the next call - old value, then new value again and so on.

Is there any kind of a workaround for this?


texts:
I am creating an NFT game and I want to create an airdrop for other token holders. I have the addresses of holders, it's more than 20 thousand addresses. Now my question is, how do I make the addresses eligible for the airdrop?
What I want to do is something like Uniswap did, you click on claim and it tells you if you have some airdrop or you don't. And if you do, you can claim it.
So in my contract, if you are eligible for the airdrop, you click on claim, then the token is minted and transferred to you, so all the gas is on you.
But my question is how do I tell the contract which address is eligible for the airdrop? What I have tried is that I created a
mapping(address => uint) private _airdrop;
and then a function
function registerAirdrop(address user, uint tokenId) public onlyOwner {
   _airdrop[user] = tokenId;
}

and then called the function 20 thousand times, for each address, but I quickly realized that this would not be either time or gas efficient. Is there a better way? How could I tell my smart contract which addresses are able to claim airdrop?


texts: Using the console of an Ethereum client, you can get the binary code of a contract placed on the blockchain. Does an online tool to get this binary code exist?


texts: How to Read Construction information?? (from blockchain develpment with go)

texts:
pragma solidity ^0.5.10;

contract Simple{

    uint256 data;
    string male;
    string name;
    string id;
    function getdata() view public returns(uint256) {
        return data;
    }

    function setdata (uint256 _data) public{
        data= _data;
    }

    function getinfo() view public returns(string memory, string memory, string memory) {
        return (id,male,name);
    }

    function setinfo (string memory _id, string memory _male, string memory _name) public{
        id= _id;
        male= _male;
        name= _name;
    }
}

this is my solidity file.. and I used abigen for compiling.
and deploying fine, write contract fine, but
reading has a problem. maybe, there is no error with one parameter in function, but if I use more than 1 parameter function doesn't work...

package main

import (
        "fmt"
        "log"

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

        simple "./contracts/sim" // for demo
)

func main() {
        client, err := ethclient.Dial("/home/paik/ethereum/test_data/geth.ipc")
        if err != nil {
                log.Fatal(err)
        }

        address := common.HexToAddress("0xfAD52Ee70d5d264F108834394a4A5EB7ECAaB303")
        instance, err := simple.NewSimple(address, client)
        if err != nil {
                log.Fatal(err)
        }

        data, err := instance.Getdata(nil)
        if err != nil {
                fmt.Println("ABC")
                log.Fatal(err)
        }

        fmt.Println(data) // "1.0"
}


texts:
I'm using oraclize in my contract.

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

When I go to verify and publish on etherscan I get this error

myc:4:1: ParserError: Source "github.com/oraclize/ethereum-api/oraclizeAPI.sol" not found: File import callback not supported
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"
^--------------------------------------------------------^

Any idea how too fix this?


texts:
I am having a heck of a time getting transactions to post on mainnet. The issue is not my wallet balance or gas related. A balance lookup on the same contract works correctly.. However, i cannot get this offlinesignedtransaction (raw transaction equivalent,)

I have tried all manners of passing various parameters, i have set the defaultGas/Price via the transaction manager and used the SendTransactionAsync() method with the overloads that do no require them. I have sent the method with the contract parameters individually (not in an object array as below). I double checked the nonce - it appears as 0. I tried both this and the andwaitforreceipt variant.

var contract = web3.Eth.GetContract(contractAbi,contractAddress);
var function = contract.GetFunction("transfer");
hash = await function.SendTransactionAsync(@from: accountAddress, gas: new HexBigInteger(60000),
       gasPrice: HexBigInteger(40), value: null, functionInput: new object[] {  recipient, Web3.Convert.ToWei(value) });

The contract is a standard ERC20 Token. Any insight as to why the transaction returns no errors, however infura does not broadcast? I used this very same code many times with a regular private geth node.

Edit: Ive also been trying to get some of the other RPC JSON APIs. If anyone is familiar, would you confirm this is the correct way to do it by sending the data payload way? I get an "underpriced error" from the etherscan api

        var contract = web3.Eth.GetContract(contractAbi, contractAddress);
        var function = contract.GetFunction("transfer");
        string fdata = function.GetData(new object[] { recipient, Web3.Convert.ToWei(value) });
        var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(accountAddress);

        var encoded = Web3.OfflineTransactionSigner.SignTransaction(privateKey: accountKey, to: contractAddress, amount: 0, nonce: txCount.Value, gasPrice: new BigInteger(70), gasLimit: new HexBigInteger(60000), data: fdata);
        encoded = "0x" + encoded;


texts: Can you extract bytesn from bytes in Solidity?

texts:
How would you create a Solidity function with the following signature?

function extract(bytes data) returns (bytes20 subdata)

Where subdata is a contiguous slice of data and data.length > 20.

This can be with or without inline assembly.


texts: The synchronization that has been working for about 12 hours has slowed from 2048 16ms to 2048 2~3 mins.  It has been telling me that my clock is off my seconds but I re-synced the clock just now. Any idea what caused the sudden jump in time for block sync?


texts: Lottery Winning number based on blockhash

texts:
After reading a lot of Info about this topic in this forum I am asking whether I can just use the formular
winningNumber = uint256(blockhash(block.number-1)) % 100;
e.g. 10 or 20 blocks after the betting period is finished. The "future" blockhash can not be known by anyone during the betting period right?
e.g. implementing in solidity could be similar to this?
require (block.number > (BettingEndBlock+20);


texts:
I have a following struct,

struct Funds {
uint amount;
address sender;
uint time;
}
Funds[] public fundArray;

function StructsDemo() public{
    fundArray.push(Funds(100,0xca35b7d915458ef540ade6068dfe2f44e8fa733c, 12345678910));
    fundArray.push(Funds(200,0xca35b7d915458ef540ade6068dfe2f44e8fa733c, 12345678910));
}
function getArray() public view returns(Funds[] array){
    return fundArray;
}

When I run getArray() function, it returns me following error:
error: Failed to decode output: Error: Unsupported or invalid type: tuple

I'm intending to print whole of the array, any suggestions will be appreciated.
Thanks


texts: Is it possible to create ICO crowdsale seamlessly accepting multiple assets?

texts:
Most of the ICO crowdsales accept ETH only.
Some accept BTC.
Very few accept other assets.

I was thinking about creating crowdsale that would accept as many assets as possible.

While creating, monitoring, securing wallet for each asset might not be practical, the ETH addresses by definition accept ERC20 tokens.

I was thinking about calling Bittrex API (most amount of assets supported) to check the current value of the token and use BTC as a baseline (1 BTC = 1000 tokens).

In that way I could provide 2 addresses only - BTC and ETH:

people who send BTC:

1000 tokens per BTC
send signed message containing ETH address to accept ERC20

people who send ETH / ERC20:

process monitoring the address / mempool
getting pricing data from API (maybe weighted average)

Then compile list of all contributors, create and transfer tokens accordingly.

Is that solution possible / reasonable / sensible at all?

transactions on blockchain.info and etherscan.io are visible by default anyway
signing message with ETH address using BTC private key does not expose any sensitive data
it allows people to send tokens with less friction (exchange, spread, gas)

For sake of simplicity in this question I assume ERC20 / ERC223 are treated the same. Newly craeted token is likely to be ERC223. Read more:

https://github.com/ethereum/EIPs/issues/223
ERC20 vs ERC223. List of differences


texts: Are addresses hashes of public keys, or are they compressed public keys?

texts:
I understand that in Bitcoin, addresses are hashed public keys. However, I've also heard that compressed public keys are just as short as hashes while maintaining their 1:1 relationship.

Does Ethereum use hashed public keys, or compressed public keys, for addresses?


texts: Why ERC20 tokens dont use external keyword in the transferFrom function

texts:
I just realized that "external" keyword in a function declaration will cost less gas than "public" even if it can be only called from outside the contract.

why not use that in the ERC20 token?

Indeed the token doesn't have to use its functions itself.


texts: How do I resolve "gas required exceeds allowance or always failing transaction" when trying to send ether?

texts:
This is the sample smart contract I am trying to run. All methods work, except, "payVendor" -  it fails with gas required exceeds allowance or always failing transaction . I have tried increasing the gas, but doesn't help.

contract vendorContract {

    uint public vendorID;
    uint public ownerID;
    uint256 public contractValue;
    string public contractDescription;
    string public contractStatus;
    string public paymentStatus;
    address public contractOwner;
    address public contractVendor;
    string constant newcon = "New";
    string constant wipcon =  "WIP";
    string constant reqcon  = "Requested";
    string constant shipcon = "Shipped";
    string constant endcon = "Completed";
    string constant err = "Error";

    modifier isOwner()
    {
        if (msg.sender != contractOwner) throw;
        _ ;
    }

    modifier isVendor()
   {
        if (msg.sender != contractVendor) throw;
        _ ;
    }

    function vendorContract(uint _vid, string _desc) public {
        vendorID = _vid;
        contractStatus="New";
        contractOwner=msg.sender;
        contractDescription= _desc;

    }

      function acceptContract(uint256 _cvalue, uint _vidd) public {
        if (vendorID !=  _vidd) {
            contractStatus = err;
            throw;
        }

        contractStatus=wipcon;
        contractValue = _cvalue;
        contractVendor = msg.sender;
        }

    function requestPayment() isVendor {
    paymentStatus=reqcon;
    contractStatus=shipcon;
    }

    function paymentStatus() returns (string) {
    return paymentStatus;
    }

    function payVendor() payable isOwner {
     if  (!contractVendor.send(contractValue))
        throw;
    //contractVendor.send(contractValue);
    contractStatus = endcon;

    }

   }


texts: Contract Function calling storage contract not setting value correctly

texts:
so i have a storage Contract A which has the following mapping and function.

mapping (address => mapping (bytes32 => uint8)) addressToQueryIDToStatus; // 0=no init, 1=init, 2=fail, 3=succeed, auth written, 4=retrieved.
mapping (bytes32 => address) queryIDToAddress; //

function requestAuthorization(bytes32 _queryID, address _sender)
public restricted(msg.sender)
{
    require(_sender != address(0x0));
    require(_queryID[0] != 0);
    addressToQueryIDToStatus[_sender][_queryID] = 1;
    queryIDToAddress[_queryID] = _sender;
    emit LogStorageEventRequestAuthorization("requestAuthorization", _queryID, _sender);
}

which works fine by it self it testing.

I have a second contract B that calls contract A through an interface function below. (i have several of these functions working correctly, but this one has me stumped)

    function requestAuthorization(bytes32 _queryID, address _sender) external;

calling function:

function requestAuthorization(bytes32 _level, string _input)
public whenNotPaused //IDContractOnly(msg.sender)
returns(bytes32)
{
    //require(_level.length > 0, "A");
    //require(bytes(_input).length > 0,"B");
    bytes32 queryId = "1";
   CoinIDStorageInterface(coinIDStorageAddress).requestAuthorization(queryId, msg.sender);
    emit LogNewOraclizeQuery2("Oraclize query with was sent, standing by for the answer for input.. ", msg.sender, queryId, _level, _input);
    return (queryId);
}

with the following test code:

    // this works
    //await coinIDStorageContract.requestAuthorization("1", accounts[1], {from: fromOwner});
    // this doesn't seem to get to storage.
    console.log("Request Auth CoinIDBankContract");
    await coinIDBankContract.requestAuthorization("1", "2085551212", {from: accounts[1]});

    //console.log(returnedQueryID);
    let queryStateCheck = await coinIDStorageContract.requestAuthorizationState("1", accounts[1], {from: fromOwner});
    console.log("CoinIDStorage AuthState: " + queryStateCheck.toNumber());
    //console.log(queryStateCheck)
    let queryState2 = await coinIDBankContract.requestAuthorizationState("1", accounts[1], {from: accounts[1]});

    console.log("CoinIDBank AuthState: " + queryState2);
    assert.equal (queryState2.toNumber(), "1",  "Bank Request of Query State incorrect, should be 1");

with the following results:

CoinIDStorage AuthState: 0
CoinIDBank QueryState: 0
1) CoinIDBank: Auth Request

Events emitted during test:
---------------------------

LogStorageEventRequestAuthorization(functionName: requestAuthorization, _queryID: 0x3100000000000000000000000000000000000000000000000000000000000000, _sender: 0x839c18df17236382f8832d9ab5ef3facafbac891)
LogNewOraclizeQuery2(description: Oraclize query with was sent, standing by for the answer for input.. , _sender: 0x839c18df17236382f8832d9ab5ef3facafbac891, queryId: 0x3100000000000000000000000000000000000000000000000000000000000000, level: 0x1000000000000000000000000000000000000000000000000000000000000000, input: 2085551212)

So it looks like i have the right values passing, don't get any errors or reverts, and the emits have the right values, HOWEVER, when i check the value, which now should be 1, all i get is the un-itialized 0 state back.  If i use the first commented out command, it definitely gets set, and returns the state of 1 which is the intended effect.

Probably something small, but i just don't see it.

this function sets the same value and works in both cases.

    await coinIDStorageContract.returnAuthorizationFail("1", {from: fromOwner});
    await coinIDBankContract.returnAuthorizationFail("1", {from: fromOwner});

returning-

CoinIDStorage AuthState: 2
CoinIDBank AuthState: 2

which is correct... still can't see the hangup...


texts: How to properly close web3 after execution? - Java

texts:
Here is what I am trying to do:
String amt = Web3j.build(new HttpService("https://ropsten.infura.io/v3/123blahblah"))
.ethGetBalance("0xblahblah", DefaultBlockParameterName.LATEST)
.send().getBalance().toString();

System.out.println(amt);

It prints the balance in wei nicely. However, the Web3 does not close and the application simply hangs. I am afraid that this would be a memory overflow if not managed properly and if too many calls are made. Also, this could lead to a potential security issue on the backend. So, the question is, how do I close the web3 as soon as I get the balance data I need ?
I've tried web3.shutdown() but it doesn't do anything.
Edit: I've noticed that there is a timeout and that it closes after several minutes.  Still, I need to close it immediately after getting the data.
Edit2: This is obviously due to OkHttpClient. Related question/answer
https://stackoverflow.com/questions/29055724/okhttpclient-close-connection


texts: Solidity Smart Contract auto withdrawal (ETH)

texts:
I'm kinda new to smart contracts, searched a lot, but hope someone here can help me out.

I'll try to explain as good as I can. I'm mining Ethereum with a couple of rigs.

Each individual rig auto-sends the ETH to a specific ETH address via pool. So now I have multiple (30+) ETH addresses that are receiving ETH. Very frustrating to check every address and send the ETH to my main account by hand.

Is there a way that I can auto-send ETH from each account to my MAIN account with a smart contract (solidity)?

Let's say; Address 1 receives 0.1 ETH, auto send (immediately after transaction comes in) 0.1 ETH to MAIN ETH address.

The addresses are receiving different amounts of ETH, some 0.1 ETH some 0.05 ETH, etc. No matter what amount is send to the mining address, it must be transferred to the main account.

I hope someone can help me out with this.

Edit: Example

0x0000ADRESS1: 0.1ETH

0x0000ADRESS2: 0.3ETH

0x0000ADRESS3: 0.2ETH

0x0000ADRESS4: 0.1ETH

(Write an smart contract for each address above, when ETH is in above addresses, transfer ETH to MAIN)

0x0000MAINADRESS: 0.7ETH


texts: Ethereum Wallet starts up really slow and loses previously created contracts - private.net

texts:
I created a private test chain using geth:v1.6.6 and Wallet:0.9.0.1884

I used the link for Ethereum-Wallet-win64-0-9-0.zip

versions 0.8.5 and earlier open in at most 20 seconds where as this version takes around 5 minutes to open.

2-3 mins with Loading client config...
2-3 mins with Downloading new
node

I don't see anything specific in fiddler so it looks like its doing nothing or failing at whatever its trying to do and timing out.

Additionally, after I deploy a contract/token, if I restart nothing remains.

Thanks for the help.


texts: I installed Geth on Ubuntu via PPA, what is the command to start it?

texts: I followed the guide for installing Geth on Ubuntu via PPA. I usually use windows so I apologise if this is a dumb question. How do I start the geth client?


texts:
I am very new to developing smart contracts. I have a simple question, do i need to write migration file separately for each contract i deploy from an account using truffle or can i deploy multiple contracts using a single migration file. How to write such file?

Any help please.


texts: Recording Event Logs in a DB from a Smart-Contract

texts:
I have created a smart-contract and deployed to the Rinkeby Network, it has a client-side application which has been established with React. Now, I would like to observe and audit every transaction or callback happens in my smart-contract and I need to record these events whenever it happens. In other words, I need to track the transaction near-real-time and record the logs to my SQL or InfluxDB directly.
Would you please show me a way how to do that.
Thank you.


texts:
I am looking for a free api to get ETHEREUM CRYPTO CURRENCY PRICE.
Entire yesterday i was searching google & test many web sites.
But result was zero for ethereum price.
Here is what i tried :
1.
https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD,EUR
It seems this api has 100,000 calls limitation in one month or has other limitations.
2.
https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd
It has id error many times
3.
https://developers.coinbase.com/docs/wallet/guides/price-data
Only has bitcoin price

I am so confused for fetch ETHEREUM PRICE.
What is your suggestion?


texts:
If this was a calculation or something i'd do myNumber * 5 and out of the contract (on client side) i'd do myNumber / 100 but since solidity doesn't accept decimals i can't do this.
so my question is how can i transfer 5% of the contract balance?
thanks


texts: How to disable one owner-only contract function without disabling others?

texts:
I have deployed a smart contract with several functions that only one address (called the 'owner') is allowed to call. The transaction will revert if any other address tries to call one of them.
Is there a way to make it impossible for the owner (or anyone else) to call some of these functions while maintaining the ability for the owner to call the other functions?
The contract has a transferOwnership(address _newOwner) function with which the owner can set a different address as owner.


texts: Storing use login details for an Ethereum app

texts:
I have an idea for a dApp using Ethereum that would require user registration and a login system. Once logged in, the user will trigger transactions and smart contract part will come in. However, I am confused if I should I be storing the user details in a central database or in the blockchain? From what I've studied so far it seems using the blockchain as a replacement for database isn't the right way to think about it and data storage can also get very expensive.

I'm quite new to dApp/Ethereum so a lot of these concepts are still muddy to me, so any help would be appreciated.


texts:
Is it possible to stop miners in mix-ide and only run them when debugging or running contracts?

The default setting makes use of 4 addresses (accounts) out of which one is a miner. The issue is that the miner is multithreaded and takes up all available CPUs making the machine very slow.


texts: according to this link about etherdice, the game needs both players provide a seed and combine them together as the input of a RNG(random number generator) to generate the dice number, but one problem is that the second player to upload the seed can have the ability to manipulate the output(I mean if the player knows about the RNG aogorithm, then he can search the seed space to find the one that benefit him), then how does the etherdice fix this problem?


texts: Is it possible to change the network id in GETH once geth is initialized?

texts:
I want to change the network_id of my private ethereum network setup with geth. It seems like I have to change it in genesis.json file and  also have that id when I start geth.
But, to apply the change made in genesis.json I have to again do geth init and this will now start behaving as fresh network and I will loose my blocks. So is there any other way to change network_id?


texts: Best way of accepting ERC20 tokens in my service

texts:
I need to allow users to deposit and extract ERC20 tokens in my service, and I'm wondering what's the best way of implementing that. My idea is to generate an account for each user, and when a user deposits, have that deposit forwarded to a main account with consolidated balances. When a user needs to withdraw, the amount is sent from the main account.

Is this the best approach to store ERC20 tokens?
How can I detect user deposits without calling the token contract
    (i.e. without spending gas)? I don't mind scanning the blockchain to see if there are deposits, however I'm not sure how I can detect them.

Thanks


texts: Error when running Truffle Test in Terminal

texts:
I am trying to use truffle to test my smart contracts and have written some test files. I am getting an error on the terminal trying to run the test and am unsure what the reason is.

I access my directory via terminal and then write:

truffle compile
truffle develop
migrate
deploy

So far everything runs fine. Then when I type truffle test it returns this error:

SyntaxError: Unexpected identifier
    at REPLServer.Interface._onLine (readline.js:280:10)
    at REPLServer.emit (events.js:211:7)
    at emitOne (events.js:116:13)
    at REPLServer.onLine (repl.js:468:10)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at bound (domain.js:301:14)
    at ReplManager.interpret (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-core/lib/repl.js:119:1)
    at Console.interpret (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-core/lib/console.js:164:1)
    at Object.runInContext (vm.js:119:10)
    at createScript (vm.js:80:10)

This also happens when I try to run truffle test followed by the address of the directory the test file I want to use is saved in.

Does anybody know what the problem might be?
The only solutions I found for similar problems talked about it being a Windows problem. I am using a Mac though so can't apply these solutions.

Thanks!


texts: Added EOS to MyEtherWwallet as default token

texts: I've added EOS to MyEtherWallet as default token. How do I correct this? It tells me to load tokens but it isn't in the list. The contract is fine and tokens are present, just elusive and misnamed.


texts:
I am very shocked. After a crash on my computer, I lost my Seed Words file to access my MetaMask account. However, I found a Keystore file (UTC or json file), but when I import it into MetaMask I can not find my Ethereum. I'll get another ETH adress and there is no ETH in my wallet.. How is this possible? And how do I get back into my old account without Seed Words, but with UTC keystore file? If this succeeds, it will make me very happy!

Kind regards,

Koen


texts: Exceptions when compiling a contract using Solidity version 0.6.0 on Remix

texts:
I've been trying to compile contracts using the current newest version of Solidity on Remix which is 0.6.0. However when I compile the following code

//pragma solidity ^0.6.0;
pragma solidity ^0.5.15;
import "Token.sol";

contract TokenTimeSol{
    Token public token;
    address public beneficiary;
    uint public releaseTime;

    constructor(Token _token, address _beneficiary, uint _releaseTime) public{
        require(_releaseTime >= block.timestamp);
        token = _token;
        beneficiary = _beneficiary;
        releaseTime = _releaseTime;
    }

    function releaseTokens() public{
        require(block.timestamp >= releaseTime);
        uint _amount = token.balanceOf(address(this));
        require(_amount > 0);
        token.transfer(beneficiary, _amount);
    }
}

using v0.6.0, I get the following error on hitting compile.

Uncaught JavaScript exception:
TypeError: soljson.Pointer_stringify is not a function

And when I hit compile again without changing anything, I get the following error in place of the one mentioned above.

Internal exception in StandardCompiler::compile: /root/project/libsolidity/interface/CompilerStack.cpp(90): Throw in function dev::solidity::CompilerStack::CompilerStack(const ReadCallback::Callback &)
Dynamic exception type: boost::wrapexcept<langutil::InternalCompilerError>
std::exception::what: You shall not have another CompilerStack aside me.
[dev::tag_comment*] = You shall not have another CompilerStack aside me.

This error message persists for all other contracts.

The contracts work fine with older versions of Solidity.
But I've been getting the above error recently on compilation.
I've just started with solidity and am curious to know the issue.

Thanks in advance.


texts: Why can't I use a contract method in my Chrome console?

texts:
I am attempting to call a method from a smart contract from my chrome console. My dApps index.html file is deployed locally at http://127.0.0.1:5500.

I set up web3 and instantiate a smart contract with the following code:

window.addEventListener('load', async () => {
    if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
        console.log('metamask success');
        await window.ethereum.enable();
        web3.eth.defaultAccount = web3.eth.accounts.givenProvider.selectedAddress;

    } else { // I removed this code for brevity

abi = [ { constant: false, ... // I removed the full abi for conciseness

MyContract = web3.eth.contract(abi);

contractInstance = MyContract.at("0xd01e06f2e70bea9ae7640367bdf0b24ac5f35ed1");

I can successfully make the following transaction from my console in Google Chrome:

web3.eth.sendTransaction({value: web3.utils.toWei('.1'), to: "0x493b6DEb52B40A517Fa64f580B5bfd325537764E"}, (e,r) =>{console.log(e,r)})

But when I try an make the following transaction:

contractInstance.notarize(item, (e,r) => {console.log(e,r)})

I get the following error message in my Chrome console:

Uncaught TypeError: Cannot read property 'match' of undefined

Any ideas on what is going on here?


texts:
I'm trying to find a way to use an ethereum address/solidity/web3 for text encryption , but i'm not even sure it's possible to get the public key from the address(hash of the pubkey) using secp256k1 to get the publickey ? or if there is any other way to access it client side? if so, would the user be able to decrypt the data using it's passphrase(ethereum passphrase )? so that everything would happen client side but the data would be stored encrypted on the chain ?

I know none of this is really meant to do any of that but i'm trying to store encrypted data on the blockchain without having to rely on a server to store keys as much as possible but can't seems to find a way.

tldr:

Ethereum + data = encrypted data

encrypted data + ethereum + passphrase = data


texts: how do miner select which transactions to validate?

texts:
i can't understand how the miners choose the transactions for example in this picture, the two first transactions have the same gas price why he didn't pick the second one first?
does each miner have his own select mechanism (priority, gas price , gas limit, account,..)?
what i can do if i want the second transaction to be validate first? do i have to raise the gas price or the gas limit?


texts: How to read uint256[] array from a method in a smart contract?

texts:
I'm using this function in my smart contract. It returns an uint256[] array containing the tokens that the user owns.

 /**
   * @dev Returns all of the tokens that the user owns
   * @return An array of token indices
   */
  function myTokens()
    external
    view
    returns (
      uint256[]
    )
  {
    return ownedTokens[msg.sender];
  }

In my web3 js console log, I get the below.

How do I read that array in my js code? Honestly, I don't understand the entire array. I just want to get the token IDs, which it supposed to return.

I'm expecting something like below as shown in Remix.

Here's my web3 js code.

async function retrieveTokenId(contract, walletAddress) {

  await contract.methods.myTokens().call(function(err, res){
        if(!err){
            console.log(res);
        } else {
            console.log(err);
        }
    });

}


texts: What happens when the owner kills a multisig wallet?

texts:
if the owner decide to kill a multisig wallet (Smart Contract),

Is he/she will be able to do kill the contract?
If so where does the ether get deposited to?


texts: Why did this transaction not win? Same block, higher gas?

texts:
I'm trying to understand why this transaction failed, even though it's in the same block as this other transaction, both trying to do the same trade and this one has higher gas than the other - yet the other still won?

Is it because the failed one may have some errors in the input data? I did notice the successful one has a little note saying "(Also found 1 other dropped Txn #1 with the same from account nonce)", would it have anything to do with that?

Failed tx:

Successful tx:


texts: What is the reason for writing truffle tests in .sol and .js files?

texts:
What is the reason that tests can be written in both? Is there any distinct advantage to using one over the other?

Or is one in general easy to work with?


texts: Is it possible to verify a given `block hash` is valid in a contract?

texts:
Inside my contract, I want to verify a given block hash is valid or not.

block_hash_validation(string blockhash) returns (bool){
   ...//check()
   return true; || return false;
}

Q1: If yes, from block hash value could I also learn its block number?

Q2: Or should I provide block number as well block_hash_validation(uint blockNumber, string blockhash) to see that does the block number points to the correct block hash?

block_hash_validation(uint blockNumber, string blockhash) returns (bool){
   if(block.blockhash(blockNumber) == blockhash)
       return true;
   else
       return false;
}

Thank you for your valuable time and help.


texts: Any way I can see what information a specific peer is sending (or exchanging ) to my node in geth?

texts:
I'm trying to run some demo script at devp2p protocol in ethereumjs (https://github.com/ethereumjs/ethereumjs-devp2p/blob/master/examples/peer-communication.ts),
but this example is running in ethereumjs,it seems to me that the code opens another p2p protocol  with different peers ,bootstrapNodes.I was unable to use it to interact with my peers in geth(or there is a way that I m  not aware of ?),so how can I get some information from a peer that connecting in geth? like how many tx my node have exchanged for last 10 min from specific peer in geth?


texts:
What is the difference between Memory and Storage ?

From both the EVM point of view and the contract design one.

Thanks!


texts:
Imagine you have a function like this:

function compute(uint256 a, uint256 b) external pure returns (uint256) {
  return a % b;
}

Does it revert when b is 0?


texts:
I am new to Ethereum. I have the v.0.8.7 client. It is fully synchronized with the blockchain (see screenshot below: last block seen a minute ago).

I am basing myself on this post.

If I understood correctly, my Client is currently synchronised with Morden (the article really does not explain things in a noob-understanable manner). So I have to swich to Ropsten.

I entered the commands specified at the bottom of the article, and get the following error.

dyn907-72:~ me$ ls  /Users/me/Library/Ethereum/testnet/
chaindata       keystore        testnet_genesis.json
dapp            nodekey
geth            nodes
dyn907-72:~ me$ geth --datadir /Users/me/Library/Ethereum/testnet init testnet_genesis.json
I1122 14:01:12.203789 ethdb/database.go:83] Alloted 16MB cache and 16 file handles to /Users/me/Library/Ethereum/testnet/chaindata
Fatal: failed to read genesis file: open testnet_genesis.json: no such file or directory
dyn907-72:~ me$

Why does it say "no such file exists" please? I m new to geth, needless to say.
Thank you.


texts: Require instead of if for input validation

texts: Why is it preferred to use require instead of if for input validation/checks of functions?


texts: What are the two arguments to a RETURN opcode?

texts:
The RETURN opcode in the EVM takes 2 arguments(ie, consumes two elements from the stack), but what do they represent? I tried to understand the yellow paper describing them, but I don't understand the notation used.

For reference this is the section in the yellow paper:


texts:
I have a private PoA network with 3 geth nodes, i connect them using addPeer and create p2p network, each node is connected with the rest of them

Now i want to create a bigger network, with 20 nodes, so i need to connect to the geth console and invoke the addPeer 20 x 20 = 400 times ..

obviously this is unstable.

I know there is an option to do this automatically, connecting the nodes to discovery/bootnodes, but i cant use a bootnode. Why? because bootnodes dont filter connections from the outside, so any hacker/malicious user could try to connect to my bootnode.

See this related issue: https://github.com/ethereum/go-ethereum/issues/16057

So, what i have in mind to research is:

Maybe i can create a bash script that connects to geth console and executes the addPeer too many times as nodes present but i want to know if there is any better approach
Maybe there is a way to add firewall rules to the bootnode , something like "only allow connections to the bootnode from the IPs of the 20 geth nodes". I dont know if this is possible without affecting the discovery protocol

Any thoughts about this scenario?


texts: Quorum - Unable to read state of one public contract from another

texts:
I'm running the 7nodes example of quorum from truffle and the example functionalities work as expected. However, when I create a public contract to access the state of another public contract, I'm getting a 0 return value even when that is not the case. Strangely, the contract is able to set the state of the callee contract. I have added the details below. Can someone please tell what I'm doing wrong over here?

geth version: 1.7.2-stable
 truffle version: v4.1.7
 solc-js version: v0.4.23

Public Contract 1:

pragma solidity ^0.4.17;

contract PublicStorage {
  uint public storedData;

  function PublicStorage(uint initVal) public {
    storedData = initVal;
  }

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

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

Public Contract 2:

pragma solidity ^0.4.17;

import './PublicStorage.sol';

contract PubStorageReader {
  uint public storedData;
  PublicStorage publicStorage;

  function PubStorageReader(uint initVal, address publStorageAddr) public {
    storedData = initVal;
    publicStorage = PublicStorage(publStorageAddr);
  }

  function setPublic(uint x) public {
    publicStorage.set(x);
  }

  function getPublic() constant public returns (uint publicRetVal) {
    return publicStorage.get();
  }
}

Deploy script:

deployer.deploy(PublicStorage, 102)
        .then(function() {
            return deployer.deploy(PubStorageReader, 202, PublicStorage.address);
        });

Invocation:

> PublicStorage.deployed().then(function(instance) { return instance.get(); })
{ [String: '102'] s: 1, e: 2, c: [ 102 ] }

> PubStorageReader.deployed().then(function(instance) { return instance.getPublic(); })
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }

> PubStorageReader.deployed().then(function(instance) { return instance.setPublic(2); })
{ ... }

> PublicStorage.deployed().then(function(instance) { return instance.get(); })
{ [String: '2'] s: 1, e: 0, c: [ 2 ] }

Now running the same code on testrpc reads the state as expected. What is the mistake in this?


texts:
Using React js i am trying to create a wallet

I want to implement few functionalities
1) display balances of all the accounts
2) Display tokens by providing smart contract address

how can i implement this wallet functionality using reactjs??


texts: geth - admin,addPeer() and static-nodes.json don't work

texts:
I'm trying to connect two nodes (both miners) on my private network.

They are based on the same VM in different data directories. They have different ports and are based on the same genesis file and network ID.

The problem is I can't get them to sync and I think the reason is they still can't find each other.

I have tried to use both admin.addPeer() inside a console or using static-nodes.json, but when I checked with admin.peers it still came back with an empty array.

Did anybody else have this problem before?


texts: Send erc20 tokens using the json-rpc api

texts:
I need to send ERC20 tokens (golem to be precise) in an automated manner, so I set up a geth json-rpc server with

./geth --fast --rpc

So I can call the api just fine.

The documentation for eth_sendtransaction makes it easy to send ethereum to another address, but I couldn't find how to send ERC20 tokens. I saw the data field which allowed to trigger a smart contracts. So I suppose I need to trigger a function within the smart contract of the ERC20 token but since I would need to learn solidity and read through the whole golem smart contract I thought I'd ask here first.

Thanks !


texts: How do I recover it? Am I SOL (sh*t out of luck)? I could have sworn it was the same as before. I've made 5 wallets all with the same password and for some reason, this isn't working.


texts:
I'm attempting to install web3 for node on ubuntu but it seems there is an issue with the url within the installation script.

osboxes@osboxes:~$ npm -v

5.0.3

osboxes@osboxes:~$ node -v

v8.1.0

osboxes@osboxes:~$ npm install web3

npm ERR! exited with error code: 128

npm ERR! A complete log of this run can be found in:

npm ERR!     /home/osboxes/.npm/_logs/2017-06-24T02_20_54_548Z-debug.log

osboxes@osboxes:~$

Inside the log is the following:

26 silly resolveWithNewModule xmlhttprequest@1.8.0 checking installable status
27 silly fetchPackageMetaData error for bignumber.js@git+https://github.com/debris/bignumber.js.git#94d7146671b9719e00a09c29b01a691bc85048c2 exited with error code: 128
28 verbose stack Error: exited with error code: 128
28 verbose stack     at ChildProcess.onexit (/opt/node/lib/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/index.js:39:36)
28 verbose stack     at emitTwo (events.js:125:13)
28 verbose stack     at ChildProcess.emit (events.js:213:7)
28 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12)


texts: Explanation of Geth's Command Line option: targetgaslimit?

texts:
I have been trying to figure out what the targetgaslimit parameter does exactly for Geth, in the context of Private Blockchains.

I have seen the following explanation but it never helped me:
"Target gas limit sets the artificial target gas floor for the blocks to mine (default: 4712388)".

Could someone provide another explanation please?  I've searched but couldn't find any good ones online?


texts: How can i safely unlock an account and send transactions from a web application server using web3js?

texts:
I need a web application backend to be able to make transactions to a smart contract. In order to do this i need to send a transaction on behalf of an account that is authorized by our smart contract. How can i generate these transactions securely?

I read somewhere that using web3.personal.unlockAccount is not a safe approach because it exposes the password when communicating with the node. Is this true? And if so, what is the better approach?


texts: How to do Ethash CPU mine using ethminer?

texts:
I have a Private Ethereum Network. I just want to do Ethash CPU mining using ethminer. I know that to have a smaller foot-print it is recommended to use GPU or openCL but for private networks, I only have few nodes on the network and all are CPU nodes. I just want my CPU node able to mine.

For small private networks, I believe mining with CPU nodes, where all nodes are also CPU nodes in the network, will be no problem.

With the current model, if we have a Parity node there is no way for us to mine using a CPU node. And I am not sure why Parity forces users to mine with only GPU node. Since I do not have any GPU machine on my small private network, I am unable to use Parity node to do mining, it forces me to switch to geth node to do mining.

I have followed https://github.com/ethereum/cpp-ethereum .

Install:

git clone --recursive https://github.com/ethereum/cpp-ethereum.git
cd cpp-ethereum

Build:

cmake -H. -Bbuild
cmake --build build

After the build; ethminer used to exist under build folder on older versions git-tag:(untagged-1d50efdb2f43825a1810).

After I build, ethminer does not exist under build. So I was not able to find ethminer binary.

[$]~/cpp-ethereum/build$ ls
_3rdParty            deps     libdevcore     libethereum     libwhisper
CMakeCache.txt       eth      libdevcrypto   libevm          Makefile
CMakeFiles           ethkey   libethash      libp2p          rlp
cmake_install.cmake  ethvm    libethashseal  libweb3jsonrpc  test
CTestTestfile.cmake  include  libethcore     libwebthree     utils

So I have followed https://github.com/ethereum-mining/ethminer to install ethminer.

This line to work for CPU mining: ./ethminer -F http://localhost:8545

The error I am facing with the current/latest ethminer:

./ethminer
  ✘  11:20:06|ethminer  No OpenCL platforms found

[Q] Is there any way to prevent this error and force ethminer to mine on CPU platform? I guess we have find an older ethminer client that accepts -C/CPU flag.

I have also tried: Genoil/cpp-ethereum and it says.

./ethminer
CPU mining is no longer supported in this miner. Use -G (opencl) or -U (cuda) flag to select GPU platform.

Thank you for your valuable time and help.

Note: Two bounties did not return any answer. I opened an issue under github's ethereum-mining/ethminer hoping it will reach someone. You can follow from https://github.com/ethereum-mining/ethminer/issues/382.


texts: Skipping blocks when using testing with Mocha on Truffle and testrpc?

texts: I have a contract that requires that things only happen at certain block numbers. I was wondering if there was a way to "skip" a set number of blocks?


texts: How to add new EIP and how are they numbered?

texts: Hi I have a question to community. How do I add a new EIP? Also, how are the EIP numbers allocated?


texts:
I installed remix-ide.

It is able to compile contracts. So it somehow calls Solidity compiler. Where is this compiler located in the filesystem and how to use it without remix-ide?


texts: Ethereum transaction events listener with AWS lambda

texts:
We are using ERC20 tokens in our application for our transactions. We are having a hard time as to how to keep track of pending transactions and users token balance. Ideally, we want to notify user as soon as the transaction is confirmed on the blockchain. For this, we tried using web3 WebSockets but we noticed that after few hours of running servers, some contract events missed out and users didnt get any confirmation notification.
Can anyone guide on this as how to effectively listen for contract events or pending transactions especially in a production environment?
Very recently I have been thinking of using AWS lambda with cloud watch for listening events but couldn't get any help on this.


texts:
I was doing a full sync with geth 1.9.22-stable. The sync is paused and the blocks are stuck at sometime on April 15th.
The log contains the following lines:
10:30:13.672838 table@compaction L0·173200 -> L1·0 S·310GiB Q·6256306088
10:32:51.016826 table@build created L1@8435513 N·8993 S·2MiB "AHn..\xb5\x00\xcf,v2773956155":"AH\x9f..\xdc\xda\x1d,v3729431318"

This is followed by thousands of "... table@build created ...". It has been running for 25hrs now - how long should this take? Any way to gauge progress?


texts:
how do you reference your own contract address in vyper, for example in solidity you would do something like that:

address(this)

Is there a way to do the same in vyper? Thanks.


texts: Deployment of Blockchain Dapp application on cloud!

texts: I have my dapp in progress using PrivateNet, Metamask, HTML, CSS, JAVASCRIPT & Solidity in Ethereum. After the finishing of my application I just wanted to host my application on cloud. As of now when I searched for the deployment, I didn't get such blockchain environment like Heroku . Can any one suggest the ennvironment for hosting?


texts: Transactions stuck in pending state on a geth node

texts:
I have a private network of a geth and a few parity nodes. I use the geth node to submit transactions via RPC. A mining pool runs on one of the parity nodes. That node is connected to the geth node using the --reserved-peers flag.

I'm sending identical transactions in batches of 300. The first few batches were processed, but then about 1000 transactions stuck in the pending state. The mining pool continued generating empty blocks, the geth node indicated that it was connected to the other nodes, but the transactions were there for a few days. BTW I checked the nonce -- the sequence was OK.

> txpool.status
{
  pending: 1115,
  queued: 0
}

Today I restarted the geth node, and a portion of the pending transactions (2 blocks) was mined right away. And now nothing again. There is this suspicious message:

WARN [01-14|10:30:16.650] Synchronisation failed, dropping peer    peer=8aae420436ab0d4c err="action from bad peer ignored"

But running admin.peers tells me that the node with the mining pool is still connected (it has a different ID).

How do I make the geth node submit all pending transactions without having to restart it all the time?


texts:
I am creating a frontend app based on Truffle + Webpack, following this tuto : http://truffleframework.com/tutorials/building-testing-frontend-app-truffle-3, and have no uderstanding of JavaScript at all.

The code works on truffle console and the app globally works, except for the function "append_buy_brent", adding a new element to a struct array called buy_orderbook_brent

Solidity :

contract Petroleum{

// Initialisations

address _creator;
uint user_number;

struct Baril_order {
    uint price;
    uint quantity;
    address addr;
}

Baril_order[] buy_orderbook_brent;

mapping(address => uint) account_map;
mapping(uint => uint) user_balance;
mapping(uint => uint) number_of_brent;

function Petroleum() payable{

    _creator=msg.sender;
    user_number=0;
    test=0;

    account_map[_creator]=0;
    account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]=1;

    user_balance[account_map[msg.sender]]=100000;
    number_of_brent[account_map[msg.sender]]=5;
    number_of_wti[account_map[msg.sender]]=2;
    debt[account_map[msg.sender]]=20;
    user_balance[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=200000;
    number_of_brent[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=7;
    number_of_wti[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=10;
    debt[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=3;
}

function append_buy_brent(uint price, uint quantity, address addr) payable {
        buy_orderbook_brent.push(
            Baril_order({
                price:price,
                quantity: quantity,
                addr: addr,
            })
        );
    }
}

JavaScript :

import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import Petroleum_artifacts from '../../build/contracts/Petroleum.json'
var Petroleum = contract(Petroleum_artifacts);

var accounts;
var account;
var account1;

window.App = {
start: function() {
    var self = this;

    Petroleum.setProvider(web3.currentProvider);

    web3.eth.getAccounts(function(err, accs) {
      if (err != null) {
        alert("There was an error fetching your accounts.");
        return;
      }

      if (accs.length == 0) {
        alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
        return;
      }

      accounts = accs;
      account = accounts[0];
      account1 = accounts[1];

      self.refreshBalance1();
      self.refreshBalance2();
    });
  },

append_buy_brent: function(){
        var self = this;

        var price_buy_brent= parseInt(document.getElementById("price_buy_brent").value);
        var quantity_buy_brent=parseInt(document.getElementById("quantity_buy_brent").value);

        this.setStatus("Initiating transaction... (please wait)");

        var petro;

        Petroleum.deployed().then(function(instance) {
          petro = instance;
          return petro.append_buy_brent(price_buy_brent,quantity_buy_brent, account, {from: account, value: web3.toWei(1000, "ether")});
        }).then(function(value) {
            self.setStatus("Transaction complete!");
            self.refreshBalance1();
            self.refreshBalance2();
        }).catch(function(e) {
          console.log(e);
          self.setStatus("Error placing buy_brent; see log.");
        });
     },
}

Log :

  Error: VM Exception while processing transaction: invalid JUMP at
  d8abbe98e23bfa2cd66729f537c8dd23bb72c25425af350243627a30533c3b73/a8c9aca1a9b5fd638a6aa025545e1274787f3456:790

I hope I gave enough information, first time here.
Thanks a lot.


texts: Connecting to an ethereum node from meteor server side

texts:
I get the error TypeError: XMLHttpRequest is not a function when I try to connect to a node on the server side of my meteor application.

The error is caused by meteor using the meteor HTTP package instead of XMLHttpRequest. From this question.

How else can a meteor app connect to an ethereum node from the server side?


texts: Getting CompileError raised on OpenZeppelin Utils code, when trying to migrate a simple ERC20 contract

texts:
CompileError: @openzeppelin/contracts/utils/Address.sol:56:42: ParserError: Expected ';' but got '{'        (bool success, ) = recipient.call{ value: amount }("");
Disclaimer: Learning how to use ERC20 OpenZeppelin code, pardon the elementary question, am a student.
Am using pragma solidity >=0.6.1
Here is the OpenZeppelin code
function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

And here is the code am migrating
pragma solidity >=0.6.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) public ERC20("RainToken", "Rain") {
        _mint(msg.sender, initialSupply);
    }
}

                             ^


texts: Why do some tokens have a Max Supply value on CMC while others do not?

texts: Tokens like EOS and Populous have a max supply value on coinmarketcap while others like vechain only have a total supply. what does this mean?


texts: Is a battleships implementation feasible?

texts:
A bunch of people created a chess system that runs on the EVM: here.

I'd like to make a similar game of battleships but there seems to be an apparent difference. In battleships, you can't know what the other person's board looks like whereas in chess, nothing is hidden.

This answer explains quite well why the data is irrevocably public. What I'd like to know is, how easy would it be for a player to cheat by, for example, looking through the blockchain?


texts: cannot transfer token from EOA account to a contract from function

texts:
i was making a contract for staking where user transfer its token to a contract and i will give him interest but i got stuck to this problem i have been searching for 3-4 days but for it is not working i dont know what i am doing wrong
    pragma solidity ^0.5.0;

interface ERC20TokenInterface {
    function totalSupply() external view returns (uint);
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint);
    function balanceOf(address tokenOwner) external view returns (uint256);
    function allowance(address tokenOwner, address spender) external view returns (uint remaining);
    function transfer(address to, uint tokens) external returns (bool success);
    function approve(address spender, uint tokens) external returns (bool success);
    function transferFrom(address from, address to, uint tokens) external returns (bool success);

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

    mapping(address => uint256) stakeAmount;

    address tokenAddress = 0x3a13Cb36dAd5d083449729Ea9dE53d68121a2c02;
    string tokens = "no";

    function stakeCoin(uint256 _amount) public {
        ERC20TokenInterface token = ERC20TokenInterface(tokenAddress);
        token.approve(address(this), _amount);
        token.transferFrom(msg.sender,address(this), _amount);
    }

    function stake1(uint256 _amount) public {
        ERC20TokenInterface token = ERC20TokenInterface(tokenAddress);
        token.transferFrom(msg.sender,address(this),_amount);
    }

    function tokenBalance() view public returns(uint256){
        ERC20TokenInterface token = ERC20TokenInterface(tokenAddress);
        return token.balanceOf(address(this));
    }

    function supply() view public returns(uint256){
        ERC20TokenInterface token = ERC20TokenInterface(tokenAddress);
        return token.totalSupply();
    }

    function balance(address _tokenAddress) public view returns(uint256){
        ERC20TokenInterface token = ERC20TokenInterface(tokenAddress);
        return token.balanceOf(_tokenAddress);
    }

}

when i run stake function transaction got even though msg.sender has tokens please me out with this problem

https://ropsten.etherscan.io/tx/0x7af622aa96a91ec2ad73d22c47fef6a5f029039d3620e0e97aae054a7c0d561e


texts: Tokens not correctly added to msg.sender

texts:
This is the result of adding  500 tokens  to msg.sender

  function addTokens()  internal{
      uint256 _value = 500 ;
      balances[msg.sender]+=_value;

The result

0.000000000000000500


texts: Looking for peers in a private run blockchain using geth

texts:
I've installed geth on ubuntu 16.04 (xenial). After creating the following genesis.json file:

{
  "config": {

        "chainId": 4568,

        "homesteadBlock": 0,

        "eip150Block": 0,

        "eip155Block": 0,

        "eip158Block": 0

    },

  "alloc"      : {},

  "difficulty" : "0x400",

  "extraData"  : "",

  "gasLimit"   : "0x7A1200",

  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",

  "timestamp"  : "0x00"

}

I created an account (same as eth.coinbase) and launched miner.start().  The hashrate is >0 and I receive the following message "Looking for peers" for more than 2 hours.
I don't understand:

why do I need to look for peers in a privately run blockchain?
why is it taking so long ?

Best


texts:
I want to copy a struct from Contract A into a struct in Contract B using Contract C. Is it possible in solidity ??

We can do it for single variables.


texts: How to compare msg.data (calldata) data type to an integer data type uint256?

texts:
As per my question here:

  I need to compare msg.data (specifically, numbers that are sent with the sendTransaction data object) to a data type of uint256 within my contract.

How is this possible?


texts: Problem using created array from assembly

texts:
I've used the code from the solidity assembly tutorial here to create a single dimensional array in assembly. The code is as follows:

contract C {
function f(uint a, uint b) constant returns (uint[]) {
    assembly {
        // Create an dynamic sized array manually.
        let memOffset := mload(0x40) // 0x40 is the address where next free memory slot is stored in Solidity.
        mstore(memOffset, 0x20) // single dimensional array, data offset is 0x20
        mstore(add(memOffset, 32), 2) // Set size to 2
        mstore(add(memOffset, 64), a) // array[0] = a
        mstore(add(memOffset, 96), b) // array[1] = b
        return(memOffset, 128)
    }
}

}

When I run the function by itself in Remix, everything is ok, and it outputs the array in the correct format. The issue occurs when I try to index any value in the array when it's returned from another function. It seems to return an array of size 32, with all elements set to 32.

function get_f(uint a, uint b) public returns(uint){
        uint[] ret = f(a,b);
        return(ret[0]); //should return a, instead returns 32.
    }

The above demonstrates the problem more clearly, but I am in fact using this method of array creation to cheaply convert between uint and byte arrays directly in memory (for use with the new precompiled modexp contract). thanks.


texts: How to sign transactions while Geth does not provide private key?

texts:
I've lunched Geth for the first time and created some accounts on it. While creating accounts, I entered a password for each, and a key file is generated which contains encrypted private key belonging to each address. On the other hand, sending transactions requires signing data with the private key.
My question is how can I retrieve private key of each account in Geth while it is encrypted?


texts: Opcode for out of gas inside a message call

texts:
According to the Solidity documentation:

  A require-style exception is generated in the following situations:

...

  If you call a function via a message call but it does not finish properly (i.e. it runs out of gas, has no matching function, or throws an exception itself)

...

  Internally, Solidity performs a revert operation (instruction 0xfd) for a require-style exception and executes an invalid operation (instruction 0xfe) to throw an assert-style exception.

However in this transaction an 0xfe opcode is performed (see step 1394) which is used for assert-style exceptions.

Is the documentation incorrect or the compiler doesn't follow the documentation?


texts: Unable to filter events with specific values of indexed parameters

texts:
I am currently trying to test a smart contract using the truffle suit ( with 'truffle test'). My contract is of a simple ERC20 token which includes the standard Transfer event:

event Transfer(address indexed from, address indexed to, uint256 value);

Below is my code which attempts to subscribe to all "Transfer" events only coming from account[0] to account[1]. Even though the 2 parameters are declared as "indexed", the filter does not seem to work and I get all Transfer events no matter the sender/receiver. I tried modifying the code in various ways but nothing seems to work so far

const EnergyToken = artifacts.require("EnergyToken");
const assert = require('assert');
const truffleAssert = require('truffle-assertions');
const { performance } = require('perf_hooks');

contract("Energy Heavy Load Test", async accounts => {
    const numberOfTransactions = 10;
    let startTime = 0;
    let finishTime = 0;
    let subscription;
    let contract;
    let i = 0;

    console.log(web3.version);

    // Function for rounding numbers
    function round(value, precision) {
        var multiplier = Math.pow(10, precision || 0);
        return Math.round(value * multiplier) / multiplier;
    }

    // executed before each test
    before(async () => {
        contract = await EnergyToken.at("0x5BbD383bD43aC3896B86207eFe88cf0628ad06F0");
    });

    // Test mining time of 2500 transaction calls on the EnergyToken smart contract's transfer() method
    it("send " + numberOfTransactions + " transactions of 1 EnergyToken from account 0 to account 1", (done) => {
        // contract.Transfer(function(error, event) {
        //     i++;
        //     console.log(event)
        //     if(i == 1)
        //         startTime = performance.now();

        //     if (i == numberOfTransactions) {
        //         finishTime = performance.now();
        //         console.log("Transactions confirmed!" + " It took " + round((finishTime - startTime)/1000,2) + " seconds to confirm " + numberOfTransactions + " transactions");
        // .       done();
        //     }
        // });

        // contract.getPastEvents('Transfer', {
        //     filter: { from: accounts[0], to: accounts[1] },
        //     fromBlock: 0,
        //     toBlock: 'latest'
        // }, function(error, result) {
        //     if(error) {
        //         console.log(error, 'error');
        //     } else {
        //         console.log(result, 'result');
        //     }
        // });

        for (let j = 0; j < numberOfTransactions; j++) {
            contract.transfer(accounts[0], 1, { from:accounts[1] });
        }
        console.log("Finished sending " + numberOfTransactions + " transactions from account 1!!" + accounts[1] + " to "  + accounts[0]);
    });

    it("Calculate average gas used by the transfer() function", async () => {
        let result = await contract.transfer(accounts[1], 1);
        let hash = await result.tx;
        let tx = await web3.eth.getTransactionReceipt(hash);
        let gasUsed = await tx.gasUsed;
        console.log(" Gas used for a 'Transfer' transaction: " + gasUsed);
    });

    it("Calculate average gas used by the approve() function", async () => {
        let result = await contract.approve(accounts[1], 1000);
        let hash = await result.tx;
        let tx = await web3.eth.getTransactionReceipt(hash);
        let gasUsed = await tx.gasUsed;
        console.log(" Gas used for an 'Approve' transaction: " + gasUsed);
    });

    it("Calculate average gas used by the transferFrom() function", async () => {
        await contract.approve(accounts[1], 100, { from: accounts[0] });
        let result = await contract.transferFrom(accounts[0], accounts[1], 100, { from: accounts[1] });
        let hash = await result.tx;
        let tx = await web3.eth.getTransactionReceipt(hash);
        let gasUsed = await tx.gasUsed;
        console.log(" Gas used for an 'Approve' transaction: " + gasUsed);
    });
});

Note: My version of web3 is 1.2.6


texts: Need recovery of original JASON file for 3000 ether

texts: Is it possible to have your original JASON file you were sent in the Pre-sale re-sent. I have the password, but the file was never saved on my hard drive and my emails were deleted.  The link was saved and not the file I had my hard drive forensically searched for the file, but no luck.  Google is saying that the email is permanently deleted from the summer of 2014 and they won't help me. We have looked at the history of Google and they have went back 11 years and retrieved emails for court cases where a man was found not guilty by retrieving his old emails from 11 years earlier. Can anyone help me here as the file is worth millions at present.


texts: Did DAO attacker gained ETH on Ethereum Classic?

texts:
I'm starting to study blockchain's world and the DAO attack caught my attention.

I studied how it worked and the solution proposed by the Ethereum community.

The hard fork splitted the blockchain in 2:

Ethereum
Ethereum classic

in the Ethereum the blockchain has been reverted into the state before the malicious transactions made by the attacker that drained the DAO balance.
But this change didn't took place in the ethereum classic blockchain.

Does this mean that in the Ethereum classic blockchain the attacker successfully stole ETC from DAO?


texts: Exchange messages between two clients of Dapp without spending gas?

texts: Let's say that I want to build a Dapp such that users can exchange messages between each other. I guess you can consider it a chat Dapp. Is there any way for the two users to find the "address" of each other on the blockchain and then start communicating without using any transaction or gas?


texts: "Truffle Networks" spits out error and can't migrate to Mainnet

texts:
I'm trying to deploy to Mainnet (for the first time) but the initial migration (1_initial_migration) is getting stuck. Deploying to Kovan works fine and is super fast. I have enough Eth to deploy to Mainnet. I've attempted it few times, and it get stuck.
I'm running this command to find out the addresses of my Contract deployment. This creates an error:
TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.display (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/networks.js:58:41)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/networks.js:31:1)
    at Command.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/command.js:136:1)
Truffle v5.1.67 (core: 5.1.67)
Node v15.4.0

Could this error (not sure what causes it) be related to Truffle not being able to migrate my Contract to Mainnet?
// truffle-config.js

const path = require("path");

const dotenv = require("dotenv");
const dotenvExpand = require("dotenv-expand");
const HDWalletProvider = require("@truffle/hdwallet-provider");
const { ethers } = require("ethers");

const pathToConfig = path.resolve(".env");

const env = dotenv.config({
  path: pathToConfig,
});

dotenvExpand(env);

module.exports = {
  networks: {
    contract_build_directory: "./client/src/contracts",
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.

    // mainTest: {
    //   url:
    //     "https://sandbox.truffleteams.com/df027e94-8bfc-4af8-82de-0205db77e32c",
    //   network_id: 1,
    // },
    development: {
      host: "127.0.0.1", // Localhost (default: none)
      port: 7545, // Standard Ethereum port (default: none)
      network_id: "*", // Any network (default: none)
      gas: 10000000,
      gasLimit: 26000000000,
    },

    kovan: {
      provider: () =>
        new HDWalletProvider({
          mnemonic: { phrase: process.env.MNEMONIC },
          providerOrUrl: process.env.RPC_URL_42,
        }),
      network_id: 42, // Kovan's id
      from: process.env.DEPLOYERS_ADDRESS,
    },

    mainnet: {
      provider: () =>
        new HDWalletProvider({
          mnemonic: { phrase: process.env.MNEMONIC },
          providerOrUrl: process.env.RPC_URL_1,
        }),
      network_id: 1, // Main's id
      gas: 5500000, // Main has a lower block limit than mainnet
      confirmations: 2, // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200, // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: false, // Skip dry run before migrations? (default: false for public nets )
      from: process.env.DEPLOYERS_ADDRESS,
    },
  },

  // Set default mocha options here, use special reporters etc.
  mocha: {
    timeout: 100000,
  },

  // Configure your compilers
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  compilers: {
    solc: {
      version: "0.7.4", // Fetch exact version from solc-bin (default: truffle's version)
    },
  },
};


texts: Detecting whether a transaction was cancelled (because a block is orphaned)

texts:
I'm writing a system where some transactions have to be automatically detected, and wait for 30 blocks to ensure they're confirmed. What I do is that I read all new blocks, and find the transactions that belong to my addresses.

I'm using geth with getBlockByNumber RPC call, and then when I find a transaction that belongs to me, I put it in a mempool and wait for 30 blocks to pass, and then consider the transaction final.

The question: How can I detect cancelled transactions to prevent double-spending?

I can imagine a situation where a block becomes orphaned and/or canceled in some way. Before considering the transaction final, how can I check that the transaction is still valid and wasn't canceled in some way?

Is it sufficient to just check the same block (by number) before considering the transaction final, and check that the transaction is still there? Are there other scenarios that I have to worry about? (uncle blocks, etc.) How can I check this systematically?


texts: Create Wallet Contract - Spinning for 2 days now

texts:
I have the ethereum wallet, created some test tokens, and then tried a wallet contract, single owner...named it and clicked create and entered the password.  Now I have the Wallet Contract spinning on my main page, saying "Creating", and it has been two days now, and this is after having stopped and rebooted a few times.

Is there a way to cancel this wallet contract?  It seems to be blocking any transfers of the test token now.


texts:
Plan to implement private chain based on PoA to overcome transaction speed and privacy issue.
Q1. what is the expected TPS? any advice to increase it?
Q2. Understand that we can still leverage tools and other modules such as geth/web3/whisper, but how about ethereum ecosystems, such as uport, oracles, etc


texts:
Please tell me how I can protect myself from the frontrunning on the pancakeswap exchange.
I use python3 and web3.py but when i set max gas price it is not help me.


texts: maintaing metadata while ERC721 cross-chain transfer

texts:
I want to make any ERC721 token (on any contract) to be transferable from ethereum to MATIC chain (fully compatible with EVM with deployed support contracts on ethereum). So I am doing the following two-step process:

"Container" ERC721 contract on ethereum and "childContainer" with default safeTransfer and onERC721Received implemented, metadata for any token minted on this contract will be stored in http://baseURI/tokenId format.
"Container" contract will approve ERC721Predicate and rootChainManager contracts deployed by MATIC on ethereum which will lock specific token and mint the same tokenId on MATIC chain contract "childContainer" (called by childChainManager deployed by MATIC). Fully managed automatically by calling a single function.

I am facing an issue while transferring metadata of tokens that are not minted on the Container contract. A tokenId on any external contract can change owner to Container by calling the transfer method by the current owner. But how do I transfer metadata cross-chain, I can query metadata but it can be any URL and all tokens minted on Container are in http://baseURI/tokenId format where baseURI set on MATIC chain childContainer manually once as soon as it is deployed so metadata can be the query with just tokenId but that is not the case with tokens minted on any other ERC721 contract except Container


texts: How to restart mining in my private blockchain?

texts:
I successfully setup a private blockchain in my laptop and mined around 5160 Ether (no market value). Also deployed a smart contract.

Now I had to close my laptop and when I came back and turned the system on, with all the steps, my wallet on my private block chain is showing 5160 Ethers, but I am not able to mine further and the hash rate is 0.0 KH/s even after miner.start(1); command in geth for around 20 minutes. Where am I going wrong and how to resume mining on my private blockchain? In the first attempt the hash rate was quite decent.


texts: Ethereum Contract ABI - Encoding for functions with no arguments

texts:
I am using argument encoding from this page (https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) to build data field for offline signing. I am using eth.sendRawTransaction to call a function in my deployed smart contract. Everything is working fine when the functions have arguments (1 or more), but I am getting an "invalid opcode" exception for the functions which have no arguments. I am using just the first four bytes of the function selector (i.e, sha3('myFunc()')) since there are no arguments.

These functions are working fine when I use a dummy argument (keeping the rest same).

Is there a special way to handle functions without arguments ?


texts:
I've been reading about the problem of front-running, especially in the Bancor case (https://hackernoon.com/front-running-bancor-in-150-lines-of-python-with-ethereum-api-d5e2bfd0d798). One proposed solution is using CREATE2 opcode (from EIP-86) - http://hackingdistributed.com/2017/08/28/submarine-sends/
But I am not sure I understand the whole concept, so it would be nice if someone could elaborate on this.

  CREATE2 will compute the address of the newly created smart contract C as H(addrCreator, salt, codeC), where addrCreator is the address of the contract’s creator, salt is a 256-bit salt value chosen by the creator, and codeC is the EVM byte code of C’s initcode

So this basically means that you can "reserve" an address without revealing the contract there or what? And you can even send ether to it?
CREATE2 then basically "turns" this seemingly random address into a smart contract?

The "submarine receiver" uses CREATE2 to instantiate a forwarder contract for himself but because the code is part of the hash he can just create
the exact forwarding contract "submarine sender" had in mind (so both have to be synchronized in that sense)?

But that whole stuff doesn't happen atomically, does it? In the sense that when the nonce/salt is revealed the same block could also contain a "normal" send that would front-run the "submarine send"? Or that doesn't matter anymore because the timestamp of the original transaction that sent ether is used?


texts: Solidity compiler doesn't work in the Javascript Console

texts:
I'm using Geth 1.4.5-stable along with Solc version 0.3.5-0 both on Linux. It is run on a Digital Ocean server. I have a fully synced testnet chain and I'm trying to compile contracts from within the Javascript console.

Steps I've taken:

A. I added Solidity to PATH with export PATH=$PATH:/usr/bin/solc

B. I connected to the console in an another shell window with the following command:

geth --rpc --rpcaddr localhost --rpcapi "eth,net,web3,admin" \
  --solc /usr/bin/solc attach ipc:/home/physes/.ethereum/testnet/geth.ipc

This seems to work fine, and I can use other RPI API commands.

C. I was testing out a Greeter contract.

i)

var greeterSource = 'contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) suicide(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }'

ii)

var greeterCompiled = web3.eth.compile.solidity(greeterSource)

At this point it fails, and I get:

solc: exit status 1
Unknown exception during compilation.
at web3.js:3119:20
at web3.js:6023:15
at web3.js:4995:36
at <anonymous>:1:23

What am I doing wrong?


texts:
In February 2014 (over three years ago), Vitalik wrote in a blog post that:

  Note that there is one weakness in this protocol: you now need to know all transactions ahead of time before processing a block, and adding new transactions requires substantial effort to recalculate intermediate stack trace values, so the process of producing a block will be more inefficient. However, it is likely possible to patch the protocol to get around this, and if it is possible then BP2.1 will have such a fix.

Has such a fix been produced?


texts: Can only the contract creator send subsequent transactions to it to run the contract?

texts:
As the contract address is created based on the sender's address plus the nonce value of the transaction creating it, I would think that only the contract owner/creator would know this and could invoke it subsequently to run the code in the contract.

Is it possible to share this address with some other account, so that the other account could invoke the code in the transaction?

Thanks.


texts: How does MetaMask communicate with the blockchain?

texts: I've looked over the source code and cannot for the life of me figure out how MetaMask is accessing the blockchain.  When set to Mainnet, which RPC is it using?


texts: How can a smart contract store mutable data outside blockchain?

texts: As storing persistent data on blockchain is costly due to the storage operation being gas-expensive, what are the solutions to store mutable data outside the realm of blockchain from within a smart contract? I heard about IPFS and Swarm, but didn't really understand how they interface as a storage layer with a smart contract. Let's say we are to design an imaginary banking application (DApp) that should handle a million customers. We need to read/write the customer information including the account balance in a persistent storage. The business logic is implemented in a smart contract. But, how do we deal with this huge volume of data in a storage later?


texts: In both the Ethereum chain specification format and in Parity's documents on private chains,  you see the term seal a block.  What exactly does that term mean?  How is it different than mining a block?


texts: Initialize a fixed size, 2 dimensional array within function

texts:
In Solidity, how do I define a fixed size, 2 dimensional uint8 array scoped to a function, initialized with all zeros?

E.g.

func(){
  var myArr = new uint8[5][5](); // which does not work.
}


texts: Stuck trying to verify a smart contract through hardhat

texts:
I am trying to verify on hardhat an nft-tutorial by chainlink but am unable to. I have converted most of the code to hardhat compatible. The contract address on Rinkeby is 0xA4630A1f2DaC2474d7397E7e8F3A41Bd574C1f9d.  I want to deploy using Hardhat not Truffle. Here is the link to the repo
Here is my command
npx hardhat verify --network rinkeby 0xA4630A1f2DaC2474d7397E7e8F3A41Bd574C1f9d "0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B", "0x01BE23585060835E02B77ef475b0Cc51aA1e0709", "0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311"

Based on the hardhat docs, I should be able to run:
npx hardhat verify --network rinkeby DEPLOYED_CONTRACT_ADDRESS "Constructor argument 1" "Argument 2"

Getting this error when running the above code:
TypeError: Cannot read property 'contracts' of undefined

Sometimes I also get:
TypeError: Cannot read property 'engines' of undefined


texts: Can't get the func in `web3.eth.getAccounts` to run

texts:
I'm trying to perform a simple balance check, but the code inside web3.eth.getAccounts doesn't run.

I'm trying to get web3 from the instance injected by Metamask.

myWeb3.eth.getAccounts(function(err, accounts) {
  console.log("why doesn't this run? ");
  myWeb3.eth.getBalance(accounts[0], function(err, balance) {
    render("Your balance is " + window.web3.fromWei(balance, "ether"));
  });
});

https://codesandbox.io/s/q3m178xnl9
src/index.js:26

I'm not really a developer, so it's possible this is something silly on my end.

Thanks a lot ❤


texts: Who knows what a token collection interface is?

texts: I'm new to blockchain development. I'm reading a tutorial on developing an NFT platform and it talks about a token collection interface. Can anyone explain to me what this is. Let's say you have a platform that has users who upload digital photos of their artwork and buyers who buy/bid on the platform? Thanks


texts: Transaction cannot found when using debug.traceTransaction

texts:
I am trying to use the debug.traceTransaction API but got the following error:

>debug.traceTransaction("0x3684f071b34da1116282ee88a106a8f2a266d273ef7d8964957f65128fb58d77")

Error: transaction 3684f071b34da1116282ee88a106a8f2a266d273ef7d8964957f65128fb58d77 not found
    at web3.js:3143:20
    at web3.js:6347:15
    at web3.js:5081:36
    at <anonymous>:1:1

This transaction seems legit via the etherscan.io, and I am also syncing with the main network with the following command:

geth --cache=1024 --rpc --rpcapi "eth,net,web3,debug" console

Currently the progress is:

> eth.syncing
{
  currentBlock: 694850,
  highestBlock: 6788672,
  knownStates: 906699,
  pulledStates: 890731,
  startingBlock: 571445
}

Is it because on my local machine I haven't "synced" that block? Thanks.


texts: Its possible to recive and send tokens by smartcontract?

texts: Is it possible to receive and send other tokens (like DAI for example) by smart contract?


texts:
On the PoW model, in order to find the proper network all you need is the address of a single correct node. You're able to identify the proper network by simply picking up the one with the most accumulated computing power.

On the PoS model, the solution isn't as obvious to me. It seems that, in order to find the proper network, you must absolutely trust whoever gave you the IP of a node. That seems to put a "trust" barrier on network entrance.

Am I missing something, is there any clever trick to solve this issue?


texts: Dropped and replaced transaction still showing pending on UNIswap

texts:
I checked some of the answers given to a similar question but none of them helped to solve my situation, hence I am writing it down.
My transaction's status is now "Drop and Replaced" but it still shows pending on Uniswap interface and I can not use the coins I wanted to swap. The "approve" button while trying to swap is now unclickable for that coin.
My transaction: https://etherscan.io/tx/0xab038a9d9d644c17414f270ca560f56faed95680e7d55244a63d26374491de13
I also tried to send O ETH to my address, didn't help.
If I put the nonce number, it gives a RPC error.
Totally stuck, appreciate help.
Thanks!


texts: How to display blockchain transaction receipt details in an Ethereum Dapp

texts:
In my dapp design, I wish to provide the user with an option to view Blockchain Transaction Receipt Details either by a link to sites like Etherscan or by providing full details on a separate page in the dapp.

How can this be accomplished?

Please help to provide some sample code or implementations for reference.


texts: Ether balance suddenly went to 0 and address not found on ether chain please help

texts: My address is 0x9ac0e6b745bbd98eec2d900d5ee8144157d7fc1e and I had ether in it but it suddenly went down to 0 I have also never been able to find my address on ether chain.


texts:
From the official Ethereum Documentation:

The DAG is totally different every 30000 blocks (a 100 hour window, called an epoch) and takes a while to generate.

Is this also true for a private blockchain which has a lot less difficulty? How is the epoch period calculated?


texts: How to use "web3.js library" in a "JavaScript" file without using "require("web3")"?

texts:
Consider we want to use web3.personal.sign in a JavaScript file. So, we need to add :

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

at top of our JavaScript file.

However, if we want to run this code in a browser, we cannot use require(). For example, in case of using ethereumjs we can add github resources as follows (as described in THIS ANSWER):

<script src="https://cdn.rawgit.com/ethereumjs/browser-builds/2fb69a714afe092b06645286f14b94f41e5c062c/dist/ethereumjs-tx.js"></script>
<script>

And It works.

So, is there a similar way for adding web3.js using <script src= ... ?

When I use <script src="https://rawgit.com/ethereum/web3.js/develop/dist/web3.js"</script> <script> instead of Web3 = require("web3") I receive following error message :

    <!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>EthereumJS - Browser Example</title>
</head>

<body>
  <script src="https://rawgit.com/ethereumjs/browser-builds/master/dist/ethereumjs-abi/ethereumjs-abi-0.6.5.js"></script>
  <script src="https://rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

  <script>

  function constructPaymentMessage(contractAddress, amount)
  {
  return ethereumjs.ABI.soliditySHA3(
    ["address", "uint256"],
    [contractAddress, amount],
  );
  }

  var message = constructPaymentMessage("0x0f0f422477d83bcbed227b0ae2fa3ace7ea3c653", 100);
  console.log(message);

  web3.personal.sign("0x" + message.toString("hex"), "0xc9c3b1351c65ac47abf3774b6a9715ba3625bec5",  function(err, something) {});

  </script>
</body>
</html>

Error:

  "test.html:28 Uncaught ReferenceError: web3 is not defined at test3.html:28"

Note1: test.html is name of this html file.

Note2: I use web3 version 1.0.0.

Note3:  My main purpose is to run successfully JavaScript code presented HERE . When I run it using node I receive some errors. What is the best way of running this JavaScript code? Do I need to create an html file and run it with browser? or it's better to create a JavaScript file and run it using node filename.js ? The problem with running this code that is for signature verification is explained in details HERE . Eventually, I had to change some part of JavaScript code (I precised which parts have been changed in my question HERE ). However, eventually, when I call the function of Solidity contract (i.e. function close) to verify signature, the transaction is reverted as I mentioned the details of error HERE.

Note4: Related question: web3.js error: Cannot read property 'providers' of undefined


texts: Is there a web3 api written in golang to interact with Eth nodes?

texts:
I'm looking for a library that can easily interact with Ethereum nodes that is similar to Web3.js.

go-ethereum is written entirely in go so I would of thought I could write scripts pretty easily.


texts: Does it possible to perform Merkle root proof with filters?

texts:
I have a centralized e-commerce system with orders table inside. There are few order categories inside this system such as:

Pending payment
Pending shipping
Pending delivery
Completed
Cancelled

I want to store all orders in a Merkle tree for accountability sake (maybe once a day).

If I put all orders under all categories above in one same tree, does it possible to perform Merkle root proof with filter as required argument?

For example, does it possible to proof order ID 1 under category Completed is part of the Merkle tree?

What I'm expecting is something like this:

If supplied category is Completed, it should return true
If supplied category is not Completed, it should return false

I read about Merkle tree, Merkle proofs and sparse Merkle tree. But I'm still clueless. I welcome all ideas from members here. Implementation wise, I can code Solidity, Golang and Node. The verification app can be in Golang or Node.


texts: Are there any exchanges like Shapeshift for testing and development?

texts:
I'm developing a simple application which involves calling Shapeshift, Bitfinex and similar exchange APIs.  They do not provide any sandboxed or under-testnet versions of their APIs for clients to use.

Do you know any similar 'fake' Exchange applications to be used for testing ETH/BTC nodes for development purposes?


texts: How can I export Ethereum blockchain data into csv?

texts:
I would like to download the Ethereum blockchain and use the data for machine learning purposes. For this, I have to get the data into a workable format like csv or a flat JSON etc.

I've read about approaches and the most common one seems to be through a monkeyDB. Do you know a source code that implements this method? Or do you know other methods that could be used to get the Ethereum blockchain data into a modeling friendly format?

Thanks!


texts:
I am new to Vyper and am trying to use the raw_call built in function as defined in the official documentation.
I am getting the error where the vyper compiler says that the raw_call function expects 2 arguments and not 5. Is the official documentation wrong here or am I missing something? Would greatly appreciate some help
Please find the output and code screenshots attached.


texts: solidity ^0.5.0 factory pattern mapping apprach

texts:
new to solidity.

Trying to understand the better approach for using a mapping storage in factory contract.

2 options:

Use mapping(address => Contract[])
Use mapping(address => address[])

Sample factory:

contract CampaignFactory {

    mapping(address => Campaign[]) campaigns;

    function createCampaign(uint min_contrib) public {
        Campaign newCampaign = new Campaign(min_contrib, msg.sender);
        campaigns[msg.sender].push(newCampaign);
    }

    function getCampaignsByAddress(address creator) public view returns (Campaign[] memory) {
        return campaigns[creator];
    }
}

As i understand, the first option suppose to use more storage space to store the whole contract instance.
However, for both options createCampaign cost (remix estimation) is the same +- 660000 gas.
Additionally, getCampaignsByAddress with the return type Campaign[] strangely returns only addresses instead of full instances (so i suppose only the address is stored).

Question: what difference does it make to use option #1 or #2?


texts:
I am running a full node in a testnet and I am trying to connect a light node. I am using the following command:

geth --datadir node1 --port 30313 --rpc --rpcport 3013 --rpcaddr 127.0.0.1 --ipcpath node1/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.1 --wsport 3113 --wsorigins "*" --syncmode light

I am using static-nodes.json and admin.addPeer() but they dont work, but if I try to connect another full node in the same way, everything works. Any idea how can I connect a light node peer?

My Geth version is 1.8.19


texts:
I'm trying to build a browser UI to interact with my Solidity smart contract that is deployed on my local Ganache blockchain. But I can't seem to get my index.html file to connect to Metamask. I keep getting this error when opening my index.html in Chrome:

main.js:5 Uncaught ReferenceError: Web3 is not defined
    at main.js:5
(anonymous) @ main.js:5

Github repo: https://github.com/Lennardmulder/Mannencoin

What am I missing here?


texts:
I would like to understand the basics of Ethereum and i would like to clone it and make my own local currency based on Ethereum to experiment at most its capabilities.
Is there anyone that can give me some good hints on this point? I have good skills with Bitcoin related forks and i cloned a lot of different coins for education purposes in the last years.

I'm just wondering about how in example generate a new genesis hash for a an Eth fork. Anyone?

Thanks anyone in advance for the many infos you can help me to gather.


texts: What is the difference between create and newAccount in web3js?

texts:
There are two ways to create account one is web3.eth.accounts.create() and web3.eth.personal.newAccount(); function, When I use newAccount() function account is created in my local geth client but when I used create() function nothing happens.

Edit :
from web3.eth.accounts.newAccount() to web3.eth.personal.newAccount();;


texts: Peers not syncing on PoA private network

texts:
I've got a private network with two PoA geth nodes, with each node running on a separate machine. One node has been running for some time (in instamine mode) and has mined 6909 blocks. I've just setup the other node and was able to connect both nodes using admin.addPeer.

Output of admin.peers confirms that the peers are connected, and both nodes are using the same genesis block.

Output of eth.syncing shows that my second node knows about the blocks on my first node :

{
  currentBlock: 4859,
  highestBlock: 6909,
  knownStates: 45954,
  pulledStates: 45954,
  startingBlock: 6844
}

The syncing process however does not actually start.
Verbose output of my second node shows some warnings :

Node data write error               err="state node c84891...25d151 failed with all peers (1 tries, 1 peers)

...

Synchronisation failed, retrying    err="state node c84891...25d151 failed with all peers (1 tries, 1 peers)

Both machines are using fixed IP's and TCP traffic is allowed on port 30303.

I have read all similar questions/answers and open issues but cannot figure out what the problem is. What am I missing?

Geth version: 1.8.23-stable & OS version: Ubuntu 18.04.2 LTS


texts:
I'm noticing a lot of ether transfers into ERC20 token contracts months after the token's ICO finished.  I am wondering how is this possible, and where these tokens are coming from, since tokens are only distributed by a company during and ICO?

An example:https://etherscan.io/address/0xa74476443119A942dE498590Fe1f2454d7D4aC0d
Here we see addresses sending 0 ether to 'GolemToken' contract in exchange for tokens.


texts: How to change prefix of signature in Javascript?

texts:
Is it possible to change the signature prefix, which by default:

"\x19Ethereum Signed Message:\n32"

Can I change it to another prefix?

I need to get a signature in solidity in this way:

bytes32 signature = keccak256(abi.encodePacked(prefix, hash));


texts: In the context of Ethereum contract creation, what does "cyclic creation dependencies are impossible" mean?

texts:
I'm reading the official solidity docs and came upon this passage on Ethereum contract creation: "cyclic creation dependencies are impossible", followed by the example code below (and also linked). After reading the contract code I'm confused whether it is a valid construction, or example of what NOT to do. OwnedToken and TokenCreator contracts seem to be referencing each other, as I have "NOTED" in via comments
    pragma solidity >=0.4.22 <0.7.0;

    contract OwnedToken {
        TokenCreator creator;
        address owner;
        bytes32 name;

        constructor(bytes32 _name) public {
            owner = msg.sender;
            creator = TokenCreator(msg.sender); // NOTE: referenced TokenCreator contract
            name = _name;
        }

        function changeName(bytes32 newName) public {
            if (msg.sender == address(creator))
                name = newName;
        }

        function transfer(address newOwner) public {
            if (msg.sender != owner) return;

            if (creator.isTokenTransferOK(owner, newOwner))
                owner = newOwner;
        }
    }

    contract TokenCreator {
        function createToken(bytes32 name)
            public
            returns (OwnedToken tokenAddress)
        {
            return new OwnedToken(name); // NOTE: references back to the OwnedToken contract!
        }

        function changeName(OwnedToken tokenAddress, bytes32 name) public {
            tokenAddress.changeName(name);
        }

        function isTokenTransferOK(address currentOwner, address newOwner)
            public
            pure
            returns (bool ok)
        {
            return keccak256(abi.encodePacked(currentOwner, newOwner))[0] == 0x7f;
        }
    }

I find this very confusing. Does this example work or not? What does cyclical creation dependencies actually mean. What are some reasons for using cyclical creation in the first place (e.g. what languages support it)? Please help clarify. Thanks!


texts: Digging into Plasma talks, I see that that Plasma chains can make periodic commitments to the root chain.  Assuming only a single tree depth with users paying validators a fee per transaction, would it be the validators who pay the gas costs for the root commitments by calling a function in the Plasma contract on the root chain?  I can't see any other possibility now as contracts cannot pay to execute contracts (yet).


texts: Formula for instrinsic gas value in Ethereum yellow paper

texts: In the Ethereum yellow paper 6.2 there is a formula (54) defining g_0 refers to a sum which is indexed over i. But i doesn't occur on the right side except by making a distinction between i = 0 and not(i = 0). Why is this expressed in such a compilicated way and not as a simple product. Or am I missing an implicit dependency on i?