texts: What's the most efficient way to check if a number is a power of ten in Solidity?

texts: That is, how to check whether a given number is 10, 100, 1000, etc., all the way up to 10**77, which is the highest power of 10 that fits in uint256.


texts: How do I get the raw private key from a WalletFile object?

texts:
How can I get the raw private key from a WalletFile object?

Here is how I am creating the wallet.

String seed = UUID.randomUUID().toString();
ECKeyPair exKey = Keys.createEcKeyPair();

BigInteger privateKey = exKey.getPrivateKey();
BigInteger publicKey = exKey.getPublicKey();

WalletFile wallet = Wallet.createLight(seed,exKey);

Here is the code where I am sending a transaction,and I need the private key created previously.

Credentials credentials = Credentials.create("MY PRIVATE KEY");

 TransactionReceipt transactionReceipt = Transfer.sendFunds(
                    web3j, credentials, accountTo,
                    BigDecimal.valueOf(0.5),Convert.Unit.ETHER).sendAsync().get();


texts: Can I subscribe to events emitted by another contract?

texts:
I am trying to subscribe to an event emitted by an existing library's smart contract. I've found examples of how to subscribe to events emitted by my contract using web sockets and my contract ABI as below from web3 docs, but am still confused as to how to listen for events emitted by other contracts.

Is it possible to capture other contracts' events by taking this approach:

const otherContractInterface = require('../build/contracts/otherContract.json')
const deployedAddress = otherContractInterface.networks[networkId].address
token = new web3.eth.Contract(otherContractInterface.abi,deployedAddress)

const subscription = web3.eth.subscribe('logs', {
address: '0x123', // Address of other contract I'm trying to listen to
topics: ['0x345'] // Index of event I'm trying to listen to
}, function(error, result){
if (!error)
    console.log(result);
});

I found a post on this exchange from 2016 (Can a contract listen to events of another contract?) that indicates it is not possible to listen to other contracts' emitted events--is this still the case with Web3 1.0.0?


texts: Why ethereum block mining time is set up to 15 seconds

texts: Why it isn't set to 1 second or smth like? Is there any cause for this decision? Or it's just a random number?


texts: How to get all kind of transactions happend to/from an address within a time range?

texts:
I'm trying to get all transactions that occured to an address within a specified time range. The transactions shall include all ethers as well as token transactions done to/from an ethereum address.
I tried writing the following code. The minTimeStamp is the time from which I need to get transactions till current time.
Take a quick peak to that:
async function getT(minTimestamp) {
minTimestamp = 1592834400;

const transactions = [];
let blockNum, block;

await web3.eth.getBlockNumber().then(r => {
    blockNum = r;
});

await web3.eth.getBlock(blockNum).then(r => {
    block = r;
});

while (block.timestamp >= minTimestamp) {
    await new Promise(async(next) => {
        console.log(`[*] Searching block ${blockNum}`);
        if (block && block.transactions) {
            for (let txHash of block.transactions) {
                await new Promise(async(next2) => {
                    let tx = await web3.eth.getTransaction(txHash);
                    if (tx.to != null) {
                        if ('0x92376311Ce465c54b26D18C50f8a90734bFB1172'.toLowerCase() === tx.to.toLowerCase()) {
                            console.log(`[+] transaction found on block ${blockNum}`);
                            console.log({
                                address: tx.from,
                                value: web3.utils.fromWei(tx.value, 'ether'),
                                timestamp: new Date()
                            });
                        }
                    }
                    if (tx.from != null) {
                        if ('0x92376311Ce465c54b26D18C50f8a90734bFB1172'.toLowerCase() === tx.from.toLowerCase()) {
                            console.log(`[+] transaction found on block ${blockNum}`);
                            console.log({
                                address: tx.to,
                                value: web3.utils.fromWei(tx.value, 'ether'),
                                timestamp: new Date()
                            });
                        }
                    }
                    next2();
                });
            }
        }

        transactions.push.apply(transactions, block.transactions);

        --blockNum;

        await web3.eth.getBlock(blockNum).then(r => {
            block = r;
        });

        next();
    });
}

console.log('Retreived', transactions.length, 'transactions');

}
It works fine although very slow, but I am not able to get token transactions from this code.
Can anyone suggest how I can tweak the code to get that?
Also, if there is any better approach I will appreciate the suggestions.
Thanks, looking forward
Fariha


texts:
How do we call contracts with msg.value? For example, below is my basic contract, but couldn't find anyway to write test cases in truffle.
So how do I write test cases for below methods?
deposit(), deposit(unit amount), deposit(address adr) ??

pragma solidity ^0.4.18;

import "./ConvertLib.sol";

contract MetaCoin {
    mapping (address => uint) balances;

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

    function MetaCoin() public {
        balances[tx.origin] = 10000;
    }

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

    function getBalanceInEth(address addr) public view returns(uint) {
        return ConvertLib.convert(getBalance(addr), 2);
    }

    function deposit() payable {
        balances[msg.sender] += msg.value;
    }

    function deposit(uint amount) payable {
        balances[msg.sender] += amount;
    }

    function deposit(address addr) payable {
        balances[addr] += msg.value;
    }
}

Truffle Test

var MetaCoin = artifacts.require("./MetaCoin.sol");

contract('MetaCoin', function(accounts) {
  it("should put 10000 MetaCoin in the first account", function() {
    return MetaCoin.deployed().then(function(instance) {
      return instance.getBalance.call(accounts[0]);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    });
  });
  it("should return 20000 Eth in the first account", function() {
    return MetaCoin.deployed().then(function(instance) {
      return instance.getBalanceInEth.call(accounts[0]);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 20000, "10000 wasn't in the first account");
    });
  });
});


texts: Using truffle migrate with Ledger Nano S

texts:
I am using truffle to develop new contracts and I have successfully deployed contracts to the Rinkeby Testnet directly with truffle. However, this process, like the one using the MainNet, requires geth started with an unlocked account:

geth --rinkeby --rpc --rpcapi db,eth,net,web3,personal --syncmode "fast" --unlock="0x000-deployer-address-here"

Now truffle migrate will deploy the Migrations contract and my other contracts with 0x000-deployer-address-here address as the owner.

My question is if this deployment can be done with a Ledger Nano S address as the owner.


texts: Difference between 'web3-react' and ''@web3-react/core''

texts:
I am trying to understand how popular projects works.
Here is what i've found in uniswap interface's source code:
https://github.com/Uniswap/uniswap-interface/blob/master/src/hooks/index.ts:
import { useWeb3React as useWeb3ReactCore } from '@web3-react/core'

And here is what i've found in aave interface's source code:
https://github.com/aave/uniswap-frontend/blob/beta/src/hooks/index.js
import { useWeb3Context } from 'web3-react'

What is the difference between those 2 libraries ?
Thanks a lot


texts:
Say you're importing a library, and that library contains a struct:
pragma solidity >=0.8.0;

library SomeLibrary {
    struct FooType {
        uint256 value;
    }
}

contract SomeContract {
    ...
}

I know that I can use that type as SomeLibrary.FooType. But that is verbose - it quickly ends up taking a lot of space in my implementation.
Is there any way I could set a local alias for this external library type? Ideally I would like to do this:
FooType = SomeLibrary.FooType;


texts:
Is it possible to filter past events with a boolean condition? For example I have the following event:
event ExampleEvent(uint256 exampleNumber);

In my js code I can filter these events with the == operator as follows:
const pastEvents = await exampleContract.getPastEvents("ExampleEvent", { filter: {exampleNumber: 10}, fromBlock: 1 });

Is it possible to filter with different operators? eg like this: exampleNumber>10


texts: How to use events to retrieve data from a transaction? PRIVATE CHAIN

texts:
i am using GETH for the architecture and deployment of my contract  on a private chain and it works pretty fine, but unfortunately i want to return data from a transaction function and this makes me crazy. I know that to read returned value of transactions is necessary to involves solidity's events and then, trough WEB3 we can read them. I'll show my detailed steps to read events but nothing works at all. Any kind of help would be really appreciated.
This is the code that i need to gather:

This is the event declaration right above the contract constructor

event Accessed(string _msg,address _add, uint _time);

function transfer(bytes32 _ID) public returns (address)
{
    // Only the current owner can transfer the token.
    if (ID == _ID)
        {
                owner = msg.sender;
                taddr.push(msg.sender); //taddr is an array used for storing address of whoever call the
                                        //transfer function
                ttime.push(now);        //same but it stores the timestamp
                Accessed("someone executed the transfer function",owner,now);
                return(owner);
        }
}
 function getOwners() view public returns (address[],uint[]) //this should print the two above arrays and return them
{

     return (taddr,ttime);

}

So what i want is mainly get the 2 arrays as return or at least read every call of the transaction() function.

After the deployment i use

var myContract = web3.eth.contract([ABI]);
var meta = myContract.at("address");
var Transfer = meta.Accessed({}, {fromBlock: 0, toBlock: 'latest'});
Transfer.watch(function(err, e) {
   if (err) {
      console.log(err);
} else {
      console.log("new Transfer executed from", e);
}
});

With this snippet on any node console i'm listening for any call of the Transfer() function but nothing happens. This is what i get in response of the event watch

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

Same happens with event.get()

SO in your opinion what is the problem? Am i missing something?

Many thanks


texts:
I want to prove that a contract was deployed by a specific address (a factory contract). I have noticed that block explorers such as https://etherscan.io/ list the contract creator. How do they get this information? I cant find any way of getting a contracts creators address from the  the etherscan api.

How can I identify the address that deployed a contract?


texts: Why creating a contract just for function declarations?

texts:
In the BAT token contract:

  https://etherscan.io/address/0x0d8775f648430679a709e98d2b0cb6250d2887ef#code

What is the purpose of declaring the contract "Token" (in which just the functions are declared) and just after creating another contract which inherits from "Token":

  contract StandardToken is Token {...}

Why not just declaring AND defining all functions in one contract ?


texts: web3.js - Retrieving an item in a Smart Contract array

texts:
In Solidity, I have an array declared as follows:

uint[] public moveTimeStamp;

In web3 JavaScript I would like to retrieve the element at position 0 in the array. I tried to access it like this:

var contract = web3.eth.contract(interface);
var instance = contract.at("0x1234...");
instance.moveTimeStamp(0).call(function(err, result) {....

Web3js says this isn't correct. What should I be writing after moveTimeStamp?

I tried the following:

instance.moveTimeStamp(0)
instance.moveTimeStamp([0])

...which doesn't work.

This is how I call it:

var contract = web3.eth.contract(interface);
var instance = contract.at(contractaddress);
instance.callTimeStamp(0).call(function(err, result) {...

And this is the error I get

TypeError: instance.callTimeStamp(...).call is not a function

And if you will like see that the callTimeStamp array really does contain something, you can go to https://ropsten.etherscan.io/address/0x86c9d3abf13d25ced87c0d00331667ac44c04a89#readContract to read the contract variables.


texts: how to connect my html form that is username and password to blockchin and taking the username as metamask key?

texts: I am developing a decentralized cloud web application, when the user will login into the application he/she will generate password from blockchain, I am not getting how to connect my html form that is username password to blockchain so that it will take the username as the key of metamask and password should be generated from blockchain.


texts: Truffle with Drizzle fails with TypeError: str.slice

texts:
Using Drizzle ran into a problem. Can anyone help? There are several get functions

1-st works fine both in the truffle console and at the frontend, function without arguments

truffle console:

input: this.Ethnote.deployed().then(instance => { return instance.getNotebooksCount();}).then(result => {console.log(result);}).catch(e => {console.log(e);});

output: BigNumber { s: 1, e: 0, c: [ 1 ] }

react:

input: <ContractData contract="Ethnote" method="getNotebooksCount "/>

output: 1

2-nd works only in the truffle console, on the front it falls with an error, function with argument 0 (Notebook index) and returns several outputs

truffle console:

input: this.Ethnote.deployed().then(instance => { return instance.getNotebook(0);}).then(result => {console.log(result);}).catch(e => {console.log(e);});

output: [ '0x627306090abab3a6e1400e9345bc60c78a8bef57',
'inbox',
BigNumber { s: 1, e: 9, c: [ 1521898678 ] },
BigNumber { s: 1, e: 9, c: [ 1521898678 ] },
BigNumber { s: 1, e: 0, c: [ 0 ] } ]

react:

input: <ContractData contract="Ethnote" method="getNotebook" methodArgs={[0]} />

output: TypeError: str.slice is not a function
    at Object.keccak256 (http://localhost:3100/static/js/bundle.js:60919:14)
    at Object.sha3 (http://localhost:3100/static/js/bundle.js:60556:29)
    at DrizzleContract.generateArgsHash (http://localhost:3100/static/js/bundle.js:69698:39)
    at Function.cacheCall (http://localhost:3100/static/js/bundle.js:69637:32)
    at new ContractData (http://localhost:3100/static/js/bundle.js:146699:130)
    at http://localhost:3100/static/js/bundle.js:27170:19
    at measureLifeCyclePerf (http://localhost:3100/static/js/bundle.js:26951:13)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (http://localhost:3100/static/js/bundle.js:27169:17)
    at ReactCompositeComponentWrapper._constructComponent (http://localhost:3100/static/js/bundle.js:27160:20)
    at ReactCompositeComponentWrapper.mountComponent (http://localhost:3100/static/js/bundle.js:27063:22)
    at Object.mountComponent (http://localhost:3100/static/js/bundle.js:19468:36)
    at ReactCompositeComponentWrapper.performInitialMount (http://localhost:3100/static/js/bundle.js:27246:35)
    at ReactCompositeComponentWrapper.mountComponent (http://localhost:3100/static/js/bundle.js:27133:22)
    at Object.mountComponent (http://localhost:3100/static/js/bundle.js:19468:36)
    at ReactCompositeComponentWrapper.performInitialMount (http://localhost:3100/static/js/bundle.js:27246:35)
    at ReactCompositeComponentWrapper.mountComponent (http://localhost:3100/static/js/bundle.js:27133:22)
    at Object.mountComponent (http://localhost:3100/static/js/bundle.js:19468:36)
    at ReactDOMComponent.mountChildren (http://localhost:3100/static/js/bundle.js:26268:45)
    at ReactDOMComponent._createInitialChildren (http://localhost:3100/static/js/bundle.js:23295:33)
    at ReactDOMComponent.mountComponent (http://localhost:3100/static/js/bundle.js:23114:13)
    at Object.mountComponent (http://localhost:3100/static/js/bundle.js:19468:36)
    at ReactDOMComponent.mountChildren (http://localhost:3100/static/js/bundle.js:26268:45)
From previous event:
    at new DrizzleContract (http://localhost:3100/static/js/bundle.js:69583:27)
    at Drizzle.getContracts (http://localhost:3100/static/js/bundle.js:69469:58)
    at http://localhost:3100/static/js/bundle.js:69450:17


texts: Geth is not generating an IPC file, cannot attach

texts:
I'm new to Ethereum so I am doing a course on it to learn how to develop decentralized apps.

I have Geth 1.6.1 and Mist.

According to the course I created a directory 'chaindata', then when starting geth --datadir chaindata it gives me this output:

MacBook-Pro-van-Lise-Lotte:Ethereum Lise-Lotte$ geth --datadir chaindata
WARN [05-28|12:07:53] No etherbase set and no accounts found as default
INFO [05-28|12:07:53] Starting peer-to-peer node               instance=Geth/v1.6.1-stable-021c3c28/darwin-amd64/go1.8.3
INFO [05-28|12:07:53] Allocated cache and file handles         database=/Users/Lise-Lotte/Documents/Jairo/Ethereum/chaindata/geth/chaindata cache=128 handles=1024
INFO [05-28|12:07:53] Initialised chain configuration          config="{ChainID: 15 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: <nil> EIP155: 0 EIP158: 0 Engine: unknown}"
INFO [05-28|12:07:53] Disk storage enabled for ethash caches   dir=/Users/Lise-Lotte/Documents/Jairo/Ethereum/chaindata/geth/ethash count=3
INFO [05-28|12:07:53] Disk storage enabled for ethash DAGs     dir=/Users/Lise-Lotte/.ethash                                        count=2
INFO [05-28|12:07:53] Initialising Ethereum protocol           versions="[63 62]" network=1
INFO [05-28|12:07:53] Loaded most recent local header          number=0 hash=2fb1a7…f0181a td=131072
INFO [05-28|12:07:53] Loaded most recent local full block      number=0 hash=2fb1a7…f0181a td=131072
INFO [05-28|12:07:53] Loaded most recent local fast block      number=0 hash=2fb1a7…f0181a td=131072
INFO [05-28|12:07:53] Starting P2P networking
INFO [05-28|12:07:55] RLPx listener up                         self=enode://a84c9a13453cc4639dabc8e82729fa51f9165978682471053966f5e328b31acc4a81490b20d8e0db6a99769ce6543c910cb4531907bec94f7072a7e8c3d880a0@[::]:30303
INFO [05-28|12:07:55] IPC endpoint opened: /Users/Lise-Lotte/Documents/Jairo/Ethereum/chaindata/geth.ipc

But the geth.ipc file is never created so I can not attach. I searched for similar answers but I couldn't find one that works.

Please help, I'm hoping to continue my course ;)


texts: NodeJS + Web3 + Infura Ropsten - Error: Invalid JSON RPC response: ""

texts:
I have problem with invalid response to ethereum from BE NodeJS app.
I got error like:

Error: Invalid JSON RPC response: ""

Below I'd attached my simple code for testing connection.

const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider(providerUrl));
const contract_web3 = new web3.eth.Contract(abi, contractAddress);

console.log("Config Data: \n", providerUrl, "\n", config.privateKey, "\n", contractAddress);

contract_web3.methods.getDocuments().call((err, result) => {
    if (err) {
        // handle error here
        console.log("Test call error: ", err);
    }
    else {
        console.log("Test call: ", result);
    }
})

I'v readed about HDWalletProvider, but I havent dive in it yet.

Regards!


texts: Cheers, please don't laugh to my stupidity. I need some extra space on my SSD and firstly checked what takes the most of the space. Almost at the top were files under Ethereum Chaindata. I stupidly went in and deleted most off them...as I thought they were history, which don't really matter. Well, I can't sync my Wallet anymore. Please help. Thanks a lot.


texts: Truffle debug on function call show null variables

texts:
With a truffle version of 4.1.0, using truffle debug on a call of my contract function below:

function Deposit (uint256 timeout, bytes32 hash, address recipient)
        public payable returns (uint256)
    {
        require( timeout >= now );
        require( timeout < (now + MAX_TIMEOUT) );
        require( msg.value > 0 );

        var lock_id = m_ctr;
        m_ctr += 1;
        m_locks[lock_id] = LockState(timeout, hash, recipient, msg.sender, msg.value);

        OnDeposit(lock_id, recipient);

        return lock_id;
    }

as (via geth):

Deposit(1521568000, '0xffcec51439a3a7195c8f5c32732bfc2bf66688a13c1d52fc9d5e548f4733b5c1,', "0x0e0060f625534293d280547bd8a782da45333b95", {from: "0x4a7268f1982acd8e405e2d8d26075480e0d6fe8f", gas:900000, value: 1})

the debug console reveals that the second argument hash is null.

5: function Deposit (uint256 timeout, bytes32 hash, address recipient)
6:     public payable returns (uint256)
                                ^^^^^^^

debug(testnet1:0x2b899125...)> v

      lock_id: undefined
      timeout: 1521568000
         hash: null
    recipient: '0x0e0060f625534293d280547bd8a782da45333b95'
             : 117
  MAX_TIMEOUT: 0
      m_locks: null
        m_ctr: 0

Considering that there is no such thing as null in Solidity, I am confused at the reported value of the hash argument. More importantly, passing a value for this parameter has resulted in it being reported back as null by truffle debug.

It has received the first argument timeout and third argument recipient correctly as expected so the call itself seems to be well-formed.

Another variable also seems to be reported back as null whilst another is undefined. What are the differences between them and why have they been assigned different 'values'?

Why is my hash argument being interpreted as null when being passed appropriate values?


texts: Are there known congested periods in the Ethereum blockchain history?

texts:
I've been building the full blockchain with geth.  I resorted to using ZFS snapshots to recover from repeated failures caused by corrupted blocks according to geth reports.  Whenever unrecoverable corruption was detected, I issued rollback in the hope that the corruption was recent and the process could continue.  This worked for awhile but ultimately failed, and I assume this is because very early blocks are corrupt.  So I've moved geth to another system in the hope that unreliable RAM was the cause of the trouble.  I'm considering building a system with ECC RAM.  But that is a side issue.  To my question:

Now I'm observing progress on system 3 which seems to be doing well, albeit more slowly on HD instead of SSD as before, but I'm curious about a peculiarity seen with each sync attempt:

The snapshots below are named according to the block number that was complete at the time of the snapshot.  I have adjusted the snapshot interval periodically so as to evenly space them out in terms of perceived work completed, or essentially, time.  The curious part is the wildly varying ratios between of blockchain blocks logged vs. apparent space modified in the filesystem.

As most readers probably know, like most snapshot support, ZFS uses copy-on-write to preserve modified disk blocks.  The space allocated to a snapshot is thus proportional to the dispersal of modification activity since the snapshot.  This can be seen in the USED column of the zfs list report:

root@merle:/blockchain/eth# zfs list
NAME                             USED  AVAIL  REFER  MOUNTPOINT
naked3t                          586G  2.06T    19K  /naked3t
naked3t/blockchain               108G  2.06T    19K  /blockchain
naked3t/blockchain/eth           108G  2.06T  27.8G  /blockchain/eth
naked3t/blockchain/eth@2278805  2.56G      -  5.63G  -
naked3t/blockchain/eth@2598969  14.4G      -  24.5G  -
naked3t/blockchain/eth@2636231  14.4G      -  24.7G  -
naked3t/blockchain/eth@2675264  18.8G      -  25.0G  -
naked3t/blockchain/eth@2680721  20.9G      -  26.4G  -
naked3t/blockchain/eth@2682986  3.38G      -  27.8G  -

Note that geth apparently raced through ~37K blocks and required 14.4G of space to maintain the prior snapshot.  But later, it slowed to a crawl, and I triggered a snapshot after only 2300 blockchain blocks, yet 20.9G had been consumed in maintaining the prior state to that point.

My questions are about what accounts for the differential, and to further explain, if this is predictable, as if there is something about the activity in certain period of the history that causes this, or if it is non-deterministic and I can expect to see different behavior if I were to restart the process.  FWIW, the current slow period in process is around November, 2016.

Insights?


texts: The Ethereum light node is synced by geth, but when we tried to sync it we lost ssh connection. We assumed that while it is syncing it is impossible to connect via ssh to computer. If anyone has any idea why this should happen. We also have the most ports closed. The open ports are just ssh, http and one more. This problem happens just in one computer, at other is not possible.


texts: How to Deploy and call a contract? Address needed beforehand?

texts:
I want to store a string from a script in node.js to blockchain.
This is the contract.

pragma solidity ^0.4.0;

contract SimpleStorage {
    string storedData;

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

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

In order to deploy the contract on net(in my case testnet) I need to create an instance of the contract. In order to create an instance and deploy it I need 3 things: web3 library, abi and address of contract:

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
abi = JSON.parse(....)  //==> I got abi following this tutorial(https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2)
StoreContract = web3.eth.contract(abi);
contractInstance = VotingContract.at('CONTRACT ADDRESS');
//And now I can use contract function
contractInstance.set(string data)

So my question is....How do I get the contract address???


texts: How can we parse and deal with BigNumber (BN) args in Solidity events?

texts:
In the past, web3 events published numeric events like so:

BigNumber { s: 1, e: 17, c: [ 1000 ] } }

Now with web3.js 1.0, big numbers come down as objects like this:

 <BN: de0b6b3a7640000>

The problem here is that if we're collecting events for troubleshooting later, this would be indecipherable. The only solution I can think of is having some code in the event consumer convert the number before storing the event somewhere like so:

web3.utils.fromWei(new web3.utils.BN(receipt.logs[0].args.amount))

Does anyone else have any other ideas?


texts:
I have a few questions regarding ETH and token storage.

Is it a good practice to store ETH on smart contract address in case only owner is authorized to withdraw it?
When deploing smart contract, do I have to send all available tokens to some external wallet address in my constructor function? Or I can leave tokens on smart contract address and send them to clients from contract address during crowdsale?
Summerizing the above two questions, how to distinguish balances of ETH and tokens on smart contract address? I mean does:
address(this).balance returns ETH quantity and balances[address(this)] returns token quantity? Or they are similar?


texts: Is block's timestamp current block's or previous block's timestamp?

texts:
When I call function giveTime, is the time stamp "now" from the block where my call is mined or from the previous block?

contract Time {
  uint time;

  function giveTime() {
    time=now;
  }

  function Timestamp() constant returns (uint block_time) {
    block_time=time;
  }
}


texts:
If I want to find out which address a name resolves to, say example.eth, does this mean I need to send a transaction to the appropriate ENS contract for resolution?
Does running a local node reduce this to a call, thereby eliminating gas cost?
Are there any cached resources for lookups and resolutions?


texts: Contract deployed successfully to Ganache via Truffle, fails to deploy on live network

texts:
I basically followed this Zeppelin crowdsale tutorial, just changed the names of the contracts. I was able to successfully deploy on a local Ganache, but then when trying to deploy to the live ethereum network it fails on invalid address, apparently raised by migrating 1_initial_migration.js, which looks like this:

var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

and Migrations.sol looks like this:

pragma solidity ^0.4.17;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function Migrations() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

Here is a screenshot from the terminal where truffle migration fails:

How is it possible that I can deploy to Ganache but not to the live network? Am I doing something wrong? Any suggestions?


texts: Running Wallet 0.8.6 with Parity 1.3.8 [Low # peers, Low speed]

texts: Wondering why my blocks are processing so slowly. Peers ranging from 0 to 10. About 45,000 blocks behind... Processing 1 block about every 5 seconds.


texts: How do you connect to a node from the server side of a meteor app

texts:
This is the command I am using to run the node (a private testnet)

geth --networkid 420 --nodiscover --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpcapi="db,eth,net,web3,personal,web3" --rpccorsdomain "*" console

This is the code I am using to connect to the node on the server side of my app

Meteor.startup(() => {
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

If I try web3.isConnected() on the server side it returns false

I also tried console.log(web3.net.listening) as recommended by the comments but this gave the error:

TypeError: XMLHttpRequest is not a function

I can connect fine on the client side and web3.isConnected() returns true

I am running the app locally on my computer


texts: Is it possible to install 2 geth ethereum nodes with one external ip?

texts: I want to install 2 nodes in one local network, will I succeed? and what is needed for this?


texts: What are the command line editing keys in geth's console

texts:
What keys are available for editing the command line in geth console?

This is a follow-on question from the answer to How to enable vi mode in geth console? (readline's inputrc not honored) and Is there something like `help` or `dir` on the geth console?.


texts: node.js leads to "Resource temporarily unavailable" when repeatedly using the web3 API

texts:
When using the web3 API in a loop, in node.js, after a certain number of iterations the script freezes, and in any other terminal I get a:
-bash: fork: Resource temporarily unavailable
error when executing any shell command. As soon as I kill the script, shell commands start working again.

As a simple test, the following script leads to this issue:

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

for (var i = 0; i < 10000; i++) {
  console.log("Start: " + i);
  console.log(web3.eth.getBalance("0x0000000000000000000000000000000000000000"));
  console.log(web3.eth.getCode("0x0000000000000000000000000000000000000000"));
}

after 225 iterations (so the last output lines shown before it freezes are):

Start: 225
{ [String: '7.221712092140691731494e+21'] s: 1, e: 21, c: [ 72217120, 92140691731494 ] }

This is running on a mac, against a geth node, with "web3": "^0.18.4".

Any help / advice / better patterns for this type of thing, much appreciated!

Thanks,
Adam


texts: Importing in SOLC to deploy smart contract

texts:
I don't run an Ethereum framework like Truffle and I want to deploy a smart contract using infura node.

The smart contract is very simple:

pragma solidity ^0.5.2;

import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";

  /**
  * @title ACoin is basic ERC20 Token
  */
contract ACoin is ERC20, ERC20Detailed, Ownable{

  uint256 public initialSupply = 100000000000;
  /**
  * @dev assign totalSupply to account creating this contract
  */
  constructor() public ERC20Detailed("ACoin", "ACO", 7) {

   _mint(msg.sender, initialSupply);

 }

}

My compile script should be working fine:

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

const ACoinpath= path.resolve(__dirname, 'contracts', 'ACoin.sol');
const source = fs.readFileSync(ACoinpath, 'utf8');

console.log(solc.compile(source, 1).errors);

module.exports = solc.compile(source, 1).contracts[':ACoin'];

The issue is that solc " doesn't know what import means" and I'm getting this error:

  [ ':3:1: ParserError: Source
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"
  not found: File not supplied initially.\nimport
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";\r\n^--------------------------------------------------------------------------------------------^\n',   ':4:1: ParserError: Source
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol"
  not found: File not supplied initially.\nimport
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol";\r\n^--------------------------------------------------------------------------------------------^\n',   ':5:1: ParserError: Source
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"
  not found: File not supplied initially.\nimport
  "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";\r\n^----------------------------------------------------------------------------------------------------^\n' ]

I looked into OpenZeppelin repo where I'm told the solution to my problem. An npm install openzeppelin-solidity & import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol" later, the problem still persists:

  [ ':3:1: ParserError: Source
  "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol" not found:
  File not supplied initially.\nimport
  "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";\r\n^-------------------------------------------------------------^\n',

Is there anything I can do without using Truffle?

Important to mention: the smart contract provided will work in Remix


texts: I would like to save daily prices of about 3000 items (about 2mb in size) on a public blockchain, and I would like to create a DAPP to retrieve the data. I am considering saving the data on Ethereum. I checked this link which said it would cost around $76000 to save about 1 GB worth of data, which is very expensive for me. Is Ethereum the right choice for this type of use case? Or Should I consider something else? Any suggestions?


texts:
Why my transaction is not mined on Ethereum Ropsten? https://ropsten.etherscan.io/tx/0x383b129d87cd6991df7701d3e4a018f8e3dd02d973aea5a8ea53ab5791146614

It shows up on https://ropsten.etherscan.io/txsPending?p=5 as stuck. Having GasLimit of 4700000   and GasPrice of 101 Gwei, why it is still not mined?


texts: The Shareholder Association doesn't compile

texts:
I tried the official Shareholder Association example from ethereum.org in MEW using a private blockchain and I got a warning that prevents contract from compiling.
The warning is ` Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.
        string description;
        ^----------------^
,

`

If I change it to string storage descripton I get another error:

 Expected identifier, got 'eth_compileSolidity'
    string storage description;
           ^

I am using the latest version of MEW.

How can I solve this?

Thank you.


texts:
It seems that there is an issue with handling of contract events and I am not sure if it is at the EVM level or just web3js.

I have 2 contracts "SomeCoin" and "SomeConcert". Both contracts emit "Transfer" event when there is a transfer of item from one address to another. For "SomeCoin" the object of transfer is a coin/token, for "SomeConcert" the object of transfer is concert tickets (that is priced in "SomeCoins").

When I called "SomeConcert" method to purchase tickets, the logic will transfer some "SomeCoins" from my address to the "SomeConcert" address. All is well and good except for the event handling. I saw 2 events emitted "Buy" event emitted from "SomeConcert" contract and "Transfer" event from "SomeCoin" contract. If I renamed the "Transfer" event in "SomeCoin" contract to "TransferCoin" then I will only see the "Buy" event.

So, apparently either web3 or the underlying layer confuses the events emitted by inner layer contract with the outer layer contract. At least this is the conclusion I have come to.

Is this a web3js bug? Is there anything I missed out in the event handling that might have prevented the confusion. The code I have for event handling is rather standard

...
      return someConcertInstance.buyTickets(3, {from: customer1});
    }).then(function(receipt) {
      assert.equal(receipt.logs.length, 1, "should have received 1 events for buy-ticket)");
      assert.equal(receipt.logs[0].args._numberOfTickets, 3, "Number of tix bought must be 3");

The test case failed on the first assert and I found out 2 events are emitted (transfer and buy).


texts: Can fiat money like USD be transferred via smart contracts in Ethereum?

texts:
I am studying about Ethereum smart contracts and how they are being used to transfer tokens. I would appreciate it if you could provide a clarification on the below issue.

Suppose User A needs to send some amount of USDs ( or any fiat money ) to User B. Can this use case be resolved using smart contracts in Ethereum? I understand that tokens can be transferred instead of fiat money, but is there a way to include fiat money as well in a smart contract?

Thank you.


texts: Other ways of paying gas different than Ether?

texts:
I've been trying to transfer my BATs from my ledger to the exchange address, only to discover that I haven't enough coins in the ETH parent wallet to pay the gas ..
I had some ETHER until a couple of weeks ago but I withdrew them to the exchange and now I am over..
now.. I don't want to buy ether at the moment since it's so expensive and transactions are too..
today network fees are not so expensive, but I still have to buy ETH, transfer ecc ..

so, as a rule, is there another way pay gas other than through ethereum coins?
couldn't I be able to just pay in BATs??
thanks


texts:
I would like to know what is the gas limit for other ERC-20 tokes like BAT, 0X, OMG
I undestand that for regular transactions in Ethereum the gas limit is 21000, is it the same for the rest of tokens mentioned?

I also want to know what other kind of transactions make the gas lime rise?


texts: Sign message (obtain v,r,s) inside Solidity

texts:
I'm trying to call an Exchange SmartContract which is POORLY designed/implemented and forces you to sign your own parameters instead of using msg.sender (and provides no alternative). <-- I've just seen its not poorly designed, they limit the contract to themselves... weird

I'm calling this Exchange from my own SmartContract.

Someone could tell me a way (if possible) to tell my SmartContract to sign some parameters? I can't sign from outside, because I don't have my SmartContract private key.

-Lets say I have "uint one, uint two, address three" and I want to get the "r,v,s" of those three parameters signed with my Smart Contract address (all this done using Solidity).

Thanks!,


texts:
Is it possible to use bcrypt hash function in a ethereum smart contract? Or only keccak is available?
Searching I got to this question, where the OP apparently assumes it's possible, but there is no confirmation or sample code that indicates such.


texts: Truffle console keep showing "undefined". Solved by rolling back to v4 stable

texts:
I have updated my truffle version to the latest v5.0.3. By running truffle version, I can get the following version statements.

Truffle v5.0.3 (core: 5.0.3)
Solidity v0.5.0 (solc-js)
Node v10.8.0

However, this update stops me from executing some tutorials that were supposed to work. Especially, the ZOS tutorial at https://docs.zeppelinos.org/docs/upgrading.html, when running commands myContract.x().toString() in Truffle Console. Instead of showing a numerical result, the console kept showing undefined. The same problem happened for the case of running myContract.s().

I am not sure whether the problem comes from a different use of cli command sets across versions. It took me hours to fix it. Therefore, if you encountered similar problems, I wish it can save you time.


texts: What changes to make in smart contract to comply with next constantinople hard fork

texts:
Constantinople hard fork in Ethereum is upcoming. So what are the changes we have to make in smart contract to comply with it?

I read this: https://www.coindesk.com/ethereums-constantinople-hard-fork-is-being-delayed-until-2019

https://ethereum.stackexchange.com/a/64216/38846

And other articles. But can not figure out, how it will affect current solidity smart contract development.

Any help appreciated. Thanks.


texts: Solidity Compile error: Identifier already declared

texts:
I'm trying to run my code but i get this error:
 Could not compile source code.

" Identifier already declared.
function addCar(string _make, string _model, unit _pricePerDay, uint _minRentalDay, uint _maxRentalDay) public onlyOwner{
^
Spanning multiple lines."

i don't understand because there shouldn't be a problem, Here's my function:

function addCar(string _make, string _model, unit _pricePerDay, uint _minRentalDay, uint _maxRentalDay) public onlyOwner{

make = _make;
model = _model;
pricePerDay = _pricePerDay;
minRentalDay = _minRentalDay;
maxRentalDay = _maxRentalDay;

Car newCar = cars[numofCars];
nameToKeys[name].keys.push(numofCar); //add the key to the name's keys

newCar.VechileOwner = msg.sender;
newCar.make = make;
newCar.model = model;
newCar.available = false;
newCar.pricePerDay = pricePerDay;
newCar.minRentalDay = minRentalDay;
newCar.maxRentalDay = maxRentalDay;

NewCar(numofCars,msg.sender);
ids.push(numofCars);
numofCars++;
}

Much appreciated.


texts: How many pending transactions can I create with the same nonce?

texts:
Recently I cancelled a pending transaction by resending an other transaction with the same nounce and a higher gas price in order to have the new transaction mined faster. This was useful in my case.

However is it not possible to spam the network by doing this ? What happens if I send thousands of transactions with the same nounce at the same time ? Will they stay in the queue until at least one is being mined ?


texts: Difference of using transfer vs _transfer in OpenZeppelin (same for dash functions)

texts:
In openzeppelin contracts in same cases we have 2 types of functions for the same functionality, one of them preceded by a dash symbol (_). That is the case of transfer(x, y, z)/_transfer(x, y, z) function.
I am aware that when I want to modify the behaviour if I inherit the function, I should use _transfer(x, y, z).
But what's the real difference? Because it happens in lot of functions, and I'm not really sure if I should use transfer(x, y, z) or _transfer(x, y, z).
So then, if I'm not gonna modify its original behaviour, should I use transfer or _transfer?
Thanks in advance


texts: How could I convert uint type to bytes type in solidity?

texts:
I want to convert uint type data to bytes type in solidity. I've found a answer about this which is like below.

function toBytes(uint256 x) public pure returns (bytes memory b) {
    b = new bytes(32);
    assembly { mstore(add(b, 32), x) }
}

But this doesn't work like what I thought. For example, if I put 0x0000000000000000000000000000000000000000000000000000000000000abc to the input value, I expected to have a return value which looks like this 0xabc0000000000000000000000000000000000000000000000000000000000000. But this function returns same as input value which is 0x0000000000000000000000000000000000000000000000000000000000000abc. How could I convert 0x0000000000000000000000000000000000000000000000000000000000000abc this to 0xabc0000000000000000000000000000000000000000000000000000000000000 this in solidity?


texts: TestRPC undeterministically throw "invalid opcode"

texts:
We have contract test suites running against TestRPC, it could fail the first run and succeed the consecutive second run. What can cause this weird behavior and how can I fix it?

The CI histories:

Failed: https://travis-ci.org/ethereum/ens/jobs/218813195
Successful: https://travis-ci.org/ethereum/ens/jobs/218814360

Thanks in advanced!


texts: What happens to currencies in mist if computer goes offlinei

texts: I downloaded Mist as my desktop storage, my question is what would happen if my computer goes offline or say we go move and my computer would stay offline for a long period of time. I am new to the cryptocurrency and blockchain world, thank you for any input


texts: Optimal way of waiting for transactions to be mined in geth

texts:
I'm currently checking if a transaction has been mined using the following function (using web3.js):

function waitForTx(tx_hash) {
        var result = null;

        // This is not really efficient but nodejs cannot pause the running process
        while(result === null) {
            result = web3.eth.getTransactionReceipt(tx_hash);
        }
    }

Is there a way to avoid the blocking loop?


texts:
In JasmineJS and other Unit testing frameworks, there is usually a focus feature which works like this using fit:

fit('Crowdsale contract - vault works correctly', function(done){
});

if I want to skip the test I'd use xit
Is there a way in truffle to do it? (Focus and skip tests)


texts:
I've typed targetgaslimit option, however it has returned the following error.

enter preformatted text here flag provided but not defined: -targetgaslimit

The following is the command.

$ geth --networkid "11" --nodiscover --datadir "hoge" --genesis "/hoge/myGenesis.json" --port "1234" --mine --targetgaslimit "4712388" --unlock myCoinbase --rpc --rpcaddr "localhost" --rpcport "8545" --rpccorsdomain "*" console

Is the targetgaslimit option eliminated?


texts: ETH transaction from Jaxx wallet to Binance is still unconfirmed...

texts:
Transaction ID 0xa6167ff0addb9e638ac5fc7406d9c238d46c976c37867e6c8700d5cdd3376511.  It's been an eternity, considering how quickly transactions process normally.

Is there network congestion right now?  Did I...do something wrong?


texts: Can't use Uniswap contract function 'swapExactTokensForETH'

texts:
When using Uniswap function swapExactTokensForETH() I get the following error:

'TransferHelper: ETH_TRANSFER_FAILED'

Contract code:
pragma solidity 0.8.0;

import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";

contract test {

address internal owner;
address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ;
IUniswapV2Router02 private uniswapRouter;

constructor() {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
    owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
    }

//owner
modifier isOwner(){
    require(msg.sender == owner, "Caller is not owner");
    _;
    }

function EthToTokens(address tokenAddress, uint EthInAmount, uint TokenOutAmountMin, uint deadline) public payable {
    uniswapRouter.swapExactETHForTokens{ value: EthInAmount }(TokenOutAmountMin, getPathForEthToToken(tokenAddress), address(this), deadline);
    }

function TokensToEth(address tokenAddress, uint EthOutAmount, uint TokenInAmount, uint deadline) public payable {
    IERC20 token = IERC20(tokenAddress);
    token.approve(UNISWAP_ROUTER_ADDRESS, TokenInAmount);
    uniswapRouter.swapExactTokensForETH(TokenInAmount, EthOutAmount, getPathForTokenToEth(tokenAddress), address(this), deadline);
    }

function getPathForEthToToken(address tokenAddress) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = tokenAddress;
    return path;
    }

function getPathForTokenToEth(address tokenAddress) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = tokenAddress;
    path[1] = uniswapRouter.WETH();
    return path;
    }

function sendEther() public payable{
}

function withdraw(address payable _address, uint withdrawAmount) public payable isOwner{
    _address.transfer(withdrawAmount);
}

}


texts: What to do to enable Websocket Steam on Ethereum Node Server for NodeJS endpoint API

texts:
I have Ethereum node by providing ws and http port access through windows server, I filter the data and get the data I want.I created the node.js api endpoint to provide this data, so I can apply my filters and access only the data I need thanks to this api. My system works fine when I run my project through the browser, I can see the output as HTTP as json output.
I want to create websocket live steam feature for this api ws: // localhost what can I do for this please inform me which shows the correct way (which npm I will use - I just want it to push the function I filtered in my project) Thanks a lot
my goal is to make this api project connect with WS:// ip in a different project. so why ı need websocket it can be listen this api steam...


texts: System requirements running blockchain application

texts: From an IT/infrastructure perspective (im not a developer) what are the system requirements to run a fully functioning blockchain application i.e based on ethereum for a small - medium sized business. How do you host the application i.e AWS? I will be starting as sys admin so will need to deploy everything for the company. Is there a guide available where i can find this. Thanks


texts: How to export transactions into a CSV file

texts: Is there a simple way to export all transactions related to a specific account/smartcontract to a CSV or some other plain text format?


texts:
I am looking for a way to create a contract that reacts according to User Input. For my purpose it would be awesome to somehow "wait for a users input" and as soon as this is done automatically continue by executing a contracts function according to the user input. Now I know that "waiting loops" arent possible in functions because the transaction would simply run out of gas.

Is there any other way to solve this problem?
The pattern I want to use is: "Execut contract A, during A ask User for input, continue A automatically as soon as the contract receives the users input"

Many thanks!

Edit, More general explanation of the problem:
Contract A provides a function. If a User wants to interact with the contract he call the function and gives the required arguments. At some point the function might ask the user for some additional information like an additional Uint-Value or String-Value. Now what I want is that the original contract function resumes doing its computation as soon as the user gives additional input

Any ideas for a pattern like this?


texts: How to convert BigInteger to a decimal in Nethereum / Web3

texts:
I need to read and write some Uniswap Transactions using Nethereum/Web3.  The uniswap methds expect BigInteger data types, but the UI expects so called Display unit types, which essentially convert the BigInteger type into a decimal, using the number of decimals of the ERC20 token contract in question.
If I know that the token I'm working with has 9 decimals and the value is given is 12356789123456, how do I convert that number to one with 9 decimals? I.e. shift the decimal point to the left 9 spaces?
Similarly, if a user enters 0.01 BNB, how do I convert that to a BigInteger if I know that BNB has 18 decimal points? I.e. shift the decimal point to the right 18 spaces?


texts: Deploying Migrations using network 'rinkeby' - insufficient funds for gas * price + value

texts:
I'm connected to the "Rinkeby" network on MetaMask. I've imported the private key into Geth. Thereby, I unlocked the account using geth --rpc --networkid 4 --unlock <account_address>. Thereafter, I'm trying to deploy my smart contract using truffle. I'm using the following command to deploy the migrations: truffle migrate --reset --network rinkeby --compile-all. But I receive the following error -

  Error: insufficient funds for gas * price + value

Inside truffle.js, I've configured to connect to Rinkeby as follows -

 host: "localhost",
 port: 8545,
 from: "<account_address>",
 network_id: "4",
 gas: 4000000,
 gasPrice: 20000000000

I have 3 ETH in my account from the Rinkeby Authenticated Faucet.

Where exactly am I going wrong?


texts: how does contract cost less gas in structs?

texts:
I have a couple of questions.

we have int types as uint8, uint16, uint32, etc. I read that :

Normally there's no benefit to using these sub-types because Solidity
reserves 256 bits of storage regardless of the uint size. For example,
using uint8 instead of uint (uint256) won't save you any gas.

So If I type directly in the contract as state variable something like this:

uint8 test1;
uint32 test2;
uint test3;

Why won't uint8 test have less gas consumption wherever I use it than uint32 test2 ? I am asking because with uint8 test1 , I use less storage space.

Let's say I use struct differently.

// way1
struct Person {
  uint8 test1;
  uint32 test2;
  uint8 test3;
}

// way2
struct Person {
  uint8 test1;
  uint8 test2;
  uint32 test3;
}

Why would the second way consume less gas than the first one ? If we look at the both struct, they both consume the same amount of storage, but still it's said way2 is gonna be much better for less gas consumption . Why ?


texts: How does ethereum alarm clock work if you can't 'wake up'?

texts:
Ethereum Alarm Clock.

This service claims that it itself is implemented as a smart contract, but how is that possible? I thought the whole reason it existed was because A contract can't wake up itself, but isn't that what this alarm clock has to do to run/call other contracts?


texts: How may I find the byte code of an arbitrary contract? Preferably using a website and not writing my own client.


texts: I want to ask how transactions are validated in hyperledger fabric? To explain this I would like to add, as per my understanding, hyperledger fabric is permission project and even only two participants can make a transaction. So in this case (two person are making any transaction) anyone can make changes on later stage so i am confuse that how this is going to work with effecting immutability of blockchain?


texts: When exactly address datatype should be used?

texts:
I have been scratching my head in understanding the situations and scenarios when address datatype should be used. I have seen Voting contracts as below

contract Ballot {
    // This declares a new complex type which will
    // be used for variables later.
    // It will represent a single voter.
    struct Voter {
        uint weight; // weight is accumulated by delegation
        bool voted;  // if true, that person already voted
        address delegate; // person delegated to
        uint vote;   // index of the voted proposal
    }
}

Here why is address datatype used for person, couldn't we use string or bytes?


texts: my_contract,estimateGas() crashes and "eth_estimateGas" returns incorrect value

texts:
I'm trying to estimate Gas for a contract method (both using parity and geth - tried web3py and web3js). Contract is deployed and proven to be working.

When I use:

estimateGas and geth (providing: to, from, data I get gas > 6 700 000, which seems to be an error as it's the whole available gas for the current block
estimateGas and parity (providing: to, from, data I get the following error: Internal("Requires higher than upper limit of 1000000000000")
JSONRPC and trace_callreturns around 49000 (parity)
JSONRPC and method eth_estimateGas returns 77858 (both for parity and geth)
however when I actually create a transaction it consumes much more Gas Used By Txn: 108140 - which doesn't match the number returned by eth_estimateGas - if I click trace on Etherscan (parity/geth) - gas from the traces matches 77858, however 108140 is used to process the transaction.

Am I missing something here? How can I calculate the gas properly? There is nothing unusual in the contract - constant number of steps. I believe that I should be able to even calculate this manually with a pen and paper.

I've tried a few transactions and gas used by txn is always higher from 30000 to 32000 units than estimated gas.


texts: how to use getPublicEncryptionKey from eth-sig-util in a Dapp

texts:
The metamask repo includes  small collection of ethereum signing functions:
https://github.com/MetaMask/eth-sig-util

There is a function (not exposed in readme section) named getEncryptionPublicKey which expects a private key. How is this supposed to be used, as we can never get a private key in our dapp.
This functionality is based on that: https://github.com/ethereum/EIPs/pull/1098
I would like to use this functionality.


texts:
This question has probably been already answered somewhere else but I didn't find anything on the internet so I'm asking here.
I wonder how clients such as Geth query the blockchain to get specific information like a transaction or some address' balance. If you search by transaction hash you can get anything you're looking for in a couple of seconds, but how does the client actually fetch data from the blockchain? I know Ethereum is backed by LevelDB, but I still don't get how it is possible to skim through the entire blockchain is such little time.
Maybe I'm getting something wrong, thanks in advace!


texts:
I've a service and I'm accepting Bitcoin using Bitcoind. I want to accept Ethereum too by running an ethereum node.

I want to generate an address for each customer, which RPC command should I call? When I assign a user with a new address in my DB, I want to listen for new transactions.

I'm asking this because I couldn't found a documentation or tutorial about this.


texts: how to use truffle to read state value of a smart contract

texts:
I'm a newbie.

I have following dummy contract

contract A{

uint public test = 6;
address public myaddress;
uint public dummy;

/**
* The logs that will be emitted in every step of the contract's life cycle
*/
event MyEvent(address myaddress);
event ReadEvent(address myaddress, uint dummy);

/**
* The contract constructor
*/
constructor() public {
    myaddress = msg.sender;
    emit MyEvent(myaddress);
}

function myF(address sender, uint value) internal {
    require(sender == myaddress );
    dummy = value;
    emit ReadEvent(sender, myaddress);

}

function run() public payable{
    myF(msg.sender, msg.value);

    /*SendMiles();*/

}
}

I then compile it and migrate using truffle. After I start a truffle console on a development network and do the following:

A.deployed().then(inst => { AInstance = inst })

account0 = web3.eth.accounts[0];

AInstance.run({from: account0, value: 5});

I then get a transaction number '0xa72b03232f5028332411d7f05cf47248616aab96d982ce9a7b147a00642db405' on glinche.

Two questions:
1. How can i get the contract variables value mainly for test, myaddress and dummy for transaction '0xa72b03232f5028332411d7f05cf47248616aab96d982ce9a7b147a00642db405'

How can I get those values in a more complex format like json?

I tried the web3.eth.storeat and A.at('0xa72b03232f5028332411d7f05cf47248616aab96d982ce9a7b147a00642db405') and it didnt work in both cases

thanks in advance;


texts:
Is it possible to use a ENS name as an address in solidity, instead of having to use the usual long address?

Example:

address public _address = myname.eth;


texts: Not able to create second geth node on the same machine

texts:
I am trying to add a peer Geth node on the same machine using the link
https://github.com/ethereum/go-ethereum/wiki/Setting-up-private-network-or-local-cluster
However, getting chainId which is wrong.

I have the following folder structure:

Blockchain

datadirone
datadirtwo
logs
myGenesis.json

myGenesis.json has following code:

{
  "config": {
  "chainId": 192,
  "homesteadBlock": 0,
  "eip155Block": 0,
  "eip158Block": 0,
  "byzantiumBlock": 0
},
"difficulty": "400",
"gasLimit": "2000000",
"alloc": {
    "<account>":{
         "balance":"1000"
 }
}}

I created my first node using command:

geth --datadir="./datadirone" -verbosity 6 --ipcdisable --port 30301 --rpcport 8101 console 2>> ./logs/01.log

In the response , I could see proper chainId as 192.

However, when I create the second geth node using command:

geth --datadir="./datadirtwo" -verbosity 6 --ipcdisable --port 30302 --rpcport 8102 console 2>> ./logs/02.log

It starts but with wrong chainid as 1.

What am I missing ?


texts:
how can I get the data of my erc1155 on the front/backend? I don't know which libraries and which functions to use?
Thank you


texts: How to transfer ether from one account to another using EthereumJ

texts: For testing purpose in test network we are creating account dynamically using ethereum java (EcKey). I have an account that contains enough ethers. How can i transfer ether from the source account to the account newly created using ethereum java. Please suggest.


texts: Not able to decode the input data from transaction using web3j

texts:
I am creating transactions using web3j and passing some private data in that transaction. The transaction is also getting mined . I have subscribed to the mined  blocks, where I am fetching the transactions added in the mined block. I want to retrieve the input data passed earlier, but unable to get it. Please help me here.

Code for transacting using web3j:

RawTransactionManager rawTransactionManager =  new RawTransactionManager(web3j ,credentials,100,1000 * 15);

EthSendTransaction send = rawTransactionManager.sendTransaction(gasPrice, Transfer.GAS_LIMIT, toAddress, "<some private data>", BigInteger.valueOf(1));

String hash = send.getTransactionHash();

I also get the hash  properly. Then, I subscribed to the blocks as follows:

Subscription subscriptionToBlocks = web3j.blockObservable(true).subscribe(block -> {
        List<TransactionResult> transactions = block.getBlock().getTransactions();
        if(transactions.size > 0){
            transactions.forEach(tx -> {
                  EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx.get();
                  System.out.println("transaction data:"+transaction.getInput());
        }

But this results in hex string, however, i want it decrypted again to process it further. Let me know how can i get the original data that was sent


texts: Find exact gas limit requirements for executing fallback function logic

texts:
I have a certain function logic coded for fallback function. This logic also contains some delete operations of storage variables (delete storeVarX;) due to which there might be some gas being refunded. Now the problem this is creating is, when i check the gas used by the fallback function in ethscan, it shows as 29,349. But allocating 30,000 gas or even 50,000 gas units to execute this function raises an [Out of gas] exception.

is there a way I can estimate gas consumed by fallback function, excluding the gas refund due to delete operations?


texts: Get to and from address using Transaction hash

texts:
How can I get only to and from addresses from a transaction Hash using Web3.
I am unable to get details of to and from using web3.eth.getTransaction() method. Please help!!


texts: What's so special about the .call() function?

texts:
All that the docs have to say about it is that it "lets the Ethereum network know we're not intending to persist any changes." So I get that it's used when not conducting a transaction.

So, I decided to test this:

truffle(development)> gc.then(function(instance){return instance.returnGreeting.call()})
'Hello, Joe'
truffle(development)> gc.then(function(instance){return instance.changeGreeting.call('threes a charm')})
[]

I thought it needed gas in the latter, so I tried but respectively got

truffle(development)> gc.then(function(instance){return instance.call.gas(10000)(bytes4(sha3("changeGreeting(string)")),'threes a charm')})
TypeError: Cannot read property 'gas' of undefined

But then I noticed that the following methods returned the same value, with no apparent difference.

truffle(development)> gc.then(function(instance){return instance.returnGreeting()})
'testing444'
truffle(development)> gc.then(function(instance){return instance.returnGreeting.call()})
'testing444'

To me, it's as useful as adding the keyword public to functions or fields: It only has semantic value. Where's the utility behind it?


texts:
I am trying to deploy a contract on testrpc using web3.js,

contract deploys fine when I deploy it from remix, it uses roughly the same amount of gas as the estimate.
However, when I try to deploy the same contract using web3.js, I keep running into "out of gas" error, even though I am supplying 5x the gas estimate.

I am obviously making some mistake in my deployment script...but I have gone over the script and can't spot the problem....some help from a knowing hand would be much appreciated

let source = fs.readFileSync('./xyz.sol', 'utf8');
    let compiledContract = solc.compile(source, 1);
    let abi = compiledContract.contracts[':Xyz'].interface;
    let bytecode = compiledContract.contracts[':Xyz'].bytecode;

    let bContract = new web3.eth.contract(JSON.parse(abi));

    let gasEstimate = web3.eth.estimateGas({data : bytecode});
    console.log(`GASESTIMATE : ${gasEstimate}`);  // <------------ returns value 120000

    let deployData = bContract.new.getData(name, choices, closesOn, min, {  data : bytecode, });

    let rawTx = {
        from: runENV.acctAddr,
        nonce: web3.toHex(web3.eth.getTransactionCount(runENV.acctAddr)),
        gasPrice: web3.toHex(web3.eth.gasPrice),
        gasLimit: web3.toHex(5*gasEstimate), // <------------- giving 5x gasestimate
        data: deployData,
    }

    let tx = new Tx(rawTx);
    tx.sign(runENV.privateKeyBuffer);

    let serialzedTx = tx.serialize().toString('hex');

    web3.eth.sendRawTransaction( '0x' + serialzedTx, (err, res) => {
            if(err) { console.log(`Error  - ${err}`); }
            else { console.log(`Xyz contract deployed successfully ${res}`);     }
        }
    );


texts: After I browsed http://www.mininghwcomparison.com, I found some GPU that had a 100+ hashrate, to 250Mh/s. I checked many other sites, and I didn't see any GPU that goes over 50MH/s, so is this site legit ? Is there any hardware that has a 100+ hashrate ?


texts: How many The DAO recursive call vulnerability attacks have occurred to date?

texts:
The first identified The DAO recursive call vulnerability attack occurred on 17 June 2016, with the accounts identified in Which accounts are involved in mounting the recursive call vulnerability attacks on The DAO?.

How many other The DAO attacks have occurred to date?


texts:
I was reading solidity Docs and everything made sense until I got to this:

What are external observers? Is it clients listening for events or is it anyone who has access to web3 api?

For example, who can access and modify uint private x = 255; except the contract it's in?

In other words, how can one get the value stored in a private state variable?


texts: Calling method to return stored string results in error: The returned value is not a convertible string

texts:
I am trying out a very simple contract on the Rinkeby testnet. Pretty much as simple as it gets:

pragma solidity ^0.4.17;

contract Root {
    string rootHash;

    function set(string x) public {
        rootHash = x;
    }

    function get() public constant returns (string x) {
        return rootHash;
    }

}

It stores an ipfs multihash, and allows retrieving it.

The write part seems to work, using this code:
https://gist.github.com/pwrstudio/6c95043ae3bb6a9aef9734a3fc8469e7

I can see that the multihash is sent to the contract, encoded as hex:
https://rinkeby.etherscan.io/tx/0x4d7b98cf577d580168d24b1f61bcbc60f3f919c751624793e83dd10191ebba98

But when calling the get function I get this error:

ERROR: The returned value is not a convertible string

Relevant js code:

return new Promise((resolve, reject) => {
  const rootContract = new web3.eth.Contract(abi, CONTRACT_ADDRESS)
  rootContract.methods
    .get()
    .call()
    .then(res => console.log(res))
    .catch(e => console.log(e))
})

Any pointers on what I am doing wrong much appreciated!


texts:
I'm using Java (web3j). I have some users and I want to give address to each user. How to generate new address in an ethereum wallet? For example I can generate lots of address from bitcoin wallet. Is it possible to generate new address in one ethereum wallet seems like bitcoin?

If it isn't possible then how can I assign different address to users? Must I create new wallet for every user and save them to a directory? Thanks.


texts: invalid arrayify value while using bytes32 array

texts:
Since we cannot pass string arrays as parameters in solidity I used a byte32 array in a function. The code gives no error at compile time. But when I give input to the drawCard function as below in Remix IDE
"this is token uri", ["maham",67,"Silver","First Token","image url"]

I get the following error:
transact to CryptoGogos.drawCard errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="maham", code=INVALID_ARGUMENT, version=bytes/5.0.5)

My code is as follows:
   function drawCard(string memory _tokenURI, bytes32[] memory params) public {
        require(uint(params[1])<total_supply,
        "Input supply is not less than total supply of cards.");
        _tokenIds.increment();
        uint256 newNftTokenId = _tokenIds.current();

        Cards memory c;
        c.name = string(abi.encodePacked(params[0]));
        c.supply = uint(params[1]);
        c.cat = string(abi.encodePacked(params[2]));
        c.description = string(abi.encodePacked(params[3]));
        c.image_url= string(abi.encodePacked(params[4]));
        c.card_id = newNftTokenId;

        card.push(c);
        tokeninfo[newNftTokenId] = c;
}


texts:
By now I have tried developing a few contracts, deploying them to a test network and using a Javascript based web application to connect to the contracts and use them.

What I want to understand what is the way to package/bundle the Web app as a DApp and deploy in the block chain. Want to understand how that is different to the traditional way of deploying a centralized web application.


texts: How to track the transactions in private ethereum blockchain


texts: How smart contracts modify data in the blockchain?

texts: As far as I understand when a smart contract function is called this smart contract will be executed by all nodes but only the node that mines it will get the gas. Now if that smart contract function for example moves some money from one account to another how can the money be moved only once if the smart contract is executed multiple times?


texts: Ethereum network transaction confirmation coverage

texts: Roughly, how many miners have to confirm the authenticity of a transaction in order for it to be added to the block chain?


texts: Error in Ethereum Wallet:"Couldn't estimate gas, resorting to default parameters. Transaction is likely cheaper than the estimate"

texts:
I am using ethereum wallet for deploying contracts in my private blockchain. But whenever I try to send a transaction in my ethereum wallet it shows an error that says, "Couldn't estimate gas, resorting to default parameters.
Transaction is likely cheaper than the estimate". When I used my ethereum wallet earlier for deploying contracts in another private blockchain, it didn't say this error and contract deployed successfully.

Can anyone help me to find out what that error says?


texts:
I've now started mining with ethminer, however, even though it is correctly using my GPU (its usage is constantly at 100%), the program is also maxing out two of my four cores, to the point where their temperature is higher than the GPU's, I thought it was supposed not to use it, expecially because considering that using the CPU for mining is basically a waste of energy.

By the way, my graphics card is an NVIDIA gtx970 and my processor is an i7-4790k.


texts: What is the difference between web3.js and ethers.js?

texts: Can anyone write a short comparison between the most important features of the two libraries?


texts: Unable to call methods on my deployed contract

texts:
Problem: All method calls to my deployed contract return null

Versions:

  Geth: 1.9.9-unstable
  Git Commit: c2d65d34d5c6f27b8d1a52280964023a3eefd66e

  solc:
  Version: 0.5.13+commit.5b0b510c.Linux.g++

  web3: web3@0.20.1

An ERC20 contract takes four arguments in the constructor. My constructor is defined like this:

  string public name;
  string public symbol;
  address public admin; // For debugging
  uint8 public decimals;
  uint256 public totalSupply;
  event Deployed(address indexed _admin, uint256 indexed _totalSupply, string _name); // For debugging

  constructor(string memory _tokenName, string memory _tokenSymbol, uint8 _decimals, uint256 _initialSupply) public {
    name = _tokenName;
    symbol = _tokenSymbol;
    decimals = _decimals;
    totalSupply = _initialSupply;

    admin = msg.sender; // For debugging
    balanceOf[msg.sender] = totalSupply;

    emit Deployed(msg.sender, totalSupply, _tokenName); // For debugging
  }

I use this JavaScript code to deploy an ERC20 contract to my private test net.

var contractObject = web3.eth.contract(<ABI definition>);
var submittedContract = contractObject.new('DKK', 'DKK', 1, 1000000,  {data:'<bin>', gas: 20000000}, <callback>);

Calling eth.getTransactionReceipt(submittedContract.transactionHash); returns (only relevant fields included):

eth.getTransactionReceipt("0xeb512f29ef2789b592b19acbbb78f8c6be6f7eaed96460c239e0a5d8c20e1dd2");
{
  contractAddress: "0xe23cfc0248b83a4bce8f9701a86e08e9cf9c59f4",
  ...
  logs: [{
      ...
      data: "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003444b4b0000000000000000000000000000000000000000000000000000000000",
      ...
      topics: ["0xf0bbe877a87290e236ea898bbce0d78d6ac7d54d62e32744b129798a2669e39b", "0x00000000000000000000000075bf9b4280b7963ddb1e9198b3aca5b1e02dcf57", "0x00000000000000000000000000000000000000000000000000000000000f4240"],
      ...
  }],
  status: "0x1",
...
}

The status field should indicate that there were no errors, but I am not sure that my constructor values are set correctly. Can you see that from the topics field?

When I then call contractObject.at("0xe23cfc0248b83a4bce8f9701a86e08e9cf9c59f4").totalSupply();, it returns 0. But it should return 1000000.


texts: What is a HD wallet for Ether and how to create one using nodejs?

texts:
I know the basics of blockchain and how to use geth. However, I'm curious to know how to build a wallet using nodejs. What I basically is that you can create a account using geth console (private network) to work on and when pass command "personal.listWallets" then you will this :

So, If anyone can tell me what is HD wallet and how to create one by using node.js. Thanks in advan


texts: transactions list for account as in etherscan

texts:
I'm using web3.py, how can I get a list transactions for account, as in etherscan ?

What are the solutions?


texts: how to import an already deployed contract into my contract

texts:
I have two smart contracts,   the first which i intend to deploy first then after a couple of days the other will follow. my issue is how to import this contract i have already deployed and use its functions in my contract.i have tried
Coin1 _coin1 = Coin1(addressOfCoin1);
 but it doesn't work and when i use the import statement it throws error at point of deployment.


texts: Frontend call --> Transaction does not go through, no error message displayed

texts:
I'm trying to build a frontend for my Dapp and first, I wanted to test if I can initiate a transaction at all.
I have a Button which calls the storeInput() function. Then, it should invoke the storeQueryResults(uint256 id1, uint256 id2, string text1, string text2) function of my smart contract. This is my index.js file:

App = {
  web3Provider: null,
  contracts: {},
  account: '0x0'

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      App.web3Provider = new
      Web3.providers.HttpProvider('http://localhost:7545');
      web3 = new Web3(App.web3Provider);
    }
    return App.initContract();
  },

  initContract: function() {
    $.getJSON("QueryResultHandler.json", function(queryResultHandler) {
      App.contracts.QueryResultHandler = TruffleContract(queryResultHandler);
      App.contracts.QueryResultHandler.setProvider(App.web3Provider);
      console.log(App.contracts);
      return App.render();
    });
  },

  render: function() {
    web3.eth.getCoinbase(function(err, account) {
      if (err === null) {
        App.account = account;
        console.log(App.account);
      }
    });
  },

  storeInput: function() {
    App.contracts.QueryResultHandler.deployed().then(function(instance) {
      return instance.storeQueryResults(1, 2, "a", "b", {
        from: App.account
      });
    }).then(function(result) {
      console.log(result);
      return result;
    }).catch(function(err) {
      console.log(err.message);
    });
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});

I'm using MetaMask, and I'm actually trying to follow Truffle's pet-shop tutorial regarding the config. http://truffleframework.com/tutorials/pet-shop

However, the button seems to do nothing, it doesn't even fire an error message and in Ganache, no new transactions are displayed. I really don't know, what I'm missing.


texts: Import wants >=0.6.0 but the import of the import is ^0.5.0

texts:
that solidity compiling is a mess :frowning:
I’m trying hours to find out why my contracts sometime compile and sometimes not …
Now I got it …
I'm using a local ganache server and the online IDE remix.ethereum.org
Want to compile that file:
pragma solidity >=0.6.12;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";

And get this error:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version pragma solidity ^0.5.0; ^---------------------^

When I look into the Context.sol (clicking in remix on the error popup):
pragma solidity ^0.5.0;

At github (following the inport link) is it the version:
pragma solidity >=0.6.0 <0.8.0;

Shouldn’t my import import the .sol from its own path? What is going on? Is it possible to “refresh” the compiled files in remix after deploying? - I guess thats the point, because I have another contract that use the older version.
Thanks hope for help :D
EDIT
Okay I found out that it doesn't happened when I use the remix with firefox instead of using it with chrome. There is also a libary "github" where openzeppelin is inside, with all the contracts that I import (only that one) but not at the local directory...


texts: What kind of companies can launch an ICO? Only blockchain based or others as well?

texts:
I'm confused as to what kind of companies can launch an ICO - only blockchain based companies that have some inherent use/tie-in of tokens/coins or others as well? For example, I just saw the ethereum based ICO of Kik messaging app where the tokens can be bought/earned and further used within the messaging app. However, Kik is not something that I would consider a blockchain company. On similar lines, can any company or business launch an IPO provided it finds a way to issue and use coins? For example, can a brick and mortar business like a restaurant launch an ICO? Where the tokens could be used to order food online?
Please share your thoughts.


texts: Ethereum smart contract require function

texts:
I have one question about the "require function" of smart contract.
Function is as following,

function set(uint currentTs) public {
    require(msg.sender == owner);
    ts = currentTs;
}

I'm not the owner but I call this function with parameter (for exmaple, 1567569109). So, the raw transaction contains contract's address, my EOA, gas, ...., and currentTs which is 1567569109.

However, my EOA doesn't match the condition in require function. At this time, is the transaction sent by me going to be mined successfully but with smart contract's status not changed. (If I scan all the transactions on the whole blockchain, I can find 1567569109, but when I query to the variable ts in smart contract, ts doesn't change.)

Does it correct? Or, if the condition in require doesn't match, the transaction will fail and it is not going to be mined.

Thanks!


texts: Multiply small rational number to obtain integer piece

texts:
I'm trying to make some advanced calculations in Solidity. I was able to successfully implement the algorithm on my contract, but its results are way below zero, and whenever I try to get it with Javascript, it justs rounds down to 0. Is there any way I can multiply a fraction stored in a variable by a really big number so I can get some precision here? Example:

uint256 x = uint256(5)/uint256(10);

and then:

x *= 100;

resulting in:

> x = 50 <

And here is some of the code I implemented:

Thanks.


texts:
When I check an NFT on eterscan.io I'm seeing that that contract has many holdings.

I think that these are total ERC20 transfers that put in the contract. Probably from NFT consumers like Opensea or Rarible. Am I right?

Someone can explain to me what are these?
When NFT transferred to anyone. Are these holdings move to the new owner too?

Thanks for your responses.


texts:
How to verify that a string, or an enum with only string properties, is initialised or not, inside of a mapping?

According to the docs, it means checking that the element of the mapping is at its 0-value, which is unclear to me when talking about strings.

contract C {
    mapping (address => string) m1;
    mapping (address => StringStruct) m2;

    struct StringStruct {
        string someString; // Always defined when initialising this struct
        // There could be other string properties here...
    }

    function amIInBothMappings() returns (bool) {
         // Check that both m1[msg.sender] and m2[msg.sender].someString are non-0
    }
}

In the example: what is the best way to implement amIInBothMappings that checks that msg.sender is un-initialised in both mappings m1 and m2?


texts: Ganache does not update account balance after contract deploying

texts:
I work with Ganache and nodeJS. Whenever i effort to deploy my contract with JavaScript the related block is mined, that demonstrate the given contract is deployed, but the balance of the sender account (or deployer account) won't be updated. What is wrong that i can see that.
JavaScript code:
    const Web3 = require("web3");
    web3 = new Web3(new Web3.providers.HttpProvider(Web3.currentProvider));

        .
        .
        .

    const cid = <a value>;
    const pid = <a value>;

    const source2='path of my solidity file';
    const compiledMyContract = solc.compile(source2);
    const myContractJson="path of json version of my solidity file";
    const myContractJs = JSON.parse(fs.readFileSync(myContractJson));
    const contractByteCode="...";
    const gasEstimate = await web3.eth.estimateGas({data: contractByteCode});
    const myContract = new web3.eth.Contract(myContractJs.abi, null, {data: contractByteCode});
          myContract.deploy().send({from:<address>, gas: gasEstimate, gasPrice:
    200}).then((instance) => {
        console.log("Contract mined at " + instance.options.address);
        instance.methods.function_A(cid, pid).send({
            from:<address>,
            gas: 2000000,
            gasPrice: 200
        });
        .
        .
        .


texts:
I having the error below when I tried compile the contract. Should I downgrade the truffle version? If yes, which version because I couldn't find the appropriate version for sol 0.4.18. Thanks

SyntaxError: Source file requires different compiler version (current compil
er is 0.4.24+commit.e67f0147.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.4.18;
^--------------------


texts: Access to ethereum-wallet.net blocked by the owner

texts:
The link https://ethereum-wallet.net/ will not give me access to my ethereum wallet. The owner claims it has been hacked and blocked access. My Ethereum coins are still in my wallet I believe but I can't get to my wallet to move them.

I have my wallet code and I know my password. Is there any way I can get to my wallet?


texts: How can I create connected multiple blockchains?

texts:
I want to create multiple private blockchains over Ethereum testnet, which need to be somehow connected. Is it possible to have a node on private blockchain that is connected to the another node on another blockchain?

Edited, added details: The idea is having separate but connected blockchains. That would be enough to having only one "head" node in a blockchain connected to to other "head" node on another blockchain. Other nodes in blockchains will operate exactly as if normal private blockchain nodes. The idea is being able to somehow tracing over different blockchains, via "head" nodes in addition to tracing through same blockchain.


texts:
Would the following story line be a fair approximation of how Ethereum would work in this simplistic scenario?

Simple network with just three nodes: N1, N2 and N3
N1 writes a contract that initiates a counter to value 0 and allows N1 and N2  (but not N3) to increment this counter.
N1 publishes the contract and as a result all the nodes now have a copy of the contract, associated transactions, and resulting state (counter value = 0).
N1 calls the counter function, and as a result, N1, N2 and N3 run the local copy of the contract. Each of them now have the same value of the contract state (counter = 1).
Dice are rolled and one of the nodes (N1, N2 or N3) gets selected at random and given the "authority" to update the transaction and resulting state associated with the contract on the public shared ledger (blockchain).
N3 is upset that he's been left out. He tries to call the increment function by publishing a transaction request, but the contract (on N1, N2 and N3) rejects this.
N3 tries outsmart the system, waits patiently until the dice roll to his favor and can add a block to the chain. In this step, however, N3 adds a bogus transaction leading to an invalid increment on the counter.

What happens after step 7 and what prevents the wrong state from propagating further?

Does the miner that mines the next block need to check that the transactions included by the previous miner are valid, or
Does the miner that processes the next transaction on the contract need to check that the transaction included by the previous miner are valid, or
something else?

If it is any of the first two above does the new miner simply ignore the bogus transaction and roll back to the previous valid state (after cross-checking the associated transactions)?

If anyone gets to read this far please note that there are effectively 3 questions above (each of them marked in bold).


texts: Trying to send signed transaction through web browser using ethereum-tx

texts:
I am working on signing and sending a transaction using web3 v1.0 and Infura.io. I have setup a script to run the TX but cannot seem to get ethereum-tx to connect in the browser.

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>
<script src="js/ethereum-tx.js"></script>

I dowloaded ethereum-tx.js from github and reference but keep getting the error TX is undefined.

var transaction = new TX(txData);

Does ethereum-tx not work in the browser? It works on the local machine after doing the npm install.

Here is the link to the download I am using -

https://github.com/ethereumjs/browser-builds/blob/master/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js


texts: Can separate ABIs be concatenated into a single file?

texts: I have seen Dapps made up of many contracts but a single ABI that I think needs to be referenced for example in a web3j Javascript file. Is it normal to concatenate the ABIs from separate contracts into a single ABI file? If so, how can this be done?


texts: Subscription using websocket through Geth

texts:
I am trying to build a dapp which will monitor a particular address balance, and update in case someone send fund (ether) to it.

Instead of polling using call getBalance, I want to take advantage of the relatively new subscription API through WebSocket (https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB). While I can successfully connect geth using WebSocket, I am struggling to apply the correct filter to the subscription.

Which subscription type should I use? If I use newHeads or newPendingTransactions, what is the correct filter for this kind of case? BTW, I try "logs" before, it seems that the address parameter is only for contract address but not "regular" address (if you understand what I mean).

Thank you.


texts: How to make a multi node ethereum private network

texts:
I'm trying to build a private network that is composed of 2 nodes. Each of the 2 nodes have to deploy a smart contract and to transact the other contract.

The problem is that I'm confused about the best way and the best or easy tools to buils such network?(geth, ganache,...)

my question is:
can any one guide me to choose the best and easy tools to do this or is there a good tutorial to follow?


texts:
I'm trying to declare an in-memory array with a fixed length:

uint length = 10;
uint[length] memory priorityList;

However, it just displays this error message:

  Invalid array length, expected integer literal

Do I have to do uint[10] memory priorityList; or is there a way I can still use a variable to declare the size?


texts: Deploying and Interacting with smart Contract through infura from web3.py

texts:
I'm trying to deploy smartcontract on ropsten testnet through infura node in web3.py. here is my code

w3 = Web3(HTTPProvider("http://ropsten.infura.io/<*Privatekey>"))

# Instantiate and deploy contract
contract = w3.eth.contract(abi=abi, bytecode=bytecode)

# Get transaction hash from deployed contract
tx_hash = contract.deploy(transaction={'from': w3.eth.accounts[0], 'gas': 410000})

# Get tx receipt to get contract address
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
contract_address = tx_receipt['contractAddress']

when I run this code, I always ended up getting timeout error. what could be the possible reason for it. every answer is appreciable because atleast you have spent time on this question.


texts: What is the purpose of raising more ETH for a DAO than can be invested in quality projects?

texts: I understand that DAO members can request ETH to be refunded before a proposal is accepted but what is the point in so much capital being raised? If I add up the sum of capital likely needed by the top 10 or 20 DAPPs I cannot reach the sum that has already been raised by the DAO.


texts: Why is storing in an array the first time in solidity costs higher than the other times? The other times it has a constant cost which is less than the first time.


texts: Transaction is stuck, how to unstuck it?

texts:
I'm using metamask to send a transaction. It sent a transaction with nonce 3, and it has high gas price. However, it's not getting mined at all, now waiting for a long time? Why is it not mined?
I sent previously two more transactions. Metamas set a nonce of 1 and 2 for those. Those transaction are now cancelled. I created a new transaction with high gas price, but it's stuck again. What is happening?
https://etherscan.io/tx/0x7f707f5fee721866f05778b0308fcdd53654a58e07c6509ea7d40d48773fc5f0


texts:
Are there charts for per-contract state size? I came across some blockchain size chart but couldn't find any per-contract breakdown.
Suppose I have a full node (geth or parity), is there an "easy" way to extract such data than scanning the blockchain? (https://ethereum.stackexchange.com/a/40280/474 seems related but that was in '18...)


texts: What is the "zero-account" as described by the solidity docs?

texts:
I was reading the solidity docs and I don't quite understand what the zero-account is.
They say: "If the target account is the zero-account (the account with the address 0), the transaction creates a new contract. As already mentioned, the address of that contract is not the zero address but an address derived from the sender and its number of transactions sent (the “nonce”). "
Does anyone have a different explanation?

From Introduction to Smart Contracts - Transactions:

Transactions
A transaction is a message that is sent from one account to another account (which might be the same or the special zero-account, see below). It can include binary data (its payload) and Ether.
If the target account contains code, that code is executed and the payload is provided as input data.
If the target account is the zero-account (the account with the address 0), the transaction creates a new contract. As already mentioned, the address of that contract is not the zero address but an address derived from the sender and its number of transactions sent (the “nonce”). The payload of such a contract creation transaction is taken to be EVM bytecode and executed. The output of this execution is permanently stored as the code of the contract. This means that in order to create a contract, you do not send the actual code of the contract, but in fact code that returns that code.


texts: why did it returned null after call miner.start()

texts:
> miner.start()
> null

  before it , I had created a account like this .

 user1 = eth.accounts[0]
"0xb62f0bae52d153365661c4e23ab1d594484e9bef"


texts:
some one knows where I can find the Uport mobile App.

I only find this link https://uport.me/devbeta, but It seem no longer be active.

Tks.