texts: Getting Error while compiling: Stack too deep

texts:
Here is my code i have array not 16 variables in a function please help where i am wrong.

struct Escrow {
     bytes16 contractID;

     uint256 sellingTokenAmt;
     uint256 feeAmtInSellingToken;
     uint256 arbitrationFees;
     uint256 paymentWindowInSeconds;
     uint256 contractLifespanInSec;
     uint256 disputeWindowInSeconds;

     uint256 buyingTokenAmt;
     uint256 buyerAddress1Amt;
     uint256 buyerAddress2Amt;
     uint256 buyerAddress3Amt;
     uint256 createdAt;
     uint256 updatedAt;
     uint256 disputedAt;

     address sellerAddress;
     address buyerAddress1;
     address buyerAddress2;
     address buyerAddress3;
     address feeAddress;
     address arbitratorAddress;
     address sellingToken;

     string buyingToken;
     bool isDisputed;
     bool createdBy;
     string sellerPaymentDetails;

}

function createEscrow(bytes16 _contractId, uint256[] calldata _intValues,
     string calldata _buyingToken,
     address[] calldata _addresses,
     address token,
     string calldata _sellerPaymentDetails
   ) payable external    {
 bytes32 _tradeHash =  keccak256(abi.encodePacked(_contractId));
 Escrow storage escrow = escrows[_tradeHash];
 uint256 tokenBalance = ERC20Interface(token).balanceOf(msg.sender);

require(escrow.contractID!=_contractId, "Already in Trading.");
require (_intValues[0] > 0, "Please add valid amount");
require (_intValues[0] > 0, "Please add valid amount");
require(tokenBalance >=_intValues[0], "Insufficient balance.");
require(ERC20Interface(token).transferFrom(_addresses[0], address(this), _intValues[0]));

escrows[_tradeHash] = Escrow(_contractId, _intValues[0], _intValues[1], _intValues[2], _intValues[3], _intValues[4], _intValues[5],
_intValues[6], _intValues[7], _intValues[8], _intValues[9], now, now, now ,_addresses[0], _addresses[1], _addresses[2],
_addresses[3], _addresses[4], _addresses[5], token, _buyingToken, false, true, _sellerPaymentDetails);
totlaEscrows++;

  emit Created (_tradeHash);

}


texts: Synching Ethereum node - do I need to start geth seperately?

texts: I installed Ethereum 0.9.1 from Github on iMac running macOS 10.12.6. Synching 6 days now & still going. Documentation on all things Ethereum is garbled to say the least. Does anyone know if I now need to start geth seperately in a new command prompt ? What directory structure should I now have on hard disk? Whats the relationship between geth - Ethereum - mist ? Where EXACTLY does the geth exe reside? Is there a resource to answer what are really fundamental questions of installing Ethereum, getting mining up and running, connecting to Ethereum wallet - relationships between all the components?


texts: Are blockchains copied or distributed between nodes?

texts:
The following guide mentions that blockchains allow digital information to be distributed but not copied:

  By allowing digital information to be distributed but not copied, blockchain technology created the backbone of a new type of internet.

I thought that blockchains were copied to computers, making them synchronized.


texts: Listen to ethereum transactions on a specific address

texts:
Is it possible to listen to transactions on a specific ethereum address? For example, if someone sends a certain amount of ETH to that address, the callback function would be triggered.

I read this: How to explore all transactions for a given account? but it seems to be about past transactions and not listening live.


texts: How Does Exchanges Implement Gas Fees for ERC20 Tokens

texts:
Any crypto exchange like binance, bitfinex and so on let you deposit and withdraw various ERC20 tokens.

Technically I don't understand how they implement gas fees when I withdraw? I deposited 100 TUSD and I was able to withdraw it without having any ETH in the same deposit address.

Once solution I can think of is, exchanges might be transferring ETH from a central wallet to this deposited address and then creating another transaction to transfer tokens. But this process will require 2 different txns which effects time and cost.

Any other solution? Anyone know how these exchanges do this?


texts: Failed to connect to startum server eu1.ethermine.org

texts:
I am running genoil miner on eu1.ethermine.org and i keep getting a "Failed to connect" error. My internet connection is strong, this should not be a problem. I have been getting this error for over a week so it is not temporary.

Start.bat:

@echo off

setx GPU_FORCE_64BIT_PTR 0
setx GPU_MAX_HEAP_SIZE 100
setx GPU_USE_SYNC_OBJECTS 1
setx GPU_MAX_ALLOC_PERCENT 100
setx GPU_SINGLE_ALLOC_PERCENT 100
ethminer.exe --farm-recheck 200 -G -S eu1.ethermine.org:4444 -O <censored>.myrig

Log:

SUCCESS: Specified value was saved.
Genoil's ethminer 0.9.41-genoil-1.1.7
=====================================================================
Forked from github.com/ethereum/cpp-ethereum
CUDA kernel ported from Tim Hughes' OpenCL kernel
With contributions from nicehash, nerdralph, RoBiK and sp_

Please consider a donation to:
ETH: 0xeb9310b185455f863f526dab3d245809f6854b4d

Found suitable OpenCL device [GeForce GTX 960M ] with 2147483648 bytes of GPU memory
  i  09:03:09|main  Connecting to stratum server eu1.ethermine.org:4444
                     X  09:03:51|stratum  Could not connect to stratum server eu1.ethermine.org : 4444 , A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
  i  09:03:51|stratum  Reconnecting in 3 seconds...
  i  09:03:54|stratum  Connecting to stratum server eu1.ethermine.org:4444

Specs:

GPU: GTX 960

CPU: Intel i5

OS: Windows 10


texts: crypto library not found in ethereumjs-wallet

texts:
I am importing ethereumjs-wallet in angular4,

import EthereumWallet from 'ethereumjs-wallet';
var wallet = EthereumWallet.generate();
const jsV3 = wallet.toV3(passwd);
the code inside the library shown as below

var privKey = crypto.randomBytes(32)

throws out an error

  ERROR Error: Uncaught (in promise): TypeError: crypto.randomBytes is
  not a function TypeError: crypto.randomBytes is not a function
  TypeError: crypto.randomBytes is not a function at
  Function.webpackJsonp.../../../../ethereumjs-wallet/index.js.Wallet.generate

The same problem applies to

  var mnemonic = bip39.generateMnemonic();
  var privateKey = hdkey.fromMasterSeed(mnemonic)._hdkey._privateKey
  const wallet = EthereumWallet.fromPrivateKey(privateKey)

TradePageComponent.html:1 ERROR TypeError: crypto.createHmac is not a function
    at Function.webpackJsonp.../../../../hdkey/lib/hdkey.js.HDKey.fromMasterSeed

  (hdkey.js:162)
          at Function.webpackJsonp.../../../../ethereumjs-wallet/hdkey.js.EthereumHDKey.fromMasterSeed
  (hdkey.js:17)

how to solve the crypto library ?


texts:
I'm new to crypto currencies, trying to get my head around how to evaluate different projects. In general, what are red flags to look out for? Is there anywhere trustworthy that compiles or critical evaluations?

As case study, this one, Appian, sets off alarm bells to me, I'd like to see if others are reading it the same way. It's a perfectly viable enough idea that can plausibly be a real project: an app store for dapps, along with developer tools.

However, I can't find anything written about it, only uncritical reprinting of their press release. There's no information about the people behind it or ways to contact them. There's no evidence in the whitepaper or elsewhere to back up the claims that they actually have the software or expertise they claim. In particular the app builder seems to me like a big project that they'd want to show off a lot more if they actually had it.

Another suspicious thing is that there's already a software company called Appian. Surely they would have done a quick google of the name if they were serious about the project, whereas a scammer might hope the confusion will lend them credibility?


texts: I would like to setup ETH purchase by Visa/Pay-Pal on my webpage. How to do it?

texts: As in title. The only option that I know is going to exchange websites and purchasing from those websites. Would there be a way to simply setup the payment option directly from my web-page ?


texts: How to generate randomness without external calls within a smart contract?

texts: How can I generate a random number within the smart contract without external oracles. Maybe based on the block number or is there any other element that can be used for that?


texts: Is there a practical way for Ethereum networks to handle considerably large volumes of data used by heavy contracts?

texts:
It's not a secret that a single contract could potentially store quite a large volume of data (1, 2). Of course, it takes some gas, but it doesn't seem to cap strictly the overall volume of data to be stored in the entire network. There are also recommended ways to avoid that (like IPFS / Swarm), but again they're not restrictive. Even being inefficient, these data consuming contracts can be created and filled with data and kept in the depth of the network for times.

Now, assuming that blockchain is distributed, how are we going to handle e.g. a few TB heavy contracts? Does it mean, the network would need to distribute these terabytes across all the node to function properly? Maybe there's some sort of retention for such "lost stones"?

Or am I missing a point?


texts: What does it mean when "admin keys have been burnt"?

texts: I've seen multiple times projects on Ethereum that have stated that their "admin keys have been burnt", thus ensuring security to all the users that the developer will not modify/update any existing smart contracts. As far as I know, the private key has a mathematical relationship with a public key address, so I am wondering what exactly these projects mean when their "admin keys are burnt". Usually they also provide a TX as "proof". What exactly is going on here?


texts: in ETH ，how many full-nodes can light nodes select to access?

texts: I want to ask how many full-nodes a light node can select to access if it wants to work safely.And if full-nodes are more than one ,Can the light node specify the node which the transaction is sent, or is it random?Thanks.


texts: My question is that when a miner broadcast some transactions and other nodes don't think these transactions are valid, what will happen? Fork?


texts: Delete function affects my array in my struct

texts:
I am using the function mentioned below to delete a user (i added delete entityList[rowToDelete] to the function )My main issue is that  the function deletes the user but somehow I lose the data in  string items[] from other users

struct EntityStruct {

    uint entityData;
    // other stuff
    string items[];   <--------- I lose the data in here/Cannot fetch the data from the array anymore
}

mapping(address => EntityStruct) public entityStructs;
address[] public entityList;

function deleteEntity(address entityAddress) public returns(bool success) {
    if(!isEntity(entityAddress)) throw;
    uint rowToDelete = entityStructs[entityAddress].listPointer;
    address keyToMove   = entityList[entityList.length-1];
    entityList[rowToDelete] = keyToMove;
    entityStructs[keyToMove].listPointer = rowToDelete;
    entityList[rowToDelete]
    entityList.length--;
    return true;
}

Mapped Structs with Delete-enabled Index by "Rob Hitchens"


texts: Recover Ethereum holding sent to wrong address due to entry error

texts: I attempted to transfer my Etererum holdings from Bitcoin to an address and entered a wrong digit in the address.  Coinbase shows transaction complete.  How can I recover?


texts:
Looked at multiple answer for this question but they seem to be out of date.

I committed a contract to the testnet chain, closed my geth console and upon starting the console again would like to redeploy contract.  I know that I have to load the .abi file in and then instantiate a new local contract, but keep getting error.  Below is code:

loadScript(Token.abi); \\ script assigning abi string to variable 'Token'
var myContract = eth.contract(Token); \\ works fine
var myContractInstance = myContract.at('0x808eca33fef859f9aa54c24780962b0519e274b8') \\ here the error is returned

The error given is

TypeError: 'filter is not a function'

I don't see the .at() function anywhere in the documentation so I assume it is deprecated?  Any ideas?

EDIT:

I did find the .at() function on the api wiki, but for some reason it does not seem to work.


texts: Move/Sell ether from Etherscan to another wallet

texts:
I bought some ether at bitpanda.com and pasted it into my watchlist at etherscan.io. Now I have some questions:

Can I sell my actual ETH at etherscan?
If not, how can I move it to my wallet at coinbase/Ethereum wallet app?

Thank you!


texts: Do the block numbers really skip when I do a transaction in testrpc?

texts:
i'm trying to do abit of testing with testrpc and noticed that when I deploy my contract the block number in the testrpc is pretty random, I tried to do it 3 times and I get either the value of 2 or 13. I assumed that the block number should be at 1 since it's the first transaction which is the deployment of contract. In addition, when I do transactions with my contract sometimes the block number skips numbers too.

Is this really how it should be or is there something wrong that I am doing?


texts: In ethereum if i submit any data is it stored in encrypted format?

texts: Does Blockchain perform encryption/decryption of data?How and where is data stored in ethereum case.


texts: Is it possible to tell whether an address is mist, mew or parity?

texts: How can I tell if an address is from Mist, MyEthereumWallet or Parity? Is there anyway to know? Are they encoded differently?


texts:
Is this the right way to get the address of a Contract, that is stored inside another contract:
Example:
import "B.sol";
contract A{
    B private bContract;
    construtor(){}

    function setBContract(address _address) {
        bContract = new B(_address);
    }

    function getBAddress() returns(address){
        return address(bContract);
    }

}

Or do I have to save the address in some variable like so:
function setBContract(address _address) {
    bContract = new B(_address);
    bAddress = _address;
}

And then just retrieve it over the bAddress variable? Or is it exactly the same?
And which one ist the preffered way? (gas wise).
I assume storing another value will cost more?


texts: EOA to EOA transaction: only data, no ether

texts: It is my understanding that it is possible to create a transaction to send just data from an EOA to another EOA (no ether). In this case the data is completely ignored by the Ethereum network and if I understand correctly, even ignored by all(?) wallet software. If so, does anybody knows if there are any studies of the pros/cons of using this mechanism to establish a communication side channel in which I can distribute a message to anyone with access to the recipient EOA?


texts: How to take a snapshot of addresses and balances of all normal addresses?

texts: How would one take an addresses and balances "snapshot" of all 6,086,374 normal addresses at block number 4293752?


texts: Where is the Approve and TransferFrom used?

texts: I am beginner. I understood how approve+transferFrom+allowance work, but I can not understand where they are used. Can you give examples from real life?


texts: Cheapest Mining Option for Private Blockchain

texts:
I am setting up my own private blockchain (well, it will be public, but a custom/random network-id) and I want to start mining so I can deploy a couple of contracts.

Can anyone recommend the best/simplest options for me?  Should I purchase an Alienware computer (because of the good graphics card?)  Are there VPSes with GPUs?  Something else?

I've never done any mining before at all, so any suggestions would be helpful.  Not only about mining, but about creating a custom/parallen network as well.  I figure there's no better way to really learn this stuff than to basically take it apart and put it together again. :)


texts:
I see some clients accept the command line argument --frontier or --olympic. Is 'Frontier' more than just a name? What does it stand for?

And how does it differ from 'Olympic' and 'Morden'? What are they?


texts: Ethereum linking library with contract not working as accepted...returning any state variable returns just the default value

texts:
my library

pragma solidity ^0.5.8;

library SafeMath {

    function add(uint256 a,uint256 b) public pure returns (uint256) {
        return a+b;
    }
}

My contract

pragma solidity ^0.5.8;

import "./SafeMath.sol";

contract Test {

using SafeMath for uint256;

uint256 c = 10;

    function addition() public {
        uint256 a = 10;
        uint256 b = 10;
        c = a.add(b);
    }

    function getValue() view public returns (uint256) {
        return c;
    }

}

THE STEPS I AM FOLLOWING ARE:-

step 1 :- I am compiling SafeMath.sol  using commnadline  [solc --abi --bin safeMath.sol ]

step 2 :- I am deploying the same with web3 and getting the address as  0x785763........

step3 :- I am linking and compiling the Test.sol contract using the command
solc --abi --bin Test.sol --libraries SafeMath:0x785763........ -o bin

step4 :- I am deploying this contract and trying to just get the value of c without performing the addition operation ,i am getting default value 0

also no events gets fired in addition method inside contract(not shown in this code)

//---------------------------------------------------
//MY WEB3 CODE

var UserRepositoryInstance1 = web3.eth.contract(UserRepositoryABI1).at(UserRepositoryAddress1);

app.get('/checkAdd', function (req, res) {
web3.eth.defaultAccount = web3.eth.coinbase;
var i=UserRepositoryInstance1.getValue();
console.log(i)
})

ANY HELP WOULD BE APPRECIATED THANK YOU.


texts: Solidity: How unlocked account can obtain return values from a call function?

texts:
Unlocked Account can obtain return values from a call function. Basically I assign eth.defaultAccount with some valid address, which only have access to the some state variables as you can see under getIndexReadFrom() as clusterContract[msg.sender].getIndexReadFrom().

[Q] Is it normal that even I didn't unlocked the account, I can use that account as msg.sender when I call a contract's function and reach that account's mapped information? Is there any lock mechanism that can I prevent this from happening, where only who can unlocks the account could reach the mapped information?

> eth.defaultAccount = "0x6af0204187a93710317542d383a1b547fa42e706"
> eth.defaultAccount
"0x6af0204187a93710317542d383a1b547fa42e706"
> myContract.getIndexReadFrom()
10 //Returns a valid information.

Example function:

   function getIndexReadFrom() constant returns ( uint ) {
    return clusterContract[msg.sender].getIndexReadFrom();
   }


texts: How to recover an address from the signed message?

texts:
I use Trust SDK for signing messages and transactions.

I recover a transaction (Trust.signTransaction()) like this:

val tx = Geth.newTransactionFromRLP(Numeric.hexStringToByteArray(response.result))

Where Geth - framework (org.ethereum.geth), version 1.8.11.

How can I recover a data (and an address of the user's wallet) from the signed message (Trust.signMessage())?

Developer of Trust SDK said to look at 'recovery'. But what is it? Framework?

Thank you very much in advance.


texts: How to access non-indexed event arguments from Go types.Log?

texts:
The Go bindings have a type called Log that has the following fields

type Log struct {
    // Consensus fields:
    // address of the contract that generated the event
    Address common.Address `json:"address" gencodec:"required"`
    // list of topics provided by the contract.
    Topics []common.Hash `json:"topics" gencodec:"required"`
    // supplied by the contract, usually ABI-encoded
    Data []byte `json:"data" gencodec:"required"`

    [...]
}

Let's say I have an event like this event SomethingHappened(uint256 indexed id, address indexed participant1, address indexed participant2, uint256 value1, uint256 value2);

There are 4 topics and they are filled as follows, they are of type common.Hash:

The first topic is the hash of the event signature: SHA3("SomethingHappened(uint256,address,address,uint256,uint256)")
The second topic is the encoded uint256 that can be read using the big library: new(big.Int).SetBytes(log.Topics[1].Bytes())
and 4. are the two addresses of the participants. Since common.Hash is 32 bytes long and common.Address is 20 bytes, you can get the address like this: common.BytesToAddress(log.Topics[2].Bytes()[12:32]).

Now, that's not that convenient to do, but it's still possible.  When we try to access the last two arguments, however, I get lost.  They are encoded somehow in the Data []byte field of the common.Log struct.  The documentation mentions they are "ABI-encoded" but offers not way to do anything with that data.  abigen also has no support for event variables, so I'm really lost on how to access those values.


texts: How can a contract run itself at a later time?

texts: In my blockchain application, I would like to have an event triggered at a later time, hours or perhaps even days after the application has most recently received a transaction from a user.  How can I create an "event" that will trigger after a certain amount of time has passed?


texts: How do I determine the most recommended (safest to use) version of Solidity?

texts:
I've seen this question pop-up a bunch of times: "is version 0.x.x safe to use in production?" Therefore, I'm wondering if there is a clear way to tell which versions are recommended for production (Mainnet) and which are not. For example, running the latest version of Slither suggests the following: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-versions-of-solidity
When this question was asked on the official solidity gitter, the following answer was provided by one of the members of the Solidity dev team:

Generally, you should always only use the latest released version available, no prior version whatsoever. [...] We keep a list of security relevant bugs known to be present in each compiler version in https://github.com/ethereum/solidity/blob/develop/docs/bugs_by_version.json. Generally, fixes are not backported across breaking releases (i.e. once 0.8.0 is released, 0.7.x won't be updated anymore). So you always want to use the most recent breaking release series. In the most recent breaking release series there will be backwards-compatible minor releases that may introduce non-breaking features and fix bugs - again it's always best to use the most recent one. So unless you have a compelling reason not to use it, the most recent released version should always be preferred and if any tooling does not yet support it, I'd suggest to pressure them to update. In case you really have to use an older release, be sure to at least check the relevant entries to the bug list.

However, we've seen time and time again that security researchers do find bugs in the most recent versions of solidity. Therefore, it is not clear how to determine the best trade-off between using recent solidity language features and also being fairly confident that enough security researchers have poked the compiler corresponding to that version of solidity and there's not many other things that can be found.
UPDATE: It seems that most of the bugs found in recent versions of Solidity have a tendency to affect all prior versions of Solidity. This supports the argument for using the latest version of Solidity.


texts: Cannot start geth miner by admin.miner.start()

texts:
Start the geth console by geth --maxpeers=50 console

then using admin.miner.start() to start mining, but got the error below

TypeError: Cannot access member 'start' of undefined
    at <anonymous>:1:1

Is there any where I can check for, or any online reference, many thanks.


texts: DwarfPool mining: Blockchain-syncing and firewall settings

texts:
Some questions related to this DwarfPool (ETH) mining command:

ethminer -F http://eth-eu.dwarfpool.com/0xb...

Is it correct that...

ethminer does not download the blockchain, it only creates DAG files.
When using pool/farm mining as shown, I don't need a geth (or eth) background process that syncs the blockchain.
So geth is only needed for administration tasks (create/list accounts, show balance etc.) and I can add the --nodiscover and --maxpeers 0 arguments (or other flags?) to disable blockchain syncing.

Regarding firewall settings:

While mining...

ethminer logs mining actions
tcpdump -i eth0 -A -s 1500 -n host eth-eu.dwarfpool.com shows connections to Dwarfpool server
and after some hours (first, I saw only an empty page) https://dwarfpool.com/eth/address?wallet=b... shows charts and statistics

So, mining seems to work. But...

Do I need to open the ethereum listen port 30303 for proper functioning (e.g. to get payouts)?
If this is the case: Is it enough to allow connections only to the Dwarfpool server eth-eu.dwarfpool.com?

Thank you


texts:
I want to know if there is there a way to have a shared wallet where 2 users both have to agree before calling "transfer". Any problem with this logic in the transfer method?

User A wants to transfer tokens to User B so user A calls the Transfer method. However, the tokens are not actually transferred but it is added to a map of "pending" transfers.

User C now has to call Transfer to User B as well and if the exact match is found in pending map (matching toAddress and amount), then the transfer of the token is actually made.

Alternatively I can make User C have to call the Approve method instead of Transfer. However that seems to go against what it is designed for looking at its signature - approve(address _spender, uint _value). So _spender would actually have to be used for the receiver.

Are both these options possible and are there any problems with them?

Thanks


texts: Is it possible to get account balances in --syncmode "fast"?

texts:
I want to get transaction details and account balance from Ethereum blockchain. The range of date is from genesis block to last mined.

Is it possible to get these information from web3.js?

Is it possible to get tx and balances from fast sync Eth node? (probably no, but please share your views)

Finally, do you suggest to migrate Ethereum block data to relational or non-relational traditional databases and query them for tx and balances?


texts: How can a history of addresses that have owned an ENS name be read on a block explorer?

texts: ENS is nice, is it possibly to easily access a history of addresses that have owned an ENS name?


texts: How to pass encoded parameters to call contract getter fuctions

texts:
I have an array (i.e. functionNames[])  of getter functions's names of my contract and another array (i.e. finalGettersParams) of encoded parameters (which has been populated from web3.eth.abi.decodeParameters) of that getter functions.

  finalGettersParams = [ Result { __length__: 0 },
  Result {
    '0': '0x0000000000000000000000000000000000000000',
    __length__: 1 },
  Result {
    '0': '0x0000000000000000000000000000000000000000',
    '1': '0x0000000000000000000000000000000000000000',
    __length__: 2 }
    ]

now i want to call all getter functions with above available information. Is it possible? One possible solution which i am trying (but its not working, being incomplete) ....

for(j=0; j<functionNames.length; j++) {
      myFunc = functionNames[j].funcName;
      try {
        res = await myContractInstance.methods[myFunc](...finalGettersParams[?????????]).call({from: account1}) // here i need help
        console.log("Getter output", res);
      } catch (error) {
         console.log("Getter ERROR", error);
      }

Anyone can suggest me how to proceed, further?


texts: msg.sender and tx.origin - how to use them in practice?

texts:
I wrote a contract A that uses msg.sender for authentication: When A creates an item it stores msg.sender in itemsOwners mapping (itemOwners[itemId] = msg.sender;). Later A compares msg.sender to itemOwners[itemId] to check access rights.
Now I have the trouble that I cannot use my contract B to wrap calls to A, because A wrongly assumes that the item owner is the contract B, when B calls A. So it stores a wrong item owner that should be a user, not contract B.
Should I replace msg.sender by tx.origin in A? Or what to do? It was not recommended to use tx.origin. So?
I ask not what is the difference between msg.sender and tx.origin, but what to do?


texts:
I am new to Ethereium Block Chain and have been trying some code written in solidity as follows.

pragma solidity ^0.5.0;

import "./MyERC20Token.sol";
import "./ERC20Burnable.sol";

contract MyERC20TokenSale {
address payable admin;
MyERC20Token public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;

event Sell(address _buyer, uint256 _amount);

constructor(MyERC20Token _tokenContract, uint256 _tokenPrice) public {
    admin = msg.sender;
    tokenContract = _tokenContract;
    tokenPrice = _tokenPrice;
}

function multiply(uint x, uint y) internal pure returns (uint z) {
    require(y == 0 || (z = x * y) / y == x);
}

function buyTokens(uint256 _numberOfTokens) public payable {
    require(msg.value == multiply(_numberOfTokens, tokenPrice));
    require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
    require(tokenContract.transfer(msg.sender, _numberOfTokens));

    tokensSold += _numberOfTokens;

    emit Sell(msg.sender, _numberOfTokens);
}

function endSale() public {
    require(msg.sender == admin);
    require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

    admin.transfer(address(this).balance);
}
 }

I wish to return all the raised tokens to the admin and burn the unused tokens. But when I am doing endSale(), I am getting Error : invalid opcode.

It will be a really helping if someone can go through this code.


texts: How to increase gas limit in block using geth?

texts:
When I try to execute methods from my smart-contract, I get limited by the gas limit in a block and can't do anything.
How to change the gas limit in the block?


texts: How to transfer from one ether wallet to another using smartcontract?

texts:
I try to transfer ethers from one account to another using my smart contract but the contract doesn't allow me with following functions :

function transferFrom(address _from, address _to, uint256 _value) returns (bool success)            /* A contract attempts to get the coins */
        {
            if (balanceOf[_from] < _value)
            {
                throw;                                              // Check if the sender has enough
            }
            if (balanceOf[_to] + _value < balanceOf[_to])
            {
                throw;                                              // Check for overflows
            }
            if (_value > allowance[_from][msg.sender])
            {
                throw;                                              // Check allowance
            }
            balanceOf[_from] -= _value;                             // Subtract from the sender
            balanceOf[_to] += _value;                               // Add the same to the recipient
            allowance[_from][msg.sender] -= _value;
            Transfer(_from, _to, _value);
            return true;
        }
function sell(uint256 TokensAmount) afterDeadline
        {

            uint256 amount = TokensAmount;
            if (balanceOf[msg.sender] < amount )
            {
                throw;                                              // checks if the sender has enough to sell
            }
            uint256 revenue = amount * sellPrice;
            balanceOf[msg.sender] -= amount;                        // subtracts the amount from seller's balance
            balanceOf[Killer] += amount;                            // adds the amount to owner's balance
            KilledTokens[msg.sender] += amount;
            KilledTillNow += amount;
            address _to = msg.sender;
            address _from = owner;
            uint256 _value = revenue;

            if (!msg.sender.send(revenue))
            {                                                       // sends ether to the seller: it's important
                throw;                                              // to do this last to prevent recursion attacks
            }
            else
            {
                transferFrom(_from, _to, _value)
                Transfer(msg.sender, Killer, amount);               // executes an event reflecting on the change
                return;                                             // ends function and returns
            }
        }


texts: Calculating sha3 of address in solidity vs web3

texts:
sha3 of address-type argument calculated in solidity

function get_sha() constant returns (address, bytes32) {
    return (msg.sender, sha3(msg.sender));
}

is different from that calculated in web3js using buffer constructed from hex representation of the argument:

returned from contract:
address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c
bytes32: 0xb1591967aed668a4b27645ff40c444892d91bf5951b382995d4d4f6ee3a2ce03
returned by web3js:
> web3.sha3(Buffer.from('ca35b7d915458ef540ade6068dfe2f44e8fa733c', 'hex').toString())
'0xd53a2663473d029b80bddef493a064cc91bad113e4a61353b243b769c6909222'

They match if I compare sha3s of string-type arguments like "a", but don't match in case of address-type argument. I also tried to pad string inside Buffer.from(...) with 24 zeros on the left and on the right, so that it would represent 32 bytes, but the result is still incorrect.

How can I make web3's value match that of solidity's?


texts: How to get the return value of a transaction instead of the transaction receipt in brownie

texts:
I have a function in my smart contract called getRandomNumer, and it returns a bytes32. However, in brownie, when I make a transaction it returns the transaction receipt.
How do I get the return value?
requestId = vrf_consumer.getRandomNumber(get_seed, {'from': accounts[0]})


texts: Is there an official source of info and decision-making about the ERC20 Token Standard?

texts:
I have been trying to trace information about the ERC20 Token Standard to an official source, and everything seems to go back to the (now closed) github thread where the standard was discussed and developed. There is also now an Ethereum Wiki page that describes the key functions and events that need to be included in a smart token contract to meet the ERC20 standard. Both links are at the end of this message.

Are these two pages official public statements and descriptions of ERC20?

Part of why I am asking is that I wonder whether the ERC20 token standard is still being refined. The github thread is now closed, so it's unclear where people can go to offer feedback about ERC20 or participate in its evolution. So, part of my question is: who currently gets to make decisions about the ERC20 Token Standard and how it unfolds from here?

Github link: https://github.com/ethereum/EIPs/issues/20
Ethereum Wiki: https://theethereum.wiki/w/index.php/ERC20_Token_Standard


texts: PoW in Public blockchain Vs. PoW in Private blockchain

texts:
I am reading about consensus mechanisms in blockchain and it is stated that PoW (Proof of Work) requires longer confirmation time compared with voting-based mechanisms. But some things are not clear for me:

1- How can we calculate/estimate the confirmation time using a particular consensus algorithm?

2- Now talking only about PoW, I read that confirmation time is generally shorter in private blockchain as in public blockchain, could some one explain to me (or give me a link containing a comparison/analysis) the difference in terms of confirmation time of PoW in public and private blockchains?

Thanks.


texts: Stuck on Downloading Chain Structure, it keeps increasing

texts:
How long does it take to download chain structure on Ethereum Mist wallet.

DAY 01: I download Mist and Geth. It sync about 20GB, after a while I shutdown system

Day 02: Resumes Sync again 30GB plus now

My question is If I have to start mining using geth miner.start() Do I need to sync everyday ? Which practically going to eat my 1TB in few weeks at this rate

AFTER 24hrs+ (30GB+)


texts: how to measure a function execution time in online solidity compiler

texts:
I'm using online solidity compiler and would like to measure the CPU time for executing a function by capturing the time at start and end of the function.

I found example for Javascript, but when tried it the compiler does not recognise 'var'

var start = new Date().getTime();
var amount = 1;
var sender = personal.listAccounts[0]
var receiver = personal.listAccounts[0]
for (i = 0; i < 5000; ++i) {
   eth.sendTransaction({from:sender, to:receiver, value: amount});
}
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);

How to implement this here?


texts:
I'm running geth for the first time with:

geth --testnet

I can see it downloading the blockchain and it's showing progress with logs like

core/blockchain.go:1047] imported 311 blocks,  2940 txs (646.960 Mg│total 16
) in    6.924s (93.431 Mg/s). #76545 [f42c1bd1… / d1e25194…]

What is mg here?


texts: How Ethereum supports in dealing with double spending problems

texts:
Let's us consider a scenario where I am using my ethereum wallet for creating a transaction request (where my account balance is 100 eth and I am doing a transaction of 50 eth to someone  from one device in a particular geographic location say India).

Now, let us continue with the same scenario where my brother is also using the same ethereum wallet for creating a different transaction request (say transferring 90 eth to someone where my account balance is still 100 eth) within the same time duration where I was proposing the first transaction but here in this case the geographic location and the device used for the second transaction request are different say california.

Can anybody here help me in understanding how and on what parameters what all transaction proposals are accepted and how ethereum avoids double spending problem.


texts: how to use web3j over infura to find exact gas price used for a successful transaction

texts:
my goal is to compute the cost of gas for a successful tx.
I get a callback when a transaction succeeds and i retrieve gasUsed with
transactionReceipt.getGasUsed(). Now I need to know the exact gas price that was used for this tx.

It does not seem like gasprice is stored in txreceipt. the gas price (obtained with transfer.requestCurrentGasPrice()) is in some other place where tx is signed but at that time we would not know the actual gas that will be used. so i wait for txreceipt to find the actual gas used but i then ran into the issue of not knowing gas price that was used.


texts: Contract the makes other contracts race condition issue

texts:
I have a smart contract that is making two (a token and a crowdsale) other contracts.

mapping (uint => myStruct) myMapping;

function start(uint uuid) public returns (bool) {
    address tokenAddress = new Token();
    address crowdsaleAddress = new Crowdsale();
    Token(tokenAddress).addMinter(crowdsaleAddress);
    myMapping[uuid].addr_t = tokenAddress;
    myMapping[uuid].addr_c = crowdsaleAddress;
    return true;
}

The issue I'm running into is that this basically works some times.  When I call it a few times in a row errors start to be thrown.  It works the first time or the last time.

Are tokenAddress  and crowdsaleAddress not being set by the time that they are being passed into Token(tokenAddress).addMinter(crowdsaleAddress).

I tried to debug this using truffle/remix debugger, but when contracts make other contracts, things get pretty crazy.

Is there anything wrong with this code? tokenAddress  and crowdsaleAddress are address and not txhashes?  Are tokenAddress  and crowdsaleAddress valid immediately or do they take time to mine?  I'm pretty confused about where the problem is so any help is appreciated.


texts:
I want to make sure a number of transactions execute in a specific order while sending them all at once (preferably within a single block). Here's what the transactions look like:

Fund ETH
Interact With Contract
Interact With Contract

2 is dependent on 1 running first and 3 is dependent on 2 running first.

It looks like I can guarantee this order using web3's batching. Can I or does the web3 batching just guarantee that this node will propagate the messages to the next node together only?


texts: Are the contents of ethereum storage private?

texts: I know that the code is public, but is the contents of storage private?


texts: Transaction response doesn't contain "receipt" value


texts: Escrow account creation in the example ICO contract from openzeppelin

texts:
I am understanding the ICO as explained in openzeppelin
https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/examples

When I called the "Buy tokens" the beneficiary is getting the tokens but the "Ether" is reaching the an Escrow account.

Question:

In the example contract where the Escrow account is getting created?
Does the contract hold the private key of the escrow account?
Please point me the code

Reference Transaction -
https://ropsten.etherscan.io/tx/0xb7812ca370cec365b6e0e50fe97ff637f8fdefcf5a31a8ed3420f76e0133b41a#decodetab


texts: Library placeholders does not appear in bytecode of compiled contracts - Solc

texts:
I have compiled my contracts with solc module for nodejs. These contracts import and use some libraries. But in the deployed bytecodes of the contracts, there are no placeholders for librairies used in the contract.
I read solc compiler documentation and i does not understand why there are no placeholders for librairies in my bytecodes.
Can someone help me ?


texts: Quorum + Web3js web3.isConnected() returning false

texts:
I am running on quorum and using web3.js. When I run web3.isConnected(), it is returning "false"

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:22000"));
alert(web3.isConnected());

Something I missed out?

Nathan Aw


texts: How to run geth at 512Mb RAM Digital Ocean droplet?

texts:
When geth process consumes too much memory it gets killed (not at all gracefully) by Digital Ocean.

Partly solved the problem by implementing swap - Setting up geth Ethereum node to run automatically on Ubuntu. But still recieved one kill within 2 mln blocks download running geth --fast --cache=16.

Similar question: Is it possible to decrease RAM usage of go-ethereum(geth)? The answer here is - NO.

Is there a way to limit geth memory usage or maybe kill it "more gracefully" than Digital Ocean with something like monit?


texts:
In the Etherem Blog

Vitalik says: "but we do not store history older than 5000 blocks.".

1) Is it to be understood that the state Trie does not contain the state of accounts which were not in use during the last 5000 blocks?

2)Let's say a guy awakeness from a hibernation after 50 years and he wants to make a transaction referencing a block which happened years ago. Taking into account all the current blockchain pruning algorithms implemented or to be soon implemented into Ethereum; how would the protocol go about that? I assume most of the typical full nodes wouldn't even contain the blocks containing transactions mentioning that particular account on their HDDs (again are there any blockchain (not the Trie State) pruning algorithms in place right now?) Probably it would be contained on a few of the archival nodes. How would the protocol go about that?

So the question spans a little across the architecture of Ethereum itself (it suggests that we actually do have a few types of full-nodes, ones that store all the data and others who decided to use some pruning algorithms.) Not that it threatens cryptographic security, as the recent hashes would be enough to verify whether those placed 50 years ago are correct but that would require verifying all the blocks again once we deleted them from the state Trie.Other option would be to TRUST an archival node right-away but then not the cryptographic security BUT, the decentralized nature of services suffers greatly.

Curious am I.


texts:
I'm coding a contract that grew so much it is sizing bigger than the limit on EIP-170.
I already replaced everything I could on inheritance and instanciation of other contracts with interfaces in the contract I want to deploy and even so it's still too big.
Is there any way to get around this problem?

More: I downloaded the TrueUSD code from GitHub and tried to deploy it on a Remix environment and it is also stumbling in the same problem. I suppose the same code was deployed in the mainnet in the past (as this token is being vastly traded for some time until now). Is it possible? How did they deploy it?


texts:
First I connected web3 with Infura. Then reading an ethereum account.

I receive the following error while fetching account balance through node.js console.

> web3.eth.getBalance(address, (err, bal) => { balance = bal })
TypeError: this.provider.sendAsync is not a function
    at RequestManager.sendAsync (/home/kavi/node_modules/web3/lib/web3/requestmanager.js:80:19)
    at Eth.send [as getBalance] (/home/kavi/node_modules/web3/lib/web3/method.js:141:42)


texts: is there a good website to check for a rug and other scams at bsc contract?

texts:
i used to check at rugscreen but now is paid. So i'm out of ways to check the bsc contracts.
Any idea there? thanks


texts:
In Appendix D of the yellow paper for Ethereum, it describes the Modified Merkle Patricia Tree, and states:

  Any series of bytes may also trivially be viewed as a series of nibbles, given an endian-specific notation; here we assume
  big-endian. Thus:

What is the purpose of this translation?


texts: How to create private network with preallocated amount of ETH?

texts:
I am trying to create a private network for testing purposes. What I need is:

Fast generating of DAG file.
Fast mining of the first block.
Address with some preallocated amount of Eth.

I found that this could be done by two ways, the first one is:

Generate the address.
Pass it in the genesis file.
Run geth --datadir "." init genesis.json
Run geth --dev --mine --datadir "."

PROBLEM: Address is not preallocated with money (I don't know why, maybe genesis.json file isn't reading properly)

The second one is:

Generate the address.
Pass it in the genesis file.
Run geth --datadir "." init genesis.json
Run geth --networkid 123 --nodiscover --mine --maxpeers 0 --datadir "."

PROBLEM: DAG file is generating too slow.

Q: Any suggestions how I can meet all requirements?

genesis.json:

{
  "nonce": "0xdeadbeefdeadbeef",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "0x0",
  "gasLimit": "0x8000000",
  "difficulty": "0x01",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0xe7b728f368fce77508e4562ef370d3e902bb79dc",
  "alloc": {
    "0xe7b728f368fce77508e4562ef370d3e902bb79dc": {
      "balance": "10000000000000000000"
    }
  }
}

geth info:

Geth
Version: 1.4.3-stable
Protocol Versions: [63 62 61]
Network Id: 1


texts: What do miners get paid for mining on the Ropsten testnet?

texts: I am just wondering that how Miners got paid in Ropsten test net or other test nets?


texts: Access all the values (tuples) stored in mappings of solidity smart contract using contract address

texts:
This question addresses how a value stored in a contract variable from the outside.

Is there any similar way to access a value of tuples stored in mapping(with and without knowing a key of mapping).

Consider the following smart contract.

pragma solidity ^0.4.24;
contract Student{
    struct stu{
        string name;
        uint age;
        bool tookTest;
    }
    mapping(uint => stu) studentNames;
    function addStudent (uint ID, string _name, uint _age) {
        studentNames[ID] = stu(_name, _age, false);
    }
    function updateStudent (uint ID) {
        studentNames[ID].tookTest = true;
    }
}

I want to all the tuples stored in studentNames and I know only contract address.

Is that possible?


texts: Not able to understand migration file for Crowdsale in ERC20

texts:
I am trying to understand nuts and bolts of the simple CrowdSales in ERC20.
In the simplest way, we have a smart contract that mint the fixed number of tokens (SimpleToken) and then we have the crowdsale (SimpleCrowdsale) contract that is in charge to allow accounts to have tokens in exchange of eth.
So far so good, but when we write the migration file in truffle
const SimpleToken = artifacts.require("SimpleToken");
const SimpleCrowdsale = artifacts.require("SimpleCrowdsale");

module.exports = async function (deployer, network, accounts) {
  await deployer.deploy(SimpleToken, 'Simple Token', 'SIM', '10000000000000000000000');
  const token = await SimpleToken.deployed();

  await deployer.deploy(SimpleCrowdsale, 1, accounts[0], token.address);
  const crowdsale = await SimpleCrowdsale.deployed();

  token.transfer(crowdsale.address, await token.totalSupply())
};

I have a problem understanding what does the following line
await deployer.deploy(SimpleCrowdsale, 1, accounts[0], token.address);

To me it seems that we have to provide the token address (where the SimpleToken sits) and then the address of the account that deploy the SimpleCrowdsale (accounts[0]) but in my understanding, these addresses are the same. If it is not, why we don't have the token.address in the account list? Where is the flaw in my reasoning?
Many thanks


texts: Ropsten Network - geth console does'nt give updated blocknumber

texts:
I have used the command :

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

to setup ropsten network in localhost:8545 and attached geth.ipc using:

geth attach /datadir/geth.ipc

I can see that ropsten network in my localhost is syncing properly. When attached geth.ipc block number is not updated, its always showingat block :  0 (Thu, 01 Jan 1970 05:30:00 IST) even though the command eth.syncing gives incremented block number and after a while current block doesn't increment. eth.blockNumber is zero.

Network time synchronization is active.


texts:
What are the mandatory parameters of genesis.json File in PoA? and what are their expected values? for ex. values of

byzantiumBlock
epi155Block
DAOForkBlock
EIP150Block
EIP158Block
epoch
nonce
mixhash

When I tried to change the value of nonce and mixhash and then started the node, it did not start.


texts:
In Solidity, I run the following code:

function hashTest() public returns(bytes32,bytes32,bytes32) {
bytes32 _solution = 0xbc756c25d68ea2f260ea5f15e1e1c734c019cbc014270dd386eacca4699f60f6;
bytes32 v = keccak256(abi.encodePacked(_solution));
bytes32 x = sha256(abi.encodePacked(_solution));
bytes32 z = ripemd160(abi.encodePacked(_solution));
Print(v,x,z);
return(v,x,z);

I want to replicate in python, but so far I can only get the first (the one supported by Web3), does anyone know how to get the others?  Here's my current try:

def testHash():
    _solutions = '0xbc756c25d68ea2f260ea5f15e1e1c734c019cbc014270dd386eacca4699f60f6';
    v = Web3.toHex(Web3.sha3(hexstr=_solutions))
    x = "0x" + hashlib.new('sha256',str.encode(_solutions)).hexdigest()
    z= hashlib.new('ripemd160',str.encode(_solutions)).hexdigest()
    print("v",v)
    print("x",x);
    print("z",z);

So like I said, the top matches, but the other two don't


texts: How much Ether does a Smart Contract Address hold before a Payable Instantiation?

texts:
The following code always reverts to "Contract must be empty".
But shouldn't address(this).balance == 0 if the contract hasn't even been instantiated yet?
Maybe since the contract doesn't even exist yet, neither does it's address/balance?
Even then, I thought all solidity values are set to 0 by default...
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.5.10 <0.7.0;

contract test {

    constructor() public payable {
        require(msg.value > 0, "User must submit a valid money amount");
        require(address(this).balance == 0, "Contract must be empty");
    }

}


texts: How can I delete an account in parity if I don't know the password?

texts: Parity is asking for a password to delete an account, which I cannot give it. How do I get rid of the account?


texts: Calculating a hash of a set of keys in Solidity

texts:
I have the following problem that I'm trying to think of an efficient solution for.

Suppose I have a set of unordered keys (KEY_1, KEY_5, KEY_2, KEY_4), and I want to calculate a unique hash for this set. Is there an easy way to do this in Solidity using data structures / types that are fairly efficient?

One approach would be to order the keys and then take the hash, but this involves sorting the keys which is not ideal (i.e. O(n*log(n))).

Is there a better approach?


texts: Why Does Ethereum does not use Delegated Byzantine Fault Tolerance? has Vitalik considered it before?


texts: Function declared as view, but this expression (potentially) modifies the state requires payable

texts:
I'm trying to change the an address data variable to a one, which is selected via a function.

Keep getting the below error.

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

address public winneraddress;

function getHighestBidID() public onlyOwner view returns (uint highestID, address _highestidaddress) {
    require(bids.length > 0,"Bid length");
    uint highestAmount = 0;
    for (uint i=0; i<bids.length; i++) {
        if (bids[i].amount > highestAmount) {
            highestAmount = bids[i].amount;
            highestID = i;
            _highestidaddress = bids[highestID].bidderAddress;
        }
    }
    winneraddress = _highestidaddress;
}
        mapping(address => uint256) public payments; //List of payments done to the Contract

    function makeBid(string memory _extraData) public inState(State.Active) payable returns(uint bidIterator) {
    require(msg.value > 0, "No value inserted");
    require(bidders <= 3, "Contract reached max registrations");
    require(payments[msg.sender] == 0, 'Sender previously paid into escrow.');
    bids.push(Bid(msg.sender, msg.value, _extraData, true));
    payments[msg.sender] = msg.value;
    bidders ++;
    return bids.length - 1;
}
    /*function withdraw() external inState(State.WinnerSelected) payable{
    require(msg.sender != winneraddress && winneraddress != address(0));
    payments[msg.sender].transfer(bids[msg.value].amount);
}*/

Any ideas how to fix it and what is causing the error?


texts: How I can get parity logs for non-mainchain blocks?

texts: There's no much info on how parity event log works. What happens to event logs that correspond to block which is not mainchain anymore? Are they unrecoverably lost? For such an occasion, is there any way to reproduce event logs(not traces) from a given block or transaction?


texts: using only html page for frontend with web3 or ethers.js

texts:
I was just wondering, since we are able to write js scripts inside html docs, would we be able to create a dapp with fully functional html front end for our smart contracts?
Or would we need to use react?
If we are not able to only use html and require react or something, else, wouldn't it be better to learn typescript over react as it's javascript with more definition?


texts:
What functionalities/standards does Ethereum have that can be used in cross-chain or cross-DLT operations?
What is the recommended solution when someone need to do an atomic swap? And other cross operations?


texts: Can anyone explain How smart contract gets validated?

texts: Is there any validation process of smart contract's write operations ?


texts: TypeError: Web3 is not a constructor when trying to use node.js with truffle-contract

texts:
I'm trying to use node.js with my smart contract for my app. As I've tried to convert from using the default app.js set-up to index.js set-up I've ran into this weird issue I can't fix.

It throws the error when trying to instantiate my .json file with truffle-contract.

App.contracts.Flip = TruffleContract(FlipArtifact); //at this line it goes to truffle-contract.js and throws this error:

var BigNumber = (new Web3()).toBigNumber(0).constructor;

TypeError: Web3 is not a constructor

I had the exact same thing but in my app.js where truffle puts it automatically and it was working fine.

Could someone please explain the difference between using truffle-contract in my app.js/client-side and my index.js/server-side. Thanks for any help.


texts: Error transferring ERC20 tokens from a contract to an user account

texts:
I am calling a method in smart contract, which transfers tokens from sender account to holder account.
the transferFrom is failing with error

  MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with payload {"id":3714284134436,"jsonrpc":"2.0","params":["0xf88f108502540be400832191c09459d3631c86bbe35ef041872d502f218a39fba15080a47547c7a300000000000000000000000000000000000000000000000000000000000000018602c909e5519ba010b173df9bdb6747b6cdf6dd8f50513d0582c67d8689aaadb9645dcc8c3bcd34a020da92f1f07c57979bf1deee5dd80c7418eda23950bdc089223f1a647101bb64"],"method":"eth_sendRawTransaction"} Error: VM Exception while processing transaction: revert {code: -32603, message: "Error: Error: [ethjs-rpc] rpc error with payload {…VM Exception while processing transaction: revert"}

SmartcontractCode

function getTokens (uint _level) public onlyUnlocked {
require (token.transferFrom(msg.sender, tokenAddress, reward.stakedAmount));
//require (token.transferFrom(msg.sender, address(this), reward.Amount));    }

Any suggestions please how to fix or debug issue


texts: Is there a way to calculate gas usage of external function call?

texts:
I have an external view function which has an iteration loop. If the contract's totalSupply gets bigger, then the iteration time will grow as well. I'm testing on rinkeby right now, but when I launch it on mainnet, and if lots of users gets involved, I'm concerned about the function call hits the block gas limit. So I want to calculate the maximum iteration time of the function, but I have no idea how to do it. Here's my function.

function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
    uint256 tokenCount = balanceOf(_owner);

    if (tokenCount == 0) {
        // Return an empty array
        return new uint256[](0);
    } else {
        uint256[] memory result = new uint256[](tokenCount);
        uint256 totalItems = totalSupply();
        uint256 resultIndex = 0;

        uint256 itemId;

        for (itemId = 1; itemId <= totalItems; itemId++) {
            if (itemIndexToOwner[itemId] == _owner) {
                result[resultIndex] = itemId;
                resultIndex++;
            }
        }

        return result;
    }
}


texts: what --txpool.lifetime is exactly used for?

texts: I want to know what --txpool.lifetime is used for ? and how can we set the value of it ?


texts: If we create a ERC20 compliant token, how do we optimize address-balance mapping storage if we have a large user base?

texts: I assume that the address-balance mapping array in ERC20 is considered as a storage variable. So say if 1 million users start to use token A, then there would  be 1 million entries in the balance array which is expensive to hold in the storage section. How can this be optimized to reduce gas costs?


texts: Noob: How do I verify that a transaction didn't come from a hacker?

texts:
I'm about to work on my first ethereum project.

When a user opens the MySecretApp, they will create a transaction on the ethereum blockchain.

My questions are:

1) Am I sharing the ethereum blockchain (and the billion existing transactions) with other companies? Or can I create a new chain that only contains transactions coming from MySecretApp?

1) How do I verify that a hacker with an app called HackersFakeApp doesn't publish a transaction to my chain? I only want to store transactions that come from my app.


texts:
i try to transform adresses into numbers to give them strictly different values and class them with order. My operation looks not very interesting and very long.
Any idea there ?


texts: PoA network confusion resolving using geth

texts:
I am planning to move from PoW to PoA consensus (clique) using geth. But I am confused of some of the topics -

1) Empty blocks are created periodically? What is the size of an
empty block?
2) Is it possible to avoid empty block creation? That is new block
will be only created whenever there is a new transaction ?
3) I have observed that with unlocking the coinbase account new block
is not created? Is it ok? if not what can be logic behind this?
4) What is the process of adding new sealer in PoA network?
5) What can be the reasonable period for new block?
6) what can be the possible issues behind period=0

I would highly appreciate if someone provides some explanations. Thanks in advance


texts: Ethereum Smart Contracts/dApp’s open source license?

texts: Can a smart contract in which it’s source was released be GPLv3/GNU licensed? I.e. if a company were to release the source code to a smart contract, can that smart contracts source code be GPLv3/GNU licensed?


texts:
Using Geth, how can I extract a snapshot of the network state for a given block?

My Geth node runs a full sync (~300 gb) which means the state trie should already be saved down. I've tried accessing the leveldb database directly, but it's mixed together with the blockchain in the chaindata folder so it's not clear what the structure is.

I've also tried using the web3 dumpBlock method, which works in theory, but it takes way too long to be practically usable (hours).

Is there an another API method that can access the state trie faster?
Any documentation on how the database in the chaindata folder is organized?


texts:
Running geth with websocket:

geth --fast --cache=512 --ws --wsorigins="*" --wsapi "db,eth,net,ssh,miner,web3,personal,admin"

Then connecting with web3 in a Node.js app:

const Web3 = require('web3');

var web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:8546"));

console.log(web3.version);

web3.eth.subscribe('pendingTransactions', function(err, res) {
    console.log('Here')
    console.log(err)
    console.log(res)
}).on('data', function(transaction) {
    console.log('Here 2')
    console.log(transaction)
});

"Here", "Here 2" do not print to the console. The subscription does not seem to activate. web3.version and other web3 commands work fine.

Geth version: 1.7.1-stable

Web3 version: 1.0.0-beta.22


texts: Optimize gas consumption when writing to store and memory

texts:
I have array of uints in contract's storage, now I want to sort it. Quicksort involves swap two array elements if necessary. But as I understand it would be 2 writes to storage. I am thinking that it would be better to copy storage array to memory and operates on memory's one and then - store it back.

My questions is:

Am I right that each uint swapping in array cause 2 storage write calls?
Does it makes sense to copy that array to memory and when sorted - store back?


texts:
I just did my first transfer of ETH from Coinbase to Kraken, to see how it would work.

I transferred 1 ETH, and Coinbase indicated that the transfer charge (the gas) would be .00042 ETH (as I would have expected).  The total transfer out of Coinbase was 1.00042.

I expected 1 ETH to arrive in my Kraken account.  But, only .99938 ETH arrived.  At some point, .00062 ETH was "lost."

Since the gas was already covered, Coinbase indicated that there was no additional fee on their end, and Kraken indicated there was no additional fee on their end, I can't figure out where the .00062 ETH went.

Any thoughts?


texts: Payable contract with multiple "options"?

texts:
I'm trying to create a contract that behaves differently based on the user's selection. I, however, have no idea how to let the user "select" the option. Currently I have a basic fallback function that does the basic logic, but this logic has 2 important variables which I'd like if the user could change. What's the best approach to accomplish this? I know I can create a payable function with 2 inputs that will modify this behavior, but how would people use this function at all? No wallet (except MyEtherWallet) supports functions and even with MEW you need to know ABI. Is there a workaround or something?

Thanks,
SEnergy


texts:
Once you add liquidity to the Uniswap, you need to provide ETH and an equal amount of ERC20 token [1]. So in total, you deposited (ETH + ERC20 amount).
Once you remove the liquidity, do you remove them in pairs as well? Or you just remove the ETH you added + equivalence of the ERC20.


texts: truffle migration: tokenName and tokenSymbol do not show up in explorer (Ropsten)

texts:
I created an ERC20 contract with Truffle, everything went right except for one thing: the name and symbol of the token does not show up in etherscan.

I used the ERC20.sol provided by openZeppelin.
My contract:

pragma solidity >=0.4.25 <0.6.0;

import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";

contract Erc20Token is ERC20 {
    using SafeMath for uint256;

    mapping (address => uint256) private _balances;
    mapping (address => mapping (address => uint256)) private _allowed;
    string public tokenName;
    string public tokenSymbol;
    uint256 public decimals;
    uint256 private _totalSupply;

    constructor(string memory _tokenName, string memory _tokenSymbol, uint256 totalSupply, uint256 _decimals) public {
        tokenName = _tokenName;
        tokenSymbol = _tokenSymbol;
        decimals = _decimals;
        _totalSupply = totalSupply;
        _mint(msg.sender, totalSupply);
    }
}

and the migration contract:

var Erc20Token = artifacts.require("./ERC20Token.sol");

module.exports = function(deployer) {
  deployer.deploy(Erc20Token, "qwerty", "qty", 100000000000000, 8);
};

Here is an example of a transaction, under "Tokens Transferred" we should find tokenName(tokenSymbol). Any idea of what the problem might be ?

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


texts: Cheapest way to store a hash for proof of publication

texts:
Can someone help me how to use events/logs for proof of publication? The way I understand it, I send a transaction with the metadata I want "proof of publication" for, to a contract. The contract does not update its state (ie. The metadata is not stored in its storage). But does there need to be anything in the contract to generate the log? Or is it easier to just aggregate all the transactions sent to that address and extract the metadata using the list of transactions?

I'm looking for the cheapest way (in gas) to log small bits of information and have it associated with a specific address/contract. Any help and suggestions are appreciated!


texts:
I am deploying a contract on a private blockchain using Parity.  The migration seems to default to 4712388 gas (not sure why) and I get this error:

  [-32010] Transaction cost exceeds current gas limit. Limit: 21127,
  got: 4712388. Try decreasing supplied gas.

My question is:

where does this 21127 number come from?  It is not in my genesis file for the private blockchain, since 21127 in hex is 0x5287 and that number is not present.

My gasLimit=0x5280.  But two things make me think this is not related. (1) 5280 is not equal to 5287.  And (2) the gasLimit should only relate to the genesis block, right?  (See gasLimit vs. minGasLimit)

This issue is similar to another error I get with a diffrent configuration, but since the numbers are slightly different I do not think it related.  But maybe? Setting Block Gas Limit in private blockchain?


texts: How to point web3j to other networks such as BSC?

texts:
I would like to use web3j and to execute the functions of contracts that are found on Binance Smart Chain.  How is this done ?
Would it be just
Web3j web3 = Web3j.build(new HttpService("https://bsc-dataseed.binance.org/"))

Then, how do I set the chain ID to 0x38 ?


texts: How can i store a Aces High Pin on the Ethereum blockchain?

texts: I have a few Aces High Pin's laying around and wanted to know how i can store them on the Eth blockchain.


texts:
I get data from array.
This is my result:
0,0,1602907512,1602907764,1602907512,1602907764,60000000,90000000

I need like that:
0,1602907512,1602907512,60000000
0,1602907764,1602907764,90000000

How can I make with JavaScript?
Return code:
     function getPlayerDeposit(address addr) public view returns (uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory) {
        Deposit[] memory invests = users[addr].deposits;
        uint256[] memory boxIds = new uint256[](invests.length);
        uint256[] memory baseTimes = new uint256[](invests.length);
        uint256[] memory lastCollectedTimes = new uint256[](invests.length);
        uint256[] memory values = new uint256[](invests.length);

        uint256 i = 0;
        while (i < invests.length){
            Deposit memory invest = invests[i];
            boxIds[i] = 0;
            baseTimes[i] = invest.depositTime;
            lastCollectedTimes[i] = invest.lastDepositTime;
            values[i] = invest.amount;
            i++;
        }
        return (boxIds, baseTimes, lastCollectedTimes, values);
    }

thanks


texts: DDEX Api Question for Python... Signing ETH Transactions?

texts:
Having an issue with signing a message for the DDEX api... I'm trying to do it in python, and for some reason my signature is off by two characters. Here's my code using the private key and UTC timestamp in the docs.

import web3
from eth_keys import keys
from web3.auto import w3
from eth_utils import decode_hex
from eth_account.messages import encode_defunct
private_key_0 = "0xe4abcbf75d38cf61c4fde0ade1148f90376616f5233b7c1fef2a78c5992a9a50"

# Testing the Auth function...
epoch_time = "1524088776656"
message = "HYDRO-AUTHENTICATION@1524088776656"

message_bytes = ''.join(hex(ord(c)) for c in message)
message_hex = b'{message_bytes}'.hex()

priv_key_bytes = decode_hex(private_key_0)
priv_key = keys.PrivateKey(priv_key_bytes)
pub_key = priv_key.public_key

public_address_0 = pub_key.to_checksum_address()
print("PUBLIC KEY: " + public_address_0)
print("PRIVATE KEY: " +private_key_0)

# print("Message hex: " +message_hex)
msg = encode_defunct(text=message.rstrip())
signed_message = w3.eth.account.sign_message(msg,private_key=private_key_0)

print("SIGNED MESSAGE")
print(signed_message)
sig = signed_message['signature']

# test should be:
# 0x603efd7241bfb6c61f4330facee0f7027d98e030ef241ad03a372638c317859a50620dacee177b771ce05812770a637c4c7395da0042c94250f86fb52472f93500
# but is:
# 0x603efd7241bfb6c61f4330facee0f7027d98e030ef241ad03a372638c317859a50620dacee177b771ce05812770a637c4c7395da0042c94250f86fb52472f9351b
test = str(sig.hex())

header = str(public_address_0) + "#" + message + "#" + test

print(header)

I've gotten here because I was getting an "unauthorized" error from the DDEX api when I've been trying with my own private key. I figure it has to be something to do with the signature function, but can't quite figure it out... any ideas?


texts: Back to basic from a personal protection perspective

texts: Apologies in advance, this may have been asked before but I can't find any answers other than "tough luck". If someone has sent Ethereum to the wrong wallet, there isn't any way to get it back, no one accountable, no help basically the person has to accept the lost. Right? So why would I back a solution that can potentially lose me my hard earnt wages? At least I have some help from my bank if a mistake is made and we all know humans are very good at making mistakes.What does Ethereum offer that protects a person from such mistakes.....nothing right? I'm just asking as I have no idea and nobody seem to have any answers. Recently I sent a small amount of Ether to a new wallet, Etherscan says the transaction was a success and something about "internal" which I don't understand and it never got to my wallet. No one seems to want to help me get my crypto back. Maybe i've been conned by this company, I don't know. But hey you live and learn. So if Ethereum has no protection for people, then what is the point? Someone educate me please. Thanks.


texts: Returning public properties of child object

texts:
I think I'm missing something very simple.  The following contract

contract Genobject{
uint public item;
function Genobject(uint _val){
    item=_val;}
}

contract Caller{
   Genobject public instance;
   function Caller(){
       instance= new Genobject(3);
   }
   function Recall() returns (uint){
      return Genobject.item; }
}

Gives this error

MultiConstructor.sol:27:16: Error: Member "item" not found or not visible after argument-dependent lookup in type(contract Genobject)

    return Genobject.item;
           ^------------^

All my types are the same, and "item" is declared publicly so it should be readable.  What's going wrong?

Thanks in advance


texts:
I'm aware of txpool module in Geth where it able to show how many transactions in the pending and queue state.

How to get the same result in Parity node? The parity_alltransactions looks like returning all the transactions and that's not what I'm looking for. I just want to see stats.


texts:
According to specs, for attester slashing i need to compare the epoch with previous epoch
my question is- is it enough to check that the current epoch with the last one i saved using is_slashable_attestation_data, or do i need to save all the slots since my first validator was created?
Also, do i use the same data for all my validator clients (and their validators)? i mean if i actually can save only the last epoch, i need to save it for each validator or one for all of them?
I was based on this info: https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/validator.md#how-to-avoid-slashing


texts:
After using both clients I couldn't find differences in terms of functionality (features) between geth and pyethapp, only reading that pyethapp is more of a stub project that is easily hackable so that its functionality set can be easily expanded.

The profiles.py file in pyetahpp contains a number of bootstrap nodes to which the client can connect:

from os import path

DEFAULT_PROFILE = 'livenet'

genesisdata_dir = path.abspath(path.join(path.dirname(__file__), 'genesisdata'))

PROFILES = {
    'livenet': {
        'eth': {
            'network_id': 1,
            'genesis': path.join(genesisdata_dir, 'genesis_frontier.json'),
            'genesis_hash': 'd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3',
        },
        'discovery': {
            'bootstrap_nodes': [
                (  # C++
                    'enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263fa'
                    'ba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a'
                    '@5.1.83.226:30303'
                ),
                (  # Go
                    'enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef2'
                    '9b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c'
                    '@52.16.188.185:30303'
                ),
                (  # Go 2
                    'enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f731'
                    '04b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786'
                    '@54.94.239.50:30303'
                ),
                (  # Python
                    'enode://2676755dd8477ad3beea32b4e5a144fa10444b70dfa3e05effb0fdfa75683ebd'
                    '4f75709e1f8126cb5317c5a35cae823d503744e790a3a038ae5dd60f51ee9101'
                    '@144.76.62.101:30303'
                )
            ]
        },
    },
    'testnet': {
        'eth': {
            'network_id': 2,
            'genesis': path.join(genesisdata_dir, 'genesis_morden.json'),
            'genesis_hash': '0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303',
            'block': {
                'ACCOUNT_INITIAL_NONCE': 2 ** 20,
                'HOMESTEAD_FORK_BLKNUM': 494000,
            },
        },
        'discovery': {
            'bootstrap_nodes': [
                (   # Go
                    'enode://e4533109cc9bd7604e4ff6c095f7a1d807e15b38e9bfeb05d3b7c423ba86af0'
                    'a9e89abbf40bd9dde4250fef114cd09270fa4e224cbeef8b7bf05a51e8260d6b8'
                    '@94.242.229.4:40404'
                )
            ]
        },
    }
}

meaning that there should not be any protocol differences between clients. Is this correct?


texts: How to calculate total profit and loss for ERC20 token investments?

texts:
New to the Defi space and I may be overcomplicating this...
I'm trying to find a programmatic way to calculate the total p&l for ERC20 tokens I've staked. I understand that in general to get the current value of my assets staked in a token the calculation would be: [token_current_price * num_of_tokens]. (And then for net profit in ETH, go through my previous transactions and keep subtracting (cost_of_eth_at_transaction_time * num_tokens_staked)).
What is confusing to me though, is that the value of ETH itself fluctuates, which makes it nearly impossible to calculate my real return in USD (unless I'm misunderstanding)? What if the ETH used to buy the tokens was valued lowered when initially traded (USD -> ETH). Wouldn't this mean that instead of using cost_of_eth_at_transaction_time, I would have to use cost_of_eth_at_time_eth_was_traded_for_usd?
Is there an API that abstracts this information, where I can provide my address and see how much I've earned or lost in ETH or USD?


texts:
I am testing out blocknative's mempool explorer (https://explorer.blocknative.com) and noticed a lot of pending transactions are actually already confirmed by the time it picks them up, which I can see by comparing timestamps on etherscan and mempools' pendingTimeStamp parameter.
Considering the fact that blocknative's mempool should only have a delay of couple miliseconds I was wondering if these transactions are somehow hidden from the txpool?


texts: Is there an API for looking up ENS records?

texts:
Currently I'm using this to do ens lookups: https://etherscan.io/enslookup

But is there a public API I can use to do queries to see what each ens goes to?


texts:
Accordin to this article valid ERC20 token must implements number of methods. Among then these two:

function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);

ERC20 standard does not declares any security advice so, anybody who has contract address, contract ABI and know non-empty address can approve any number of tokens and then - transfer it to any other account?


texts:
I have been searching the web for a simple/safe ERC-20 Token Bare-Bone Contract example to use as a base for learning. The Bare-Bones as I understand would only include what the ERC-20 Token Standard requires it to:

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

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

sources: https://theethereum.wiki/w/index.php/ERC20_Token_Standard , https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md

However, even when finding simple templates, you find differences, for instance:

Official ethereum.org/token example:

includes the burn(...) and burnFrom(...) functions. At first glance, all that might need to be done is delete these two. However when looking at another example:

Github link to a token example:

there was the inclusion of various other portions of code that at first glance might seem vital for the ERC-20 standard (but I'm unsure), for instance:

// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
    function safeAdd(uint a, uint b) public pure returns (uint c) {
        c = a + b;
        require(c >= a);
    }
    function safeSub(uint a, uint b) public pure returns (uint c) {
        require(b <= a);
        c = a - b;
    }
    function safeMul(uint a, uint b) public pure returns (uint c) {
        c = a * b;
        require(a == 0 || c / a == b);
    }
    function safeDiv(uint a, uint b) public pure returns (uint c) {
        require(b > 0);
        c = a / b;
    }
}

// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
    function totalSupply() public constant returns (uint);
    function balanceOf(address tokenOwner) public constant returns (uint balance);
    function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);

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

QUESTIONS:

Is the SafeMaths section preventing some types of hacks/exploits? And if that were the case, why don't I see something as important as this in other token examples? Also I'm unsure why another contract called ERC20Interface is being made that initiates the functions, is it just for organization purposes?

If someone has a better simple BARE-BONES template, please do sure! Thank you.


texts: Trading ETH with lightweight Know Your Customer requirements

texts:
Clearly banks follow AML/KYC regulations.

But every bitcoin exchange (Ethereum exchange) I've seen has registration requirements that are far in excess of any bank I've used.

Gemini requires your username/password login for your bank's website (extra LOL)
Kraken requires persistent access to your webcam
Coinbase requires selfies

And at the other end of the spectrum, Venmo requires even less than a bank.

What is a better exchange that I would not be embarrassed to recommend others to?


texts: Attempting to create a transaction on BSC via Ethers.js

texts:
I've been trying to create a transaction using Pancakeswap's V2 router and Ether.js but been having little success with SwapExactETHForTokens:
I've created the function with:
const pancakeswap = new ethers.Contract(
addresses.router,
[
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
    'function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) external payable returns (uint[] memory amounts)',
    'function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)',
],
account)

getAmountsOut seems to be working perfectly fine as I do get output but my issue is with:
    let tokenIn = addresses.WBNB
    let tokenOut = addresses.WSB
    const amountIn = ethers.utils.parseUnits('0.01', 'ether')
    const amounts = await pancakeswap.getAmountsOut(amountIn, [tokenIn, tokenOut])
    const amountOutMin = amounts[1].sub(amounts[1].div(10));
    let deadline = Math.floor(Date.now() / 1000) + 60 * 20 // 20 minutes from the current Unix time

const tx = await pancakeswap.swapExactETHForTokens(
        amountOutMin,
        [tokenIn, tokenOut],
        addresses.recipient,
        deadline,
       {
        gasPrice: 100,
        gasLimit: 9000000
        })
    console.log(`Tx-hash: ${tx.hash}`)

    const receipt = await tx.wait();

    console.log(`Tx was mined in block: ${receipt.blockNumber}`)

My problem is that the function just seems to hang? I don't receive any output or error messages so not sure how to tackle this.


texts: How to start a node on private ethereum chain using "geth --config config.toml"?

texts:
I set up a chique poa ethereum private chain.
the node can start to work using the command below:

geth --networkid 123456 --rpc --rpcport "8545" --rpcaddr 0.0.0.0 --rpccorsdomain "*" --datadir ./node1/data --syncmode 'full' --port "30301"  --rpcaddr "0.0.0.0" --rpcapi "admin,db,eth,miner,web3,net,personal,txpool" --unlock '0x731c68c093dae541baf59616b7f7cd800dfe7de8' --password passfile --mine

I generated a toml config file usding the command：

geth --networkid 123456 --rpc --rpcport "8545" --rpcaddr 0.0.0.0 --rpccorsdomain "*" --datadir ./node1/data --syncmode 'full' --port "30301"  --rpcaddr "0.0.0.0" --rpcapi "admin,db,eth,miner,web3,net,personal,txpool" --unlock '0x731c68c093dae541baf59616b7f7cd800dfe7de8' --password passfile --mine dumpconfig > config.toml

for this way, when I lauch the node by command:

geth --config ./config.toml

the node can not work and be stuck at:

INFO [06-25|05:36:03.943] Started P2P networking                   self=enode://e37dbb1464b9af5404ef337c64cd22061228e8f19552949ef9d9754ae74f5574f0a7fd13b7ebc5dce6b74d87be610f0fa4855b3086c9ebfe7b7c3ace950946dc@127.0.0.1:30301

So how can I use toml config file in private ethereum chain correctly?

Thanks.


texts: Using Truffle with Ethercamp Ethereum Studio

texts:
I'm trying to use the Truffle development environment inside of EtherCamp Ethereum Studio.

My main reference is this issue in the Truffle issue tracker. It suggests using eth-lightwallet and hooked-web3-provider with the latest version of Truffle. To do so, it suggests modifying the truffle.js file to look like this:

  var lightwallet = require('eth-lightwallet');
  var HookedWeb3Provider = require("hooked-web3-provider");

  var contents = JSON.stringify(require('./wallet.json'));
  var global_keystore = lightwallet.keystore.deserialize(contents);

  global_keystore.passwordProvider = function(callback) {
    console.log('PWD requested...');
    callback(null, 'test');
  };

  // get the first account in this wallet
  var account = global_keystore.getAddresses()[0];
  console.log('Main account is ', account);

  // create the provider
  var provider = new HookedWeb3Provider({
    host: 'http://1.2.3.4:8545',
    transaction_signer: global_keystore
  });

  module.exports = {
    build: {
      "index.html": "index.html",
      "app.js": [
        "javascripts/app.js"
      ],
      "app.css": [
        "stylesheets/app.css"
      ],
      "images/": "images/"
    },
    verbose: true,
    rpc: {
      provider: provider,
      verbose: true,
      from: account
    }
  }

I did so. But it fails:

The new KeyStore constructor has been deprecated in favor of KeyStore.createVault(), and will be removed in a future version. Read issue #109 for info. https://github.com/ConsenSys/eth-lightwallet/issues/109
TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at Function.KeyStore.deserialize (/usr/lib/node_modules/eth-lightwallet/lib/keystore.js:399:42)
    at Object.<anonymous> (/root/workspace/solidity-experiments/truffle.js:5:44)

The 5th line of truffle.js is this: "var global_keystore = lightwallet.keystore.deserialize(contents);".

I'm new to eth-lightwallet, truffle and the whole ethereum scene so I'm kinda lost on how to proceed from here. How can I fix this?


texts: Web3.py EventFilter.get_new_entries() always empty

texts:
I've following code to obtain new event entries. The idea is to get latest Transfer events from a specific contract.

from web3 import Web3, HTTPProvider
import json

abi = json.load(open('abi.json'))
address = '0x.....................'

w3 = Web3(HTTPProvider('http://localhost:8545'))

contract = w3.eth.contract(abi=abi,address=address)

event_filter = contract.eventFilter('Transfer',{'fromBlock':0,'toBlock':'latest'})

logs = event_filter.get_new_entries()

print(logs);

There is a local ethereum node running under port 8545 with --rpc.

When I run above script after initiating a transaction, it always prints an empty array.

If I change it to event_filter.get_all_entries() I can see all the transactions. But get_new_entries() doesn't work.
Any idea what would be the issue?


texts: How to increase stored block states from 128 to 10 000 in Geth?

texts: AFAIK Geth preserves states for the last 128 blocks by default. I would like to keep states for, say 10000 blocks (not turning myself into archive node). Is it possible?


texts: Is there any reason for why Solidity has modifiers instead of just having a normal function which is called in the first line of a function body? The docs motivate it with readability but I do not see how that justifies adding a new keyword for a function and the weird underscore syntax.


texts: keystore path in geth command does not work

texts:
I've lunched Geth server and want to store data and keystores in a non-default directory. I've used this command to run Geth:

geth --datadir /etc/dir/ --keystore /etc/dir/keystore/

But when I run geth account new command, the new key stores in the default path /root/.ethereum/keystore/.

What is the problem here?


texts: How do I change/move the .ethash (DAG) directory to a different location?

texts:
When mining, the ~/.ethash folder is quickly fielded. This is annoying as my home directory is on a SSD with no large empty space. Furthermore, mining is writing/reading a lot on the SSD, which is not convenient. Thus my wish to move this directory somewhere else.
I know the geth command accept the --datadir option to point to .ethereum folder when this one is elsewhere than in home directory. But there is no such option for .ethash directory.
Is there any way to create this directory somewhere out of home and tell geth its path ?


texts:
Using the web3 JS library, there's hooks to grab a transaction by its hash (web3.eth.getTransaction()), which includes an input property that is the data payload of the transaction. The first four bytes of which are the function selector which is a fragment of a hash.

The question is, how to determine what function was called? Hashes can't be worked backwards, so we need to derive the list of function signatures for that contract (a.k.a. the contract ABI).

Web3 has the web3.eth.getCode(txnHash) method that can get the hex code for a contract, but can that be parsed into an ABI of the contract?

Or is it impossible to derive the ABI without having the source code of the contract?


texts:
What is the equivalent of (in Web3Js)

token = web3.eth.contract(erc20abi).at(tokenAddress);

in Web3J

I have the erc20abi and the contract address, i want to perform transfer from one address to another.


texts: I get an error when I want to post on infura

texts:
I prepared a new token to learn. My tutorial would show me to post this in infurada, but I am doing the same and getting an error.
I would be glad if anyone could help me.


texts: Binance Smart Chain tokens: What are tTotal, rTotal, tSupply, rSupply, rOwned, tOwned which I see everywhere?

texts:
Looking at all the latest shitcoins' Smart Contract code on Binance Smart Chain, there's a lot of common,recurring themes because most of each project's code is mostly copy-pasted. The code is also completely uncommented, which makes it a pain to understand what's what.
Most of these contacts use two different types of variables for their internal token calculations, 1 called t and one called r. For example, on TrustPad's smart contract (available here: bscscan link):
    mapping(address => uint256) private _rOwned;
    mapping(address => uint256) private _tOwned;
    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private constant MAX = ~uint256(0);
    uint256 private constant _tTotal = 100 * (10 ** 6) * (10 ** 9);
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;
    uint256 private _tFeePercent = 2;

Anybody got any idea what the r and t mean, and why they maintain _tOwned and _rOwned, _tTotal and _rTotal, etc?


texts: Store and retrieve a JSON object in the blockchain?

texts:
Relative blockchain newbie here (go easy on me please:)

Let's say I have a JSON object that contains:

UPC code
Product name
Product color
Product size

Could I store this object in the blockchain--and then retrieve it by UPC?

Now let's say I have a few hundred million of these, with thousands of new ones being created daily.

Possible? What's the process?


texts: How pass a struct as an argument in call from python code

texts:
How call this contract functions from python code?

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract MY_PERSONS {

    struct Person{
        string name;
        uint age;
    }

    Person[] private persons;

    constructor ( Person[] _persons ) public {
    // persons = _persons; // not yet supported
    for(uint i=0; i<_persons.length; i++)
        persons.push(_persons[i]);
    }

    function add_person(Person _person) public  {
        persons.push(_person);
    }

    function get_person(uint index) public view returns(Person) {
        require(index >=0 && index < persons.length);
        return persons[index];
    }

}

I tested Contract Deployment Example
and Passing Struct as an argument in call and everything was OK, but I don't know how call the functions.


texts: How does solidity online compiler link libraries?

texts:
Suppose I have this code:

import "github.com/Arachnid/solidity-stringutils/strings.sol";

contract Contract {
    using strings for *;

    // ...
}

For this solidity online compiler generates this byte code:

60606040523415600b57fe5b5b60338060196000396000f30060606040525bfe00a165627a7a723058207a17f097139e731ad961366b8214b226041a3cd4427248c94ea39ee29bafface0029

Here I don't see any placeholder to add the library address. But when I deploy the byte code it creates a contract successfully.

So how does solidity online compiler find the address of the library?

And how does it know where to deploy the library i.e., mainnet or testnet. I am able to use the same byte code in both mainnet and testnet but the library address may be different in both networks. There are private networks also too.


texts:
I'm trying to deploy a truffle project to testnet. When I run truffle migrate --reset --network rinkeby  --verbose-rpc, this is output:

You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project
You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project

Compiling your contracts...
===========================
> Compiling ./contracts/Migrations.sol
> Compiling ./contracts/StarNotary.sol
...
> Artifacts written to /home/how/projects/_mooc/blockchain/starNotary_3/build/contracts
> Compiled successfully using:
   - solc: 0.5.8+commit.23d335f2.Emscripten.clang

It doesn't create any contract neither in testnet nor locally, and it doesn't mention what goes wrong.

Here is relevant content of truffle.js file:

const HDWalletProvider = require('truffle-hdwallet-provider');
const fs = require('fs');
require('dotenv').config()

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 9545,
      network_id: "*"
    },
    rinkeby: {
      provider: () => new HDWalletProvider(process.env.MNENOMIC, "https://rinkeby.infura.io/v3/" + process.env.INFURA_API_KEY),
      network_id: 4,
      gas: 3000000,
      gasPrice: 10000000000
    }
  }
}

I tried pinging rinkeby.infura.io and it doesn't seem to respond. Can it be that I just can't reach the network?

edit #01

Scripts in migrations folder

// 1_initial_migration.js
const Migrations = artifacts.require("Migrations");

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

// 2_deploy_contracts.js
const StarNotary = artifacts.require("StarNotary");

module.exports = function(deployer) {
  deployer.deploy(StarNotary, "Udacity Star Token", "UST");
};

Link to project

https://github.com/SteveRedka/Star_Notary


texts: What's the difference between 'address' and 'address payable'?

texts:
I saw a Solidity smart contract where some variables were declared with the type address and some were declared with the type address payable. What are the differences between the two?

Do they store the same data?
How do you convert a value from one address type to the other type?


texts: Will I lose all mining time if I restart my miner?

texts:
An example about solo mining with my own pool:

When I stop the miner after about 3 days and start it again, is the mining time lost to find a block?


texts: how can i translate JSON RPC API for curl into a http://..... address

texts:
I have access to a private chain Ethereum node that is accessible via http https://sustainability-chain.info (e.g. i can access it with metamask using special RPC and networkid 20030117

Based on https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_blocknumber I would like to change

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' sustainability-chain.info

which actually works better using:

curl -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' sustainability-chain.info

into something like:

https://sustainability-chain.info/?method=eth_blockNumber&params=[]&id=1

but that does not work

Any idea what I am doing wrong?


texts: I've set up a 5-node network with 3 validator nodes. I would like to test the integrity of the blockchain by having a non-validator node attempt to validate a new transaction. How can I go about doing this?