texts: Why is using `.callcode()` discouraged in Solidity?

texts:
The Solidity document says

  Note

  The use of callcode is discouraged and will be removed in the future.

But in what reason is using <address>.callcode() discouraged?

Is using CALLCODE EVM opcode also discouraged?


texts: Unable to read contract instance variable from deployed contract with truffle test

texts:
I am attempting to write some unit tests as I'm working on the development of some smart contracts, but I've run into an issue that's preventing me from continuing. I'm attempting to check the address of a contract instance that has been imported into my smart contract, which has been deployed to my local network.

For example:

import "./ContractB.sol";

contract ContractA {
    ContractB public _cB;

    constructor(address _addr) public {
        _cB = ContractB(_addr);
    }

}

I would like to retrieve the address of _cB after ContractA has been deployed to the network, but my attempts have been unsuccessful thus far. Here are the methods I've tried to extract the address, but none have proven successful so far:

First Method:

contract('ContractA', (accounts) => {
    it("should return the address of the ContractB contract", () => {
        return ContractA.deployed().then((instance) => {
            return instance._cB;
        }).then((address) => {
            assert.equal(address, accounts[0], "The addresses don't match");
        });
    });
});

Second Method:

contract('ContractA', (accounts) => {
    it("should return the address of the ContractB contract", () => {
        return ContractA.deployed().then((instance) => {
            return instance._cB.address;
        }).then((address) => {
            assert.equal(address, accounts[0], "The addresses don't match");
        });
    });
});

Third Method:

contract('ContractA', (accounts) => {
    it("should return the address of the ContractB contract", () => {
        return ContractA.deployed().then((instance) => {
            return instance._cB.call();
        }).then((address) => {
            assert.equal(address, accounts[0], "The addresses don't match");
        });
    });
});

Fourth Attempt

var contractA = null;
beforeEach(() => {
    return ContractA.new(accounts[0]).then((instance) => {
        contractA = instance;
    })
});

it("should return the address of the ContractB contract", () => {
    assert.equal(contractA._cB.address, accounts[0], "The addresses don't match");
});

If anyone has any ideas or has had experience with this, I would appreciate the help. Thanks in advance.

P.S I know the test-case that I've written will always return false, but I'd just like to see an output. At the moment, I always get "undefined".


texts:
I have two servers, one for eth-node, one for web api and user db.

I want to send request to create account from web server to eth server, but i see it can be created by running command like geth account new localy.
https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458

The purpose of this account is to receive and spend eth, which will be mapped with user-account on user-db server.

Anyway to remotely create account from the eth server then get returned address then store it to the user-web server?

I've read the ethclient, but it shows the way to create wallet only, not account
https://goethereumbook.org/accounts/

Or i have to write a service on eth server to exec command geth account new to get result and return it to the user-web server?


texts: Contract import from GitHub gives an error "Unable to import "undefined": TypeError: Failed to fetch"

texts:
This would be an old issue, but the solutions I have seen on this site aren't working. I'm trying to import a contract of OpenZeppelin to my Remix IDE.

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.4.0/contracts/token/ERC721/ERC721Full.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.4.0/contracts/drafts/Counters.sol";

And it gives me an error:

  Unable to import "undefined": TypeError: Failed to fetch


texts: How to properly calculate amount of fee in this smart contract?

texts:
I'm exploring tradeBalances method of this smart contract and trying to investigate how does fee actually calculate for this transaction with the following decoded input data:

[
    "0xac709fcb44a43c35f0da4e3163b117a17f3770f5",
    "2500000000000000000000",
    "0x0000000000000000000000000000000000000000",
    "13775000000000000000",
    "3156959",
    "3696351802",
    "0xd8eeda4ee2657bb267bc35c1d60babdc5aedd269",
    "28",
    "b4bf0dcd37ca73bd5abce9532b033dcc6427be160683de113efca41320c27f3e",
    "78799d84040e5c245828b1b531ef97e1af124946f4dc1db5a20cf28a7073b269",
    "726181804936299500000"
]

As far I see from the calculation of fee:

tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));

I get:

// fee constants
const feeMake = '0';
const feeTake = '3000000000000000';

// amout fee calculation
let feeMakeXfer = (726181804936299500000 * 0) / (1 ether); // 0 ETH
let feeTakeXfer = (726181804936299500000 * 3000000000000000) / (1 ether); // 2.1785... ETH

// fee calculation
let fee = (feeMakeXfer + feeTakeXfer) - feeRebateXfer; // 2.1785... ETH

As result of calculations above I get fee as 2.1785... ETH which I believe is very big in this case because amount of ETH he is buying according to formula is:

let amount = (13775000000000000000 * 726181804936299500000) / 2500000000000000000000; // 4.001261... ETH

What I'm doing wrong? Please point to my mistake. Thanks in advance.


texts:
I have a question:
How to calculate this function for both Ethereum networks mainnet and ropsten getBlockTimestamp().add(delay)?
I installed web3.eth and tried web3.eth.getBlockTimestamp().add(delay) but it did not work. I would appreciate it if you could help me in this.


texts: I've seen multiple ICO's make total token supply untransferable and understand the purpose why. Now, is it possible to make an individual contributor's token balance transferable in portions? e.g. 5% every 7 days.


texts: Private Blockchain ETH Price Display in Parity

texts:
I have fired up what I think is a private blockchain in parity.  But I still see "Updated conversion rate to Ξ1 = US$88.11" and that is the correct price as of now.

So I'm wondering if this means that my parity is still readinh from homestead, and not the private blockchain?

How can I verify I'm running parity on the private chain?


texts: Is there a current (11/2017) way to parse the Ethereum blockchain?

texts:
I understand there exist many (defunct/unsupported to date) blockchain explorer project and rate-limited web APIs exist for culling Ethereum data from the .ldb blockchain files. But what about bulk processing of the .ldb files on a local node?  Is there a (preferably python based) parser scheme?

Is there a recommended to date? For being a public ledger, it is quit difficult to actually access any of the data...


texts: How to connect with WebSocket with Web3?

texts: Already referred web3 documentations and other Q-A for web socket connection. Currently using infura as provider.


texts: Deployment Failed "Ownable" is an abstract contract or an interface and cannot be deployed

texts:
"Ownable" is an abstract contract or an interface and cannot be deployed.

Import abstractions into the '.sol' file that uses them instead of deploying them separately.
Contracts that inherit an abstraction must implement all its method signatures exactly.
A contract that only implements part of an inherited abstraction is also considered abstract.
This is my Migrations file.

var Ownable = artifacts.require("./@openzeppelin/contracts/access/Ownable.sol");
var Killable = artifacts.require("./zeppelin/lifecycle/Killable.sol");
var Authentication = artifacts.require("./Authentication.sol");
var Rideshare = artifacts.require("./Rideshare.sol");

module.exports = function(deployer) {
  deployer.deploy(Ownable);
  deployer.link(Ownable, Killable);
  deployer.deploy(Killable);
  deployer.link(Killable, Authentication);
  deployer.deploy(Authentication);
  deployer.link(Killable, Rideshare);
  deployer.deploy(Rideshare);
};

Plese guide me


texts:
Account to this text, they are different: https://nethereum.readthedocs.io/en/latest/accounts/

But it never mentioned what are the differences.

Anyone know which one to choose from when implementing my own wallet?


texts: Send funds to owner after each buy or after several?

texts:
I copied and modified smart contracts from TenX and EOS.

TenX sends funds to their wallet after every purchase from a buyer:

function createTokens(address recipient) public isUnderHardCap saleIsOn payable {
    uint rate = exchangeRate.getRate("ETH");
    uint tokens = rate.mul(msg.value).div(1 ether);
    token.mint(recipient, tokens);
    require(multisigVault.send(msg.value));
    TokenSold(recipient, msg.value, tokens, rate);
  }

Whereas EOS does not.  EOS seems to collect funds every once in a while:

// Crowdsale owners can collect ETH any number of times
    function collect() auth {
        assert(today() > 0); // Prevent recycling during window 0
        exec(msg.sender, this.balance);
        LogCollect(this.balance);
    }

Doesn't it get too expensive (with gas) to do it TenX's way, especially if there are thousands of transactions?  Is it insecure to do it EOS's way, because they are leaving funds on the contract?

Which is the better method?

UPDATED 2017-08-25

Maybe the better way is something in between.  I'm thinking of adding the following code, which is to send only if contract's balance is over 50 ETH and also give the owner the option to disable/enable this.  If this the best method or compromise?:

  bool public autoSend = true;

  function createTokens(address recipient) public payable {
    require(recipient != 0x0);
    require(validPurchase());
    uint256 tokens = rate.mul(msg.value).div(1 ether);
    require(token.mint(recipient, tokens));
    weiRaised = weiRaised.add(msg.value);
    if (autoSend && this.balance > 50000000000000000000) { // > 50 ETH
        uint256 amount = this.balance;
        Vault.transfer(this.balance);
        LogCollect(amount);
    }
    LogBuy(recipient, msg.value, tokens, rate);
  }

  function collect() onlyOwner returns (uint256) {
    uint256 amount = this.balance;
    Vault.transfer(this.balance);
    LogCollect(amount);
    return amount;
  }

  function setAutoSend(bool _auto) public onlyOwner {
    autoSend = _auto;
  }


texts: Web3: Error Number can safely store up to 53 bits

texts:
I'm working on a sniping/scanning bot to improve my web3 knowledge. I'm running the latest (1.3.5) web3 package and connecting to the official BSC testnet rpc.
The follow code runs and logs between 2-10 transactions before erroring with: Error: Number can only safely store up to 53 bits.
if (block && block.transactions) {
        for (let txHash of block.transactions) {
                let tx = await web3.eth.getTransaction(txHash);
                console.log(`Transaction: ${txHash}`);
            if(account === tx.from.toLowerCase() && (tx.to.toLowerCase() === pcsRouter.toLowerCase())) {
                gweiToSnipe = tx.gasPrice - 1000000;
                //Call Snipe function here
                let snipeObj = {
                    _contractAddress: contractAddress,
                    _gasPrice: gweiToSnipe,
                    _payable: bnbToSend,
                    _path: '0xae13d989dac2f0debff460ac112a837c89baa7cd',
                    _deadline: `${Date.now() + 60000}`
                }
                return await snipe(web3, snipeObj);
            }
        }
    }

After doing some logging and debugging, removing the if(account...) line changes nothing which leads me to believe its to do with block.transactions. Any idea?
TIA.


texts:
I want to run Soliditykeccak256(abi.encodePacked(challenge_number, msg.sender, nonce)) where nonce is uint256, challenge_digest is bytes32, challenge_number bytes32, testTarget is uint.

What's the analog of this in python? I've already connected to the contract with my metamask account through Python.


texts: How do block explorers interface with a chain differently than full nodes? Would it be possible to integrate block explorer features into a full node implementation in the future?


texts: What if two ether functions have the same signature?

texts:
It should not be hard to find collision.
There is only 4 294 967 296 possible signatures.


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

A send TX to B
B send call to C
C receive tokens in B and give service to A.
In addition, C check balance of msg.sender while execution.

In this case, which one should I use delegatecall or just call to make this logic feasible?


texts:
I modified the example crowd sale contract from the Ethereum site slightly.
First I sent 0.5 ETH from a wallet, it then sent the new tokens and I ran the safeWithdrawal function as the Beneficiary. This then triggered the contract to send the 0.5 ETH to the Beneficiary. I then later sent 1 ETH to the contract and it sent the tokens. I then ran the safeWithdrawal function again as the Beneficiary on the contract but for some reason this time it did not send the 1 ETH. Does it have anything to do with the "if (beneficiary.send(amountRaised))" that it is wrapped in, what is that part even doing?

    function safeWithdrawal() {
    if (beneficiary == msg.sender) {
        if (beneficiary.send(amountRaised)) {
            FundTransfer(beneficiary, amountRaised, false);
        } else {
            //If we fail to send the funds to beneficiary, unlock funders balance
            fundingGoalReached = false;
        }
    }
}

I think I know the problem, amountRaised increases each time, where I have withdraw .5 ETH it never took this off the amountRaised. So now there is 1 ETH but it is trying to withdraw 1.5 ETH. I guess I'm never going to get that back then?


texts: How to handle an ERC20 token which does not return true/false at the end of transfer/transferFrom

texts:
The ERC20 Token Standard dictates that functions transfer and transferFrom should return true for success and false for failure.

However, various ERC20 tokens deployed on the network have not implemented this requirement.

Subsequently, how would you go about asserting success or failure?

The only way that comes to mind is this:

uint256 prevSourceBalance = token.balanceOf(address(this));
uint256 prevTargetBalance = token.balanceOf(to);
token.transfer(to, amount);
uint256 currSourceBalance = token.balanceOf(address(this));
uint256 currTargetBalance = token.balanceOf(to);
assert(currSourceBalance == prevSourceBalance - amount);
assert(currTargetBalance == prevTargetBalance + amount);

But this verification method effectively adds a restriction which is not a part of the standard:

Function transfer can theoretically:

Return true without setting these balances correctly
Return false after setting these balances correctly

Is this restriction considered "legitimate enough" for me to impose it?

Otherwise, would you have any idea how else could I assert success or failure?

Thank you!!!


texts: Why am I receiving invalid transaction hashes?

texts:
I am very new to this whole ethereum and web3 part. I've learned from this tutorial
Link Here about how it is suposed to work and what information should my code deliver to me. But for some reason all the transaction addresses the code returns are wrong.
The whole thing is based on node.js and web3 and looks like this:
        if (block != null && block.transactions != null) {
        for (let txHash of block.transactions) {
            let tx = await this.web3.eth.getTransaction(txHash);
            console.log('Transaction found on block: ' + number);
            console.log({address: tx.from, value: this.web3.utils.fromWei(tx.value, 'ether'), timestamp: new Date()});
            console.log("\n+\n Address" + txHash + "\n+\n");
            console.log(this.web3.eth.getTransaction(txHash).then(console.log));

        }
    }

For example this is one of the returned transaction hashes, which if I check on ethereum.io comes as invalid.

0x254fdffeafd45f04d30936f48fdf2c5adeb9732e8bcdd6f4b5ba2b0cf31329d5


texts:
please i dont come to send data from form with inputs to blockchain database, using nodejs, web3 and dust (engine templating ) ?

please share some exemples if exists ..

Thanks,


texts:
i am currently storing a secret (string) directly inside a smart contract. The idea is that the smart contract only allows authorized people to obtain the secret.
The problem is that the smart contract is on the blockchain and everyone can simply decompile it.

What is the best practice to solve this issue?

As an example one could think of a bidding contract, which contains a secret (reward for the highest bidder). After a bidding round the secret can be obtained by the highest bidder. Is there a way to securely store the secret?

I'm mainly interested in a solution that does not contain a trusted third party.


texts:
I'm trying to mine using Geth. Right now, it's syncing and showing:

{
  currentBlock: 3999975,
  highestBlock: 4000109,
  knownStates: 16329,
  pulledStates: 1739,
  startingBlock: 3999975
}

The Geth console just keeps saying Imported new state entries count=384 flushed=0 elapsed=1m51.659s processed=2507 pending=20431 duplicate=0 unexpected=227. The processed number keeps going up, and the pending number goes up and down. Elapsed varies between 500ms and a few minutes.

I tried leaving it for a few hours, restarting it, using --syncmode=fast, but nothing seems to work, and it's still stuck at block 3999975/4000109...

What should I do?

Edit: I restarted Geth and it increased to 4000079/4000288 within a few seconds. Restarting it again got it to 4000210/4000298, and no progress seems to happen after the "Importing new state entries" start appearing. It's now stuck at 4000210.


texts: can mining be done from different computers using same eth account

texts:
i am trying to setup ethereum mining cluster and i have 3 desktops for this running ubuntu 16.04 with 6 CPU each and 0 GPU.

Is it possible to configure these 3 servers in cluster and using the same etherium account can i increase the overall hash processed/second.


texts: Where are my keys and chain data located if I am using Parity?

texts: Switched from geth to Parity and wondering where my information now is. Thanks.


texts: How to view/edit/cancel scheduled transactions on Parity wallet?

texts: I've set up a scheduled (after a specific time) transaction using Parity wallet and the transaction is not showing up in the Transactions view. Just wondering if there is a way to view/cancel/modify scheduled transactions?


texts: Expected primary expression.-Error in compiling Solidity code

texts:
pragma solidity ^0.4.17;

interface IERC20Token {
    function balanceOf(address owner) public returns (uint256);
    function transfer(address to, uint256 amount) public
    returns (bool);

}

contract ico {
  address private owner;
  address private ops;
  address private trustee;
  mapping(address => bool) public whitelist;

  modifier ownerFunction {
      require(owner == msg.sender);
       _;
  }

  modifier opsFunction {
    require(ops == msg.sender);
    _;
  }

  event Whitelist(address _address);
  event UnWhitelist(address _address);
  event Error(address _address);

  function setOpp (address _oppAddress) private ownerFunction {
    ops = _oppAddress;
  }

  function ico() internal {
    owner = msg.sender;
  }

  function buyTokens(uint256 _value) payable {
      if (getWhitelistStatus(msg.sender) == true) {
          require(balanceOf(msg.sender) >= msg.value);
          msg.sender.transfer(trustee, msg.value);
          return true;
       }
      else
          {
              revert();
              Error(msg.sender);
              returns false;
          }
    }

  function getWhitelistStatus(address _address) returns (bool) {
      return whitelist[_address];

  }

  function whitelist(address _address)opsFunction {
      whitelist[_address] = true;
      Whitelist(_address);

  }

  function unWhitelist(address _address)opsFunction {
      whitelist[_address] = false;
      UnWhitelist(_address);

  }

}

I am getting the attached error while compiling the above contract.Can anyone explain what is the issue here?


texts: How can a contract interact with other chains?

texts:
Reading the Waifusion postmortem article this caught my eye:

At the same time, we were made aware of multiple parties that were
going to fork us as soon as we went live with a sale on BSC. This has
been discussed constantly but the general idea was we should launch on
both rather than give someone who simply forked us and took our art
any potential revenue — and our advisor agreed.

Now I'm not very familiar with the project, but I'm assuming this means that it was possible for users on BSC to interact with the contract in the ETH chain? (Because cloning the project in the BSC chain doesn't make sense to me, it would reduce the value of the NFTs they were selling, since there would be two "original" copies in different chains)
Even if it's not the case, is there a way for contracts in different chains to interact? Assuming one of the chains is ETH.


texts:
I need to use the Ownable contract from Open Zeppelin. Something like:

import 'https://raw.githubusercontent.com/OpenZeppelin/zeppelin-solidity/master/contracts/ownership/Ownable.sol';

Is there a way of defining a setOwnableImportPath function so I can change the url path if the library codebase is shuffled around?


texts: How do I fix this truffle error: "Something already exists at the destination"?

texts:
$ truffle init
Downloading...
Error: Something already exists at the destination. `truffle init` and `truffle unbox` must be executed in an empty folder. Stopping to prevent overwriting data.
    at C:\Users\Welcome\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-box\lib\utils\unbox.js:22:1
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3


texts: Tracking back data from blockchain and Immutable concepts

texts:
Suppose I have an array of some data let say
arr[15]="any value"
If I changed this value to any other value
arr[15] = "changed value"
How can I get the previous value of arr[15]=" any value"
Please Explain on the basis of immutable concept of Blockchain
Are there any way on solidity programming ?


texts: Why does a full client need to store the DAG?

texts:
The yellow paper says that miners and full clients must store the DAG dataset, but light clients can verify block headers by generating only a few necessary pages from the DAG.

It makes sense to me that this suggests more Ethash hashes are necessary for a full client than a light client. What is being hashed? Or is there another reason?

What hash function is used in the Merkle trees? If it is Ethash then it would make sense that a lot more hashing is necessary to check the validity there.

I have searched for hours for this information but I can't find it. Thanks for any help.


texts: Custom bytecode logs data but doesn't return it on eth_call, why not?


texts:
I have bought a sapphire nitro+ rx 570 8GB (Samsung Memory)...
Modded with SRBPolaris...
copied strap 1500 to upper (to 1625,1750 and 2000)...
PolarisBiosEditor cant read my rom...
after that i tried to overclock memory and underclock core and undervolt...
If I overclock the memory above 2000 MHz system fails...
I underclocked core to 1100 MHz...
Undervolted to 150 mV...
and i could only get 21 MH/s in Ethereum mining...
And it consumed 125 Watts...

I've tried some other clock speed and volts...
none of those worked...

Need help with this...
Let me know if anyone know which straps to edit and what is the preferred core and memory clock and volt...
Thanks in advance...


texts:
I'm launching geth with following command:

geth --testnet --syncmode="full" --rpcaddr "0.0.0.0" --rpccorsdomain "localhost" --rpc

But when I'm trying to interact with geth by this python code

from web3 import Web3
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
w3.eth.getBlock(123)

I'm getting Failed to establish a new connection: [Errno 111] Connection refused error
I also tried to use --rpcport argument but it doesn't helped too


texts:
I'm using this compiler: https://ethereum.github.io/browser-solidity/

And it's giving me this error:

  Exception during compilation:
  /src/libevmasm/../libevmasm/Instruction.h(217): Throw in function
  dev::solidity::Instruction dev::solidity::swapInstruction(unsigned
  int) Dynamic exception type:
  N5boost16exception_detail10clone_implIN3dev8solidity13InvalidOpcodeEEE
  std::exception::what: InvalidOpcode [PN3dev11tag_commentE] = Invalid
  SWAP instruction requested.

What does that mean and how do I fix it?


texts: Retrieving Contract instance from .abi and address

texts:
Having the .abi file and the address of a Smart Contract. Can I somehow retrieve the smart contract object instance?

I know for the web3.js we could do something like:

var inst = eth.contract(abi).at(address))

But this doesn't work for the web3py. I am new to this syntax. How can I solve this?


texts: Difference between window.ethereum and window.web3?

texts:
If I log the two functions, I get two objects, that both contain for example selectedAddress, but the structure of the objects seem different. I couldn't find  a comparison in the documentation.

I did find out that window.web3.currentProviderand window.ethereum are equal, but then, what is window.web3 for?


texts: Contract creation from another contract succeeds, then fails?

texts:
I have a first contract with some very basic functionality :

contract ContractA {

    uint public supplyA;

    function ContractA (uint _supply) {
        supplyA = _supply;
    }

    function setNewSupply() {
        supplyA = 1000;
    }
}

I want to create a new instance of this contract from within a second contract :

import './ContractA.sol';

contract ContractB {

    uint public supplyB;

    event LogSupplyA(uint supplyA);

    function ContractB () {
        supplyB = 100;
    }

    function deployA() returns (address) {
        ContractA newContract = new ContractA(250);

        newContract.setNewSupply();
        LogSupplyA(newContract.supplyA());

        return newContract;
    }
}

When I run the deployA() function on contractB in Remix, it returns an address for a contractA instance. However, if I use that address to look at that instance afterwards it cannot be found

  TypeError: Cannot read property 'op' of undefined

Omitting the following lines solves the problem:

        newContract.setNewSupply();
        LogSupplyA(newContract.supplyA());

But leaving the lines in does make the LogSupplyA event display 1000 as value instead of 250, and does return an address for my new instance.

I don't fully understand what is happening here. Why is an updated value shown in my event and is an address returned for my new contract instance, if apparently something went wrong and my contract was not instantiated?


texts: TypeError: Derived contract must override function “_beforeTokenTransfer”

texts:
I am trying to implement an ERC20 token that inherits ERC20.sol, ERC20Detailed.sol, ERC20Burnable.sol, ERC20Mintable.sol, and ERC20Pausable.sol.

contract DemoContract is ERC20,ERC20Detailed,ERC20Burnable,ERC20Mintable, ERC20Pausable {
    constructor(uint256 initialSupply) ERC20Detailed("Test Token", "TEST", 18) public {
        _mint(msg.sender, initialSupply);
    }
}

The function _beforeTokenTransfer is defined in  ERC20.sol as follows:

function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }

and in ERC20Pausable.sol as follows:

function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
    super._beforeTokenTransfer(from, to, amount);

    require(!paused(), "ERC20Pausable: token transfer while paused");
}

When I try to compile my contracts using truffle framework, I get the following error:

TypeError: Derived contract must override function "_beforeTokenTransfer". Two or more base classes define function with same name and parameter types.

contract DemoContract is ERC20,ERC20Detailed,ERC20Burnable,ERC20Mintable, ERC20Pausable {
^ (Relevant source part starts here and spans across multiple lines).

I cannot seem to understand why this error occurs although override is used in the ERC20Pausable.sol.

Here are the new contracts after removing ERC20 from the DemoContract:

contract ERC20 is Context, IERC20

contract ERC20Detailed is ERC20

abstract contract ERC20Burnable is Context, ERC20

abstract contract ERC20Mintable is ERC20, MinterRole

abstract contract ERC20Pausable is ERC20, Pausable

contract DemoContract is ERC20Detailed,ERC20Burnable,ERC20Mintable, ERC20Pausable

However, the error still remains.


texts:
In exchange contract,With multi token when I call approve function from exchange contract, nor my address and spender get approved. Instead only the exchange address and spender gets approved.
Its like when I call approve with spender as my contract address, in token contract it takes msg.sender as my contract address.

How to solve this issue.

With the below code, I tried calling approve function. But that's not a working properly. Kindly prefer a solution for this.

function transfer(address token, uint256 tokens)public payable // deposit perticular token balance to contract address (site address), can depoit multiple token
{
***if(Token(token).approve(address(this),tokens))***
{
    dep_token[msg.sender][token] = safeAdd(dep_token[msg.sender][token], tokens);
    Token(token).transferFrom(msg.sender,address(this), tokens);
}
}

function token_withdraw(address token, uint256 tokens)public payable // withdraw perticular token balance from contract to user
{
dep_token[msg.sender][token] = safeSub(dep_token[msg.sender][token] , tokens) ;
Token(token).transfer(msg.sender, tokens);
}


texts: Is there a loadscript equivalent in eth?

texts:
I got this error in eth client :

  Error: Uncaught ReferenceError: loadscript is not defined

is there a loadscript equivalent command in the cpp client eth?


texts: swapExactETHForTokens - Gas Error Message

texts:
After spending hours of research, I finally found the code from this forum that will do the trick for me. I've successfully compiled the code in Remix (Kovan Test Environment), but I'm getting this gas error message:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Here's the code that I'm re-using:
pragma solidity 0.7.1;

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

 contract BuyToken{

    IUniswapV2Router02 usi = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

function buyTokenWithExactEth() public payable returns(uint256) {
        address cryptoToken = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;

        uint deadline = block.timestamp + 15; // I am only using 'now' for convenience, for mainnet I will pass deadline from frontend
        usi.swapExactETHForTokens{value: msg.value}(0, getPathForETHToToken(cryptoToken), address(this), deadline);

        // no need to refund ETH
        return 1000;
}

  function getPathForETHToToken(address crypto) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = usi.WETH();
    path[1] = crypto;

    return path;
  }

}

Here's the screenshot of my remix environment:

Any advice on how to fix this? thanks in advance!
Edit: new error when deploying the contract in Mainnet


texts:
A am implementing a custom ERC20 token inheriting from OpenZeppelin's StandardToken. I override some of the functions but did not override approve or allowance. I write a test for approval:

contract('MyToken', async(accounts) => {
it("approve test", async() => {
    let token = await MyToken.deployed();

    let approveResult = await token.approve.call(accounts[1], 20, {from: accounts[0]});
    assert.isTrue(approveResult);

    let allowanceAccountZeroAccountOne = await token.allowance.call(accounts[0], accounts[1]);
    assert.equal(allowanceAccountZeroAccountOne.toNumber(), 20);
  });
});

I get the following result:

  Contract: MyToken
    1) approve test
    > No events were emitted

  1 failing

  1) Contract: MyToken approve test:
     AssertionError: expected 0 to equal 20
      at Context.it (test/mytoken.js:51:12)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

It seems that approve returns true, as expected, but the subsequent allowance returns 0 instead of 20. What could be the problem?

PS I tested the contract manually in Remix, and it works as expected.


texts: Send 2 transactions on same ETH address, one is pending after 1hour

texts:
simple question on Ethereum :

-can we make several withdrawals to the same ETH address?

-Or do we need one destination address for one withdraw transaction?

I made 2 transactions to the same ETH address 3 minutes apart, the first one went through and the second one is stuck, pending; however the later had a low transaction fee. It has been 70 minutes.

Thanks for helping.


texts: sendSignedTransaction: why does it take variable times to return a transaction hash and to reach a mempool?

texts:
When we call sendSignedTransaction from web3, my understanding is that the transaction is broadcasted to a provider (either a hosted node or your own node) and added to that node's mempool, assuming the mempool for that node isn't currently full. It's then synced with other nodes and eventually makes it's way to a miner node's mempool.

Why does it take some time for the transaction hash to be returned from this function call to Infura:

web3Provider.eth.sendSignedTransaction(signed).once('transactionHash', hash => {
        //this takes ~50-100ms to return.
});

//It takes anywhere between 100ms-1s to hit a mempool of a node I monitor

and 2) why does it then take a variable time to appear in the mempool of a node I monitor?
Is there anything that would affect the speed both of 1) and 2) - i.e. if the network was particularly busy or the node was busy syncing/doing other stuff?


texts: How to create a smart contract that has token and transfers tokens to whoever sends ether?

texts:
I want to create a smart contract which is able to create tokens, priced at some amount of ether, example uint price = 1 ether;. Now after someone sends any amount of ether, the same amount of tokens are sent to the sender's ETH account.
Some of the main problems are
1. Since there is no minimum value, the sender might send ether in decimal, so how to store it and send the tokens in decimals?
2. How to create tokens within the smart contract without transferring it to the owner?
I already have seen the code to send tokens after someone sends ether to the smart contract - How to create a token smart contract that sends tokens after recieving payment in ether?
Also, I have the code to issue my own ERC-20 token - https://github.com/bitfwdcommunity/Issue-your-own-ERC20-token/blob/master/contracts/erc20_tutorial.sol
I'm quite advanced in Solidity platform and is still learning so help will be really appreciated.

Here's the code to send tokens after recieving payment in ether:-

uint256 public totalSupply;// total no of tokens in supply
uint remaining;
uint price;
mapping (address => uint) investors //it maps no of tokens given to each address

function token(uint _totalSupply) //constructor
{
totalSupply = _totalSupply;//set initial no of tokens in supply
remaining = 0;
}

function ()  payable// called when ether is send
{
assert(remaining < totalSupply);
uint noOfTokens = div(msg.value,price); // calculate no of tokens to be issued depending on the price and ether send
assert(noOfTokens < sub(totalSupply,remaining)); //no of tokens available should be greater than the one to be issued
add(investors[msg.sender],noOfTokens);
remaining = add(remaining,noOfTokens);
transfer(msg.sender, noOfTokens);

}

function setPrice(uint _price)
{ //  price need to be set maually as it cannot be done via ethereum network
price = _price;
}


texts:
I have a basic understanding of elliptic curves, so I'm more interested to find out how does ecrecover specifically verify signatures. It has rather weird requirements, like this prefix thing (excerpt taken from this thread):

bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, hash);
return ecrecover(prefixedHash, v, r, s) == (Your Address);

There seems to be no clear topic on this matter on SE.


texts: Different events for revert types or one event and then on the client/backend figure the reason why it reverted from emitted data?

texts:
Let's say I have 3 conditions which can lead to revert(). which way should I handle it? 3 types of events or one event with extra parameters?

3 events types:

if condition A:
 emit causeA(dataA1, dataA2)
 revert()
if condition B:
 emit causeB(dataB1, dataB2)
 revert()
if condition C:
 emit causeC(dataC1, dataC2)
 revert()

1 event:

if condition A:
 emit cause(dataA1, dataA2,-1,-1,-1,-1)
 revert()
if condition B:
 emit cause(-1,-1,dataB1, dataB2,-1,-1)
 revert()
if condition C:
 emit cause(-1,-1,-1,-1,dataC1, dataC2)
 revert()

Backend:

Would need to fetch by 3 types of events and switch by the result.
Add the logic after fetching the event to figure what happened or search for the cases != -1 and then act.


texts: Web3.Utils - WeiToEth and EthToWei Conversion choking on decimals

texts:
I have the following two helper functions.  It was based on a course I'm going through, so I didn't think I would have to debug them. I don't understand why it works with whole numbers, but not with decimals.

    export const EthToWei = (n) => {
        return new web3.utils.BN(
          web3.utils.toWei(n.toString(),'ether')
        )
      }

    export const WeiToEth = (n) => {
        return new web3.utils.BN(
          web3.utils.fromWei(n.toString(),'ether')
        )
      }

I wrote this unit test (was already using Truffle):

    describe('testHelpers - full WeiToEth', () => {

        let wei = 2000000000000000000  // len 19
        console.log("A1: wei=" + wei)
        let eth = WeiToEth(wei)
        console.log("A2: eth=" + eth)
        let expectedEth = 2;
        it('full WeiToEth', async () => {
            eth.toString().should.eq(expectedEth.toString());
        })
    })

    describe('testHelpers - fraction WeiToEth', () => {

        let wei = 200000000000000000   // len 18
        console.log("B1: wei=" + wei)
        let eth = WeiToEth(wei)
        console.log("B2: eth=" + eth)
        let expectedEth = .2;
        it('fractional WeiToEth ', async () => {
            eth.toString().should.eq(expectedEth.toString());
        })
    })

    describe('testHelpers - Bidirectional Whole Number', () => {

        let eth = 4
        console.log("C1: eth=" + eth)
        let wei = EthToWei(eth)
        console.log("C2: wei=" + wei)
        let eth2 = WeiToEth(wei)
        console.log("C3: eth2=" + eth2)
        it('Bidirectional Whole Number ', async () => {
            eth2.toString().should.eq(eth.toString());
        })
    })

    describe('testHelpers - Bidirectional Decimal Number', () => {

        let eth = 4.5
        console.log("D1: eth=" + eth)
        let wei = EthToWei(eth)
        console.log("D2: wei=" + wei)
        let eth2 = WeiToEth(wei)
        console.log("D3: eth2=" + eth2)
        it('Bidirectional Decimal  Number ', async () => {
            eth2.toString().should.eq(eth.toString());
        })
    })

Results without the stack traces:

A1: wei=2000000000000000000
A2: eth=2
B1: wei=200000000000000000
B2: eth=-18
C1: eth=4
C2: wei=4000000000000000000
C3: eth2=4
D1: eth=4.5
D2: wei=4500000000000000000
D3: eth2=385

  testHelpers - full WeiToEth
    √ full WeiToEth

  testHelpers - fraction WeiToEth
    1) fractional WeiToEth

  testHelpers - Bidirectional Whole Number
    √ Bidirectional Whole Number

  testHelpers - Bidirectional Decimal Number
    2) Bidirectional Decimal  Number

  2 passing (57ms)
  2 failing

  1) testHelpers - fraction WeiToEth
       fractional WeiToEth :

      AssertionError: expected '-18' to equal '0.2'
      + expected - actual

      --18
      +0.2

  2) testHelpers - Bidirectional Decimal Number
       Bidirectional Decimal  Number :

      AssertionError: expected '385' to equal '4.5'
      + expected - actual

      -385
      +4.5


texts:
https://solidity.readthedocs.io/en/develop/abi-spec.html
"address: equivalent to uint160, except for the assumed interpretation and language typing. For computing the function selector, address is used."
So I understand from the above document, ethereum addresses are numbers. Is there any way to see or find the number to an ethereum address? And is there any way to send this number through a function to find the corresponding address?
If not, is there any way to look up an address' last signed message and get data from there simply by quering an address?


texts: At which point the smart contracts get executed?

texts:
Let's say I sent a transaction to invoke a smart contract (to its address). At which point will the smart contract get executed? Is it during the transaction validation process?

Also, is there any limit on how long a smart contract can run on? For example, the block generation time in Ethereum is about 12 seconds. If there is a smart contract which takes a long time to run and if it gets executed during the transaction validation process, how would that impact on the block time?


texts: Transaction mined but state variables aren't changing

texts:
I am able to get the transaction with a block number while calling method of a contract however the state variables don't change unless I mention the "address" and "gas" parameters on web3^0.20.7

HelloWorld.sol

contract HelloWorld {
  string message;
  event evntGetMessage(string message);

  constructor(string mymessage) public {
    message =  mymessage;
  emit evntGetMessage(message);
  }

  function getMessage() external view returns(string) {
    return message;
  }

  function welcomeMssg(string name) external returns (string){
     message =  string(abi.encodePacked(message, " ", name));
     emit evntGetMessage(message);
     return string(abi.encodePacked(message, " ", name));
  }
}

txn.js

//txn.js file to call the contract instance from web3. I have deployed the contract using web3 JS:

contractInstance.welcomeMssg('Hi',{gas: 500000,from:txnAccount1})   //returning me the expected results and appending the state variable - "message"

contractInstance.welcomeMssg('Hi')    //returning me transaction block number but not updating the "message" variable

Is it the expected behavior in web3@0.20.7?

Thanks


texts:
I'm doing oraclize calls on the json rpc of a chain to get this function:

  function getTransfer(uint _transferId) public view returns(uint,address,uint){
    Details memory _locked = transferDetails[_transferId];
    return(_locked.amount,_locked.owner,_locked.transferId);
  }

It's really not that important what it does, but when I call this function from oraclize, I get back a string with all three variables...for instance:

"0x0000000000000000000000000000000000000000000000000b1a2bc2ec500000000000000000000000000000c69c64c226fea62234afe4f5832a051ebc8605400000000000000000000000000000000000000000000000000000000000000001"

I'm working on a callback to parse this into a uint, an address, and a uint.  This is what I have so far:

function __callback(string result) public returns(uint,address,uint){
    emit Print(result);
    string memory _int = Strings.substring(result,60,90);
    emit Print(_int);
    emit P2(stringToUint(_int));
    uint _amount= parseInt(_int);
    _int =strConcat('0x',Strings.substring(result,91,130)) ;
    address _owner =  parseAddr(_int);
    _int =Strings.substring(result,131,194) ;
    uint _transId = parseInt(_int);
    return (_amount,_transId,_transId);
}

This sort of works, but the problem is that the uint's are actually in hex value (this string should return .8e18,0x,1), but I need to convert a literal string to a hex to a decimal..if you have any ideas.  Also, can I use substring, or will the length of my string change with the values?

The code of the contract we're calling is here:
https://ropsten.etherscan.io/address/0xd29d27cfacf7b77a16edac7c2cddf07dc4a603b8#readContract

p.s. It can break remix doing this kind of string manipulation


texts: How to implement crypto refunds in a smart contract?

texts:
I am quite new to cryptocurrencies and after some investigation I thought this might be the right place to ask.
Problem: I have a small business and I would like to offer to my customers the option to pay with some cryptocurrencies (ex: Bitcoin). However I would like to receive the money only if my job has been performed on time. Otherwise they get a discount of x%. I believe this can be done with smart contracts and as far as I understand the Ethereum platform offers the option to do so by deploying a code that does so.

I tried to code myself the logic by following some youtube tutorials and even though they mention the possibility to achieve what I want to do, the examples are always oversimplified and do not implement the "IF THIS THAN THAT" condition which is fundamental for my business.
Question: Do you know if there is a minimal valuable example that accomplishes this task? Or can you point me to some resources where I can find some help please?


texts:
uint256 public max_contribution = 50 ether;
    uint256 public min_contribution = 1 ether;

I added this to my ICO smart-contract, but still can do less than 1 ether transactions. What should i change there or may be how can i set minimal contribution in other way?


texts:
I am using node to test solidity with a ReactJS front end. After IPFS required I used a SSL I had to add some changes to my nginx conf and now port 3000 is not being found.

I installed the SSL and nginx -t is all ok. Here is my congif file:

server {
    listen 80 default_server;
listen 8080;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html/ipfs/src;
index App.js index.html index.htm;
listen   443 ssl;
server_name jenbil.com;
ssl    on;
ssl_certificate    /home/keys/jenbil.com.chained.crt;
ssl_certificate_key    /home/keys/jenbil.key;

When I try to access https://jenbil.com:3000 I get a not found error but http://jenbil.com works and also https://jenbil.com displays the ReactJS but no actual action is performed.

I am using npm start to run the development server.

Here is netstat -nltp:

root@ubuntu-512mb-nyc3-01:/etc/nginx/sites-enabled# netstat -nltp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1287/sshd
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      24017/nginx
tcp        0      0 104.236.58.158:8545     0.0.0.0:*               LISTEN      8702/geth
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      24017/nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      24017/nginx
tcp        0      1 104.236.58.158:47508    93.108.217.34:*         SYN_SENT    8702/geth
tcp        0      1 104.236.58.158:35970    66.41.106.197:*         SYN_SENT    8702/geth
tcp        0      1 104.236.58.158:52430    124.176.170.179:*       SYN_SENT    8702/geth
tcp        0      1 104.236.58.158:38030    86.155.52.143:*         SYN_SENT    8702/geth
tcp6       0      0 :::22                   :::*                    LISTEN      1287/sshd
tcp6       0      0 :::3000                 :::*                    LISTEN      23874/node
tcp6       0      0 :::30303                :::*                    LISTEN      8702/geth
tcp6       0      0 :::80                   :::*                    LISTEN      24017/nginx
root@ubuntu-512mb-nyc3-01:/etc/nginx/sites-enabled#

How can I get the 3000 port to be listened to or how can I not use that anyway in testing?


texts:
Are local variables stored in memory or on the stack in Solidity?

If memory, is the memory freed after the function returns?


texts:
I have a struct with the following variables:

struct contract {
        address customer;
        uint8 tokentype; // 5 token types
        uint8 size;  // 5 sizes
        bool  gender; // 2 types
        bool  active;  // 2 types
    }

I'm not a computer scientist, but I think bools are 2 bits, and when I have 5 cases, I suppose that's 5 bits.

To save on gas and memory, I could store them as a uint instead of separate variables, so that each digit slot would reflect one item: {tokentype, size, gender, active} --> {digit4, digit3, digit2, digit1}. Thus 4411, would be the largest possible number for my set of cases, while 0 the smallest. I would then access them via pulling out some particular contract "con", so that I could apply logic on the cases using

for size, it's digit 3, and thus

con.digit3 / 1e3 % 10 = case of digit 3

which I could use in my contract via the generalized function, for various x and j:

if ((con.digitx / 1ex) % 10 == j)

I would replace values the following way. For example, if the existing value of digit3 is not 4, and I wanted it to be 4, I would apply the function

  con.digit4 = con.digit4 + 4e3 - ((con.digit4 / 1e3) % 10) * 1e4;

In the context of Solidity's gas considerations, is there a more efficient way? I figure there is using a shift operation.


texts: How many topics can a whisper message have?

texts: I'm thinking in a new DAPP that may use whisper extensively. To evaluate the viability of the DAPP, I need to know if there is a limit on the number of topics that a whisper message can have. I would like also to know how many topics a single filter can listen to, and how many whisper filters can coexist in the same node.


texts: How to console log output in hardhat test?

texts: I'm using running hardhat tests. When I add console logs to the test cases, nothing actually gets outputted to console. Why's that?


texts: Binance Smart Chain Full Node Implementation - geth is not recognized (Error)

texts:
I am trying to install Binance network,by following the official link
https://docs.binance.org/smart-chain/developer/fullnode.html

However, while trying to run make geth  I find the below error.

They point out several ways for exampkle download the binaries
Linux
wget  https://github.com/binance-chain/bsc/releases/download/v1.0.7/geth_linux

However, this does not recognize geth after it. Can I just simply use to install geth ethereum instead? Normally, that geth should not have the changes made by Binance.


texts: Where can I find an authoritative/"official" listing of the pre-compiled contracts currently on the Ethereum network, along with their exact specifications? I couldn't find anything in the official documentation, but maybe I'm looking in the wrong place. Ideally, I'm looking for a list that will be kept up-to-date (as new EIPs will get approved).


texts: How can I synchronize account between geth servers?

texts:
I have setup geth in 2 servers as a private testing Etheruem environment.

In the 1st server, I have created accounts.
For the 2nd server, I would like to build as a node to attach the 1st server.
After I have setup and mount the 2nd server, 2 server can synchronize the number of block immediately.

However, the accounts in the 1st server cannot be found in the 2nd server.
Is there a way to synchronize accounts between nodes?

If no, it implied that each account can be access from a single server only even there are multiple nodes/server for the single private Ethereum network.

Appreciate if there is any idea.


texts: how to get the reserves of all coin pairs at once on pancakeSwap

texts:
I am trying to query the pancakeSwap token pair contract for the reserves, and since I am trying to get it for 10000 tokens at a single time.
My current solution is to basically loop over the 10000 tokens and query each smart contract of that coin pair to get the reserves which happen to be very consuming in physical resources.
Is there a way to get all the reserves in a single smart contract query?


texts: What's the deal with "burning" tokens during an ICO?

texts:
I was reading about the AIR token ICO and they mention that they minted 1.491 billion tokens and burned 8,507,442 tokens. Why not just mint an even 1.5 billion tokens and distribute them evenly among the people who bought the token? Or why not just mint the 1.491 billion and just never create the 8.5 million?

I get that if you mint all the coins ahead of time then what's variable is how much they're worth but you can sell them all. If there's a set price, then you can mint the coins after the ICO ends. Either of these approaches wouldn't require burning tokens.

What am I not getting?


texts: meta mask registers ether delta as a probable phishing site

texts: My question is about how recently when I go to ether delta my metamask registers it as a phishing site and does not let me interact with the site? what should I do and what does this mean?


texts: getting error TypeError: Member "transfer" not found or not visible after argument-dependent lookup in address

texts:
Hi I need one help as I am unable to run below logic in solidity as some change in solidity.

function transfer_balance(address recipient_address, uint amount)
public returns(bool) {
    if(msg.sender == owner){
         if (amount <= get_balance()){
             //transfer the amount received as argument to the recipient_address
             recipient_address.transfer(amount);<-- error here
             return true;
         }else{
            return false;
        }
    }else{
        return false;
    }
 }

Error is

  TypeError: Member "transfer" not found or not visible after argument-
  dependent lookup in address.
                   recipient_address.transfer(amount);
                   ^------------------------^

This is little confusing as it was run  on old version on solidity.


texts: How does .on work in Web3 1.0, and why do I get duplicate results?

texts:
I don't understand what .on event handler does in Web3. Take this example for signing a transaction:

    web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
        .on('transactionHash', function () {
            console.log('*** Transaction Hash ***')
        })
        .on("transactionHash", console.log)
        .on('transactionHash', function () {
            console.log('*** Waiting for Confirmation ***')
        })
        .on('receipt', function () {
            console.log('*** Transaction Submitted ***')
        })
        .on("confirmation", function() {
            console.log('*** Transaction Confirmed ***')
        })
        .on("error", function() {
            console.log('*** Error ***')
        })
}

It waits for various things to happen, but when they do, I get 10-20 console log lines every confirmation or error. Is this an infura thing maybe, sending back events asynchronously from multiple nodes, or is there something else going on?

Nothing bad is happening in my script, I just get spammed with the same events that have already happened.


texts: parity initializing snapshot whole night

texts:
I have parity installed and synced. I went out of disk space. I moved the chain to bigger ssd. Then I started the parity service and let it run whole night. It did not finish.

in log I can see repeating lines like

IO Worker #3 INFO import  Snapshot initializing (378 chunks restored)  #7280022   19/25 peers      1 MiB chain   10 MiB db  0 bytes queue   15 KiB sync  RPC:  0 conn,    0 req/s,    0 µs

After about 2000 chunks I stopped it. How many chunks are there going to be ? This method should be fast, so I expect It should not take whole night

Edit 1

so import  Snapshot initializing messages changed eventually to import  Syncing snapshot and after few more hours stopped at Syncing snapshot 3070/3070  #7280022   20/25 peers      2 KiB chain   10 MiB db  0 bytes queue   15 KiB sync  RPC:  0 conn,    0 req/s,    0 µs

now there's reating message IO Worker #3 INFO snapshot  Block restoration at #6870000 decreasing at by 100000 ever 2 minutes. I hope it's not going to zero. It would take another day.

Is this warp taking me to another galaxy ?

Edit 2

so after another restart it started syncing rest of the blocks


texts: Is there a way for a smart contract to manage a codebase?

texts:
For example, could one set up a smart contract with governance protocols which could merge PR’s in a github repository? How might one govern open source via a smart contract?

In a related vein, is there a method to automatically deploy to ethereum from a github repository?


texts: Can I use a Bitcoin client to sign a message with an Ethereum address?

texts:
If an Ethereum address is a point on the Bitcoin EC, then one can use the private key that matches that address to sign a message using bitcoin software.

I'd like someone to prove they have the private key for an ethereum address by signing something with it and I don't know how one would sign a message with an ethereum address.  I found https://etherscan.io/verifySig where such a signature can be verified.

If I export the private key for my ethereum address and then import it into a Bitcoin client and then sign a message with it, will that be valid according to etherscan's verifySig page?

If I simply restore my wallet to a Bitcoin client using my Bip39 phrase, then can I sign something with the bitcoin address at a certain derivation path to produce a valid signature under ethereum for the address at the same derivation path?


texts: Deploying new contract inside truffle test case

texts:
I was trying to transact between two contracts inside my truffle test case. But not been able to do it. The second contract instance comes back undefined always.

As per the truffle documentation, deploying new contract inside a test case is as shown below,
Contract2.new().then(function(instance) { contract2Instance = instance; });

The error I'm getting is TypeError: Cannot read property 'address' of undefined on Contract2Address = contract2Instance.address;

Any idea what I'm doing wrong?

var Contract1 = artifacts.require("./Contract1.sol");
var Contract2 = artifacts.require("./Contract2.sol");

contract('Contract1', function(accounts) {
  it("should put 30000000 in the second account", function() {
    var contract1Instance;
    var contract2Instance;

    var Contract1Address;
    var Contract2Address;

    return Contract1.deployed().then(function(instance) {
      contract1Instance = instance;
      Contract1Address = contract1Instance.address;
      console.log("Contract1Address:" + Contract1Address);
      Contract2.new().then(function(instance) { contract2Instance = instance; });
      console.log("contract2Instance:" + contract2Instance);
      Contract2Address = contract2Instance.address;

      contract1Instance.deposit({from: accounts[0], value: web3.toWei(2, "ether") });
      contract2Instance.claim({ value: web3.toWei(1, "ether"), gas: 1000000 });
      return web3.eth.getBalance(Contract2Address).toString(10);
    }).then(function(balance) {
      assert.equal (30000000, 30000000, "30000000 wasn't in the first account");
    });
  });

PS: Please pardon the mix of the new and old syntax.
The whole test works in truffle console though.


texts: Solidity - How do I generate a random address

texts:
EDIT: there is currently no good answer to this question. Solidity is not able to generate anything random, not at this moment at least.

I would like to generate a random 0X address using solidity. It would be the best if it could be an existing address, however, I understand that it might be too complicated to do (it might need an oracle?).

What is the best way of doing it?

My approach would be to simply have an array of characters 0-9, a-z, A-Z and take a random character from it to concat the 0x address. However, I am not sure if that would be the best coding practice with Solidity.


texts: how can you deploy smart contracts on main ethereum network?

texts: I have created a dapp and using truffle I have migrated and tested it on ganache, I was wondering how can I deploy same application on main ethereum network.


texts:
for a client of mine i'm creating a ICO website. The basic html & css code is fully done, and I have implemented a progress bar from Bootstrap on the webpage.

My client asked me if it's possible that this progress bar automatically changes from percentage based on the current available tokens in their ERC20 smart contract address.

I've read some stuff about web3js, but I can't find anything related to this matter.

Is there someone here who is willing to help me with this?

Any help is appreciated :)


texts:
I have a mapping like this:

pragma solidity 0.4.24;
pragma experimental ABIEncoderV2;
pragma experimental "v0.5.0";

...

mapping(bytes32 => LibMarket.Market) public hashToMarket;

where each Market is defined as:

struct Market {
    address a;
    uint256 b;
    uint256 c;
    string d;
    string e;
}

in a library file LibMarket.

In another contract, I'm trying to access this mapping using the hash like so:

    LibMarket.Market memory market = registry.hashToMarket(marketHash);

However, I'm receiving the error

  Exchange.sol:139:9: TypeError: Different number of components on the
  left hand side (1) than on the right hand side (5).
          LibMarket.Market memory market = registry.hashToMarket(marketHash);
          ^----------------------------------------------------------------^

Why am I getting this error?

EDIT:

Although this doesn't answer this exact question. A simple workaround is to define a different getter function in the contract that has the hashToMarket mapping like so and it will work as intended:

function getMarket(bytes32 marketHash) public view returns(LibMarket.Market) {
    return hashToMarket[marketHash];
}


texts: I have a Crowdsale smart contract taken from the example provided by Ethereum on their website. The Crowdsale contract contains the addresses of the people who participated in the Crowdsale. Is there any way for me to access those address from a different contract and how?


texts:
I am using Ganache and wanted to understand where can we see the events in the Ganache UI. I tried checking the events in the transaction and logs tab but I did  not find it. Here is one sample code.

pragma solidity ^0.4.0;

contract Ballot {

    event isEOAOrNot(bool val);

    function isContract(address addr) returns (bool) {
       uint size;
       assembly { size := extcodesize(addr) }
       bool val = size > 0;
       isEOAOrNot(val);
       return val;
    }
}

Please let me know where can I see the events in the UI.


texts: How to store x amount of uint8s inside a byte32?

texts:
I'm trying to store an array of uint8 but its not very gas efficient. This is my current solution of storing things:

uint8[5] public VALUES = [10, 11, 12, 13, 14];

The problem is that I will have about 40 of these VALUE arrays, and if I test that in Remix, I can't even start the Contract (I've waited minutes for the initialisation and it doesn't occur, so I am assuming this is very inefficient).

My next planned solution is to store the values in a string:

string public VALUES = "1011121314";

And then I would retrieve numbers by getting their index i and i+1, and using parseInt(string) to get the number. But I'm not so sure about the efficiency of doing that.

So since I've heard about assembly being very efficienct within Solidity, I'm wondering if there was a way to store multiple uint8 values in a larger data format, such as a byte32? My current use case is 5 uint8 values, so perhaps byte5 would only be required? Also how would I retrieve such values?


texts: How does function getPastEvents works? It's too quick

texts:
I'm trying to understand how .getPastEvents function works. When given block range to search is {fromBlock:0, toBlock: 'latest'} it finds my events almost instantaneously. Shouldn't filtering all 7M blocks (using Ropsten testnet) take more than a second? Code snippet if it's of any use.

myContract.getPastEvents("EventName", {fromBlock:0, toBlock: 'latest'}).then(
  function(event) {
    event.forEach(element => {
      //doing some logic here
    });
  }
);


texts: How much gas does it cost to create and/or execute a smart contract?

texts: Curious for any other good resources for this Q!


texts: How could i fetch transaction hash for a particular transaction in frontend?

texts:
let's take an example
I send calimID = 123
and got a transaction hash = 0x123...
when I try to click on claimID in front end I should be linked to transaction hash...
how could I do that?


texts: How to withdraw from contract exact amount of ether?

texts:
Suppose I have a contract:
contract mycontract {
    constructor() payable {}

    function withdraw(uint256 amount) public {
        // either
        //payable(address(msg.sender)).transfer(amount);
        // or
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed.");
    }
}

When I call withdraw(100000000000000), I got my ether balance increased by 99999999973576 or so wei instead of 100000000000000. Is it because of transaction cost? How can I fix this function to receive exactly 100000000000000 wei? And if it's tx cost, why it applied differently to "normal" transaction (like wallet to wallet)? Why tx cost doesn't deduced from contract balance, not from tx amount? Where one can read about it?


texts: Adding payable to my contract constructor causes the contract deployment cost to be really high ~100 Ether

texts:
Here is an abstract/interface contract I created because I want to call this contract which will be deployed before my other contracts. It just holds the addresses of all the contracts I have deployed.

IAddressManager.sol

contract IAddressManager {
    function getTokenAddress() public constant returns (address) {}
    function setTokenAddress(address _tokenAddress) public {}
    function getEventAddress(uint8 _indexOfAddress) public constant returns (address) {}
    function setEventAddress(uint8 _indexOfAddress, address _newContractAddress) public {}
    function getSpecialAddress(uint8 _indexOfAddress) public constant returns (address) {}
    function setSpecialAddress(uint8 _indexOfAddress, address _newContractAddress) public {}
}

I omitted a bunch of stuff, but here is my basic contract code:

MyContract.sol

contract Oracle {
    IAddressManager private addressManager;

    function Oracle(
        address _addressManager,
        bytes _eventName,
        bytes32[] _eventResultNames,
        uint256 _eventBettingEndBlock,
        uint256 _decisionEndBlock,
        uint8 _averageBlockTime,
        uint256 _arbitrationOptionMinutes)
        public
        payable
    {
        require(_addressManager != address(0));
        require(msg.value >= minBaseReward);
        require(_eventName.length > 0);
        require(_eventResultNames.length > 1);
        require(_decisionEndBlock > _eventBettingEndBlock);
        require(_averageBlockTime > 0);
        require(_arbitrationOptionMinutes > 0);

        addressManager = IAddressManager(_addressManager);
        eventName = _eventName;

        for (uint i = 0; i < _eventResultNames.length; i++) {
            eventResults.push(Result({
                name: _eventResultNames[i],
                votedBalance: 0
            }));
        }

        eventBettingEndBlock = _eventBettingEndBlock;
        decisionEndBlock = _decisionEndBlock;

        uint256 arbitrationBlocks = getArbitrationOptionBlocks(_averageBlockTime, _arbitrationOptionMinutes);
        arbitrationOptionEndBlock = decisionEndBlock.add(arbitrationBlocks);
        assert(arbitrationOptionEndBlock > decisionEndBlock);

        OracleCreated(_eventName, _eventResultNames, _eventBettingEndBlock, _decisionEndBlock,
            arbitrationOptionEndBlock, msg.value);
    }
}

MyContract would deploy fine before, but after adding the interface contract it runs out of gas. 1075835 gas without IAddressManager and 4712388 gas with it.

Why is it adding so much overhead when the contract code is very minimal?

Here is my test code:

beforeEach(async function() {
        let addressManager = await AddressManager.new();
        console.log(addressManager);
        console.log(addressManager.address);
        myContract = await MyContract.new(
            addressManager.address,
            testParams._eventName,
            testParams._eventResultNames,
            testParams._eventBettingEndBlock,
            testParams._decisionEndBlock,
            testParams._averageBlockTime,
            testParams._arbitrationOptionMinutes,
            { from: creator, value: baseReward, gas: 10000000 });
    });

EDIT 1

I was playing around with the code, and for some reason even passing the address _addressManager param in the constructor causes the Out of Gas error. Why is it doing this even if I don't try to create IAddressManager?

EDIT 2

Also tried to increase block gas limit to 10,000,000. No luck. It still always runs out of the gas and hits the limit.

EDIT 3

I went on Remix and did some tests to try to deploy the code on the Kovan testnet with Parity. So it looks like with the code the way it is, it costs ~100 Ether to deploy (WTF). I kept removing params and code to see what was causing this and it seems after everything, just removing the payable from the constructor seemed to fix the issue.

Anyone know why having this payable caused my contract deployment cost to skyrocket?


texts: Exception: Error: CONNECTION ERROR: Couldn't connect to node http://localhost:8501.


texts: Does Serpent/Solidity allow functions to jump into other functions?

texts: Do either Serpent or Solidity allow calling other functions in the same contract via a JUMP opcode, or do they only use CALL?


texts: updating variable inside and outside struct, different results, why?

texts:
With this, bool p does not update,

contract b {

        bool p;

    mapping(uint => bool) public t;

    function setValue() {
        bool b = t[1];
        b = true;
    }
    function checkValue() returns (bool) {
        return t[1];
    }
}

but with this, it does, why?

contract b {

    struct Info {
        bool p;

    }
    mapping(uint => Info) public t;

    function setValue() {
        Info b = t[1];
        b.p = true;
    }
    function checkValue() returns (bool) {
        return t[1].p;
    }
}


texts: Saving ether from a corrupt ether wallet

texts:
I have just recently opened a MyEtherWallet but I am having trouble. Can the wallets be corrupted? Is the ether lost or can it be saved?

I have successfully been able to send ether to the wallet address. I thought the wallet was working and so I sent some more ether. The account shows the full amount of ether sent.

However when I try to send ether from the wallet to another address the generate transaction button doesn't work.

As far as address to send to - I have tried the Donation button; I have tried the address from the Ether exchange I used to receive the ether in the first place; I have tried the DAO address. None has worked.

I have tried clearing my cache. This didn't change anything.

I also tried the method using off-line send transaction - both JSON and plain text private key - and both returned this message...

TypeError: Object.assign is not a function

Is there another method to use to remove the ether from the wallet? Could using Mist work or is the wallet corrupt? Is there a way to extract the ether from the wallet?

Is there something I can do to fix this? At the very least I would want to be ably to send the ether back to the exchange address.

Many thanks,

Daryl Watson


texts: Contract's Mapping variable state change fails when called from web3 js javascript program

texts:
I am running into a strange issue with following contract-

pragma solidity ^0.4.25;
contract ApprovedPOCreateAndOwnershipTransferContract {

    struct PO{
        bytes32 bill_to_location;
        bytes32 ship_to_location;
        bool exists;
    }

    //mapping(bytes32 => PO) poMap;

    mapping(uint256 => PO) poMap;

    event PODebugParameters(
        uint256 po_num,
        //bytes32 po_num_key,
        uint256 business_unit_id,
        bytes32 ipfs_hash,
        bytes32 bill_to_location,
        bytes32 ship_to_location,
        uint256 po_status_code,
        uint256 bill_to_location_code,
        uint256 ship_to_location_code,
        address maintain_org_add_map_contract_add_sender,
        address maintain_org_add_map_contract_add_receiver,
        address msg_receiver,
        uint256 supplier_id,
        uint256  status
    );

    /**
     * Method to save approved PO in BC raised from ERP,compute hash of string (PO_num + PO Last Update date)
     */
    function saveApprovedPONotSigned(uint256 po_num,
                                    uint256 business_unit_id,
                                    bytes32 ipfs_hash,
                                    bytes32 bill_to_location,
                                    bytes32 ship_to_location,
                                    uint256 po_status_code,
                                    uint256 bill_to_location_code,
                                    uint256 ship_to_location_code,
                                    address maintain_org_add_map_contract_add_sender,
                                    address maintain_org_add_map_contract_add_receiver,
                                    address msg_receiver,
                                    uint256 supplier_id,
                                    uint256  status) external {

        //chk for approved status of PO
        require(po_status_code == 1, "PO is not approved in ERP");

        //chk whether bill_to_location = 'Dallas' & ship_to_location = 'Florida'
        require(bill_to_location_code == 1 && ship_to_location_code == 2, "PO raised with incorrect billing or shipping locations");

        poMap[po_num].exists = true;
        poMap[po_num].bill_to_location = bill_to_location;
        poMap[po_num].ship_to_location = ship_to_location;

        emit PODebugParameters(po_num,business_unit_id,ipfs_hash,bill_to_location,ship_to_location,po_status_code,bill_to_location_code,ship_to_location_code,maintain_org_add_map_contract_add_sender,maintain_org_add_map_contract_add_receiver,msg_receiver,supplier_id,status);

    }

    /**
     * Method to verify for an existing PO in a bill_to_location & ship_to_location combination for ASN module
     */
    function verifyForExistingPO(uint256 po_num,bytes32 bill_to_location,bytes32 ship_to_location) constant external returns (bool){
        if (poMap[po_num].bill_to_location == bill_to_location && poMap[po_num].ship_to_location == ship_to_location){
            return true;
        }else{
            return false;
        }
    }

}

When I test this contract from remix the mapping variable is getting set but when I try testing using web3js(0.20.6) from a node js it program like below -

web3Obj.eth.sendTransaction({ from: sender_acct_info, to: contract_add, data: data, gasLimit: 105395, gasPrice: gasPriceHex }, function (err, result) {...});

The transaction gets mined mined but fails (I enabled debug trace also). The state of the variable is not changed.

Could anyone please help with this issue?

geth version -  1.7.3-stable

Thanks.


texts:
When we look at the earlier attempts to solve consensus problem in distributed systems, we encounter Raft and Paxo, are they analogous to what we see while comparing the technology behind Bitcoin vs Ethereum ?

Ref: http://ds.cs.ut.ee/courses/course-files/MartBakhoff-consensus.pdf


texts: Does the gas limit for AAVE transactions need to be so high?

texts:
There are two parts to the fee you pay for an Ethereum transaction - gwei and gas limit. Gwei is determined by how competitive (ie, congested) the Ethereum network is. As most people are aware, the amount of gwei required to get a transaction through has increased significantly, particularly in the last few months.
The other component of the fee is gas limit which is the maximum amount of gas that you're willing to spend on a particular transaction. It is estimated by the wallet you are using based on the complexity of the transaction youre trying to complete. So if you are just transferring eth, the gas limit will be lower than if you're interacting with a smart contract.
Anyway, my question relates AAVE. For some reason the gas limit suggested by my metamask wallet for AAVE transactions is really high, like almost 1,000,000 whereas most other smart contract transactions for other protocols are way way less, like 200k or 300k. I know it depends on the complexity of the transaction but the AAVE gas limit still seems ridiculously high. Does anyone know whether the gas limit for AAVE transactions can be reduced? Generally the advice is to only reduce gwei and not the gas limit. But when the gas limit is 930k, decreasing gwei only does so much.


texts: Faster way of getting contract property in Web3js

texts:
Using web3js 0.20.2 and truffle-contract, I have been getting public properties of my contract by doing

Foo.deployed().then(function(instance) {
    instance.rate.call().then((r) => {
        console.log(r)
    })
});

Came across a less verbose way of writing the same code [here], which does something like

Foo.deployed().then(function(instance) {
    console.log(instance.rate())
});

In the linked webpage, the author suggested the following where k is the contract instance:

for(i = 0; i < k.size(); i++) {
    someFunc( k.balances(k.addressLUT(i)) );
}

to avoid

for(i = 0; i < k.size(); i++) {
    k.addressLUT(i).call().then((res) => {
        k.balances(res).call().then((res) => {
            someFunc(res)
        })
    })
}

However when I try out the second method, why is instance.name() giving me a promise, similar to using instance.name.call()? Shouldnt we get the value immediately without waiting for the Promise to be resolved?

instance.rate()

> instance.rate()

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: BigNumber

instance.rate.call()

> instance.rate.call()

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: BigNumber


texts:
I am trying to understand what is the private key in Ethereum. Help please.

Private key = the address?
Private key = the password/passphrase?
Private key = the text seen when we open the file in the keystore folder?
Private key = something other than the above?


texts: Solidity CALL and DELEGATECALL: messages and data format

texts:
I have some questions about Solidity CALL and DELEGATECALL. I have already read some related threads (link), but found no answers to my doubts.

1) Is there any difference in performing a CALL to a function in a Solidity contract by directly calling the function (e.g. funct(arg1) ), or by using addressOfTheContract.call(bytes4(sha3("funct(uint256)")), _n)?

2) Is there any difference in performing a DELEGATECALL to a library function by directly calling the function (e.g. lib.funct(arg1) ), or by using addressOfTheLibraryContract.delegatecall(bytes4(sha3("funct(uint256)")), _n)? Let's assume that in both cases the library is imported with an import statement at the beginning of the contract.

3) Do both CALL and DELEGATECALL generate messages with the same format of a transaction (nonce, to, value, ...), except for the gasPrice and gasLimit fields?

4) Finally, do both CALL and DELEGATECALL take place locally on each node?


texts: Simple re-entrance attack example with fallback function

texts:
Here I am trying to invoke fallback function of A .Is it the right ? I am trying to understand the DAO attack by simple programs.

I need to send B's contract address in constructor A() .

pragma solidity ^0.4.8;

contract A {

    address destAdd;

    function A(address sendContractAddress)  {
        destAdd = sendContractAddress;
    }

    function () {
        uint transferAmt= this.balance;
        if (!msg.sender.call.value(transferAmt)()) throw;
    }
}

contract B {

    function() {

            // invoke fallback function of A
            bool ret = msg.sender.call('0xabcdefgh');
            if (!ret) throw;
        }
}


texts: Function takes input of 400 accounts, should output 400, outputs only 399. Why?

texts:
If more than 350 accounts are sent to this group-sorting algorithm, then it begins to just loose accounts. If 400 accounts are sent in, then only 399 accounts are added to hangoutGroups[][]

function commit(bytes32 POIuser) {
    uint groupNumber = uint(POIuser) / (uint(maxHash) / numGroups()) + 1;

    if(hangoutGroups[groupNumber].length >= groupSize) {
        for(uint i = 0; i < numUsers(); i++) {
            if(groupNumber - i >= 1) {
                if(hangoutGroups[groupNumber - i].length < groupSize) { groupNumber -= i; break; }
            }
            if(groupNumber + i <= numGroups()) {
                if(hangoutGroups[groupNumber + i].length < groupSize) { groupNumber += i; break; }
            }
        }
    }

    hangoutGroups[groupNumber].push(POIuser);
}

If the loop code is changed slightly then it outputs 400

function commit(bytes32 POIuser) {
    uint groupNumber = uint(POIuser) / (uint(maxHash) / numGroups()) + 1;

    if(hangoutGroups[groupNumber].length >= groupSize) {
        for(uint i = 0; i < 2; i++) {
            if(groupNumber - i >= 1) {
                if(hangoutGroups[groupNumber - i].length < groupSize) { groupNumber -= i; break; }
            }
            if(groupNumber + i <= numGroups()) {
                if(hangoutGroups[groupNumber + i].length < groupSize) { groupNumber += i; break; }
            }
        }
    }

    hangoutGroups[groupNumber].push(POIuser);
}

Then if the loop is incremented just one step, it looses an account again

function commit(bytes32 POIuser) {
    uint groupNumber = uint(POIuser) / (uint(maxHash) / numGroups()) + 1;

    if(hangoutGroups[groupNumber].length >= groupSize) {
        for(uint i = 0; i < 3; i++) {
            if(groupNumber - i >= 1) {
                if(hangoutGroups[groupNumber - i].length < groupSize) { groupNumber -= i; break; }
            }
            if(groupNumber + i <= numGroups()) {
                if(hangoutGroups[groupNumber + i].length < groupSize) { groupNumber += i; break; }
            }
        }
    }

    hangoutGroups[groupNumber].push(POIuser);
}

This is the output for the loop with < numUsers(), 399 accounts

0, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 0

This is the output if the loops is limited to 2, 400 accounts

0, 6, 5, 1, 3, 4, 5, 5, 7, 5, 1, 4, 3, 5, 5, 5, 5, 5, 7, 6, 6, 7, 7, 7, 5, 2,
5, 5, 4, 5, 5, 5, 3, 5, 5, 5, 3, 3, 5, 5, 4, 3, 5, 2, 5, 5, 7, 6, 5, 5, 1, 5,
7, 5, 4, 5, 6, 5, 6, 7, 8, 6, 5, 5, 4, 5, 5, 5, 8, 8, 8, 6, 7, 6, 5, 5, 4, 4,
5, 5, 4, 0

This is the output if the loop is incremented to 3, 399 accounts

0, 5, 5, 1, 3, 4, 5, 5, 5, 5, 3, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 5, 5, 4,
5, 5, 4, 5, 5, 5, 3, 5, 5, 5, 3, 3, 5, 5, 4, 3, 5, 2, 5, 5, 7, 6, 5, 5, 3, 5,
5, 5, 5, 5, 5, 5, 6, 7, 8, 6, 5, 5, 5, 5, 6, 5, 6, 6, 9, 7, 7, 5, 5, 5, 5, 4,
5, 5, 4, 0

The accounts are generated by this code, and I've used hashes to simulate accounts

bytes32[] public fourHundredAddresses;

function generateFourHundredAddresses() {
    for(uint i = 0; i < 400; i++) {
        fourHundredAddresses.push(sha3(i));
        numUsers++;
    }
}

function batchRegisterOne() {

    for(uint i = 0; i < fourHundredAddresses.length; i++) {
        commit(fourHundredAddresses[i]);
    }
}

The rest of the code

mapping(uint => bytes32[]) public hangoutGroups;

uint groupSize;
uint public numUsers;

    bytes32 maxHash = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
    function numGroups() returns(uint){ return numUsers / groupSize;}

    function poi() {
        groupSize = 5;
    }


texts: How to deploy contract in parity-ethereum use json-rpc

texts: I'm using atomic swap to exchange money in 2 private blockchain. I used json-rpc to create 2 private chain and created HTLC (Hash time lock contract) to exchange. But I don't know how to deploy contract in private chain. Please help me how to deploy contract in private chain. Can I use remix and metamask to deploy contract?


texts: Ethos 1.3.0 drops hashrate on RX 560 4GB card

texts:
After upgrading my Ethos to 1.3.0 from 1.2.9, the hashrate of RX 560 becomes very low. Initially there was gpu clock problem error. After playing with the flags in local.conf, I was able to get rid of the error. Here is the config I end up with:

flags --cl-global-work 16384 --farm-recheck 300

But the hashrate of 4 RX 560 cards is very low. It was 10.5mh before. But it is only 2.21 - 7.76mh:

  ¹  13:03:45|ethminer   Accepted.
  m  13:03:45|ethminer  Speed   2.21 Mh/s    gpu/0  2.21  [A2+0:R0+0:F0] Time: 00:14
  m  13:03:46|ethminer  Speed   7.65 Mh/s    gpu/0  7.65  [A6+0:R0+0:F0] Time: 00:14
  m  13:03:46|ethminer  Speed   7.13 Mh/s    gpu/0  7.13  [A6+0:R0+0:F0] Time: 00:14
  m  13:03:46|ethminer  Speed   7.76 Mh/s    gpu/0  7.76  [A5+0:R0+0:F0] Time: 00:14

The motherboard is ASUS EX-B250-V7 6 GPU with latest BIOS. What are the parameters I need to adjust to have normal hashrate on RX 560? Many thanks.


texts: finding the wallet address for good ETH showing on Etherscan.io

texts: I bought ETH from a BTC exchange and it went through ShapeShift. I sent them a wallet address. It has been too long and I don't know the wallet provider I used. The ETH is good on Etherscan. How do I move it to a wallet like MEW? TYIA


texts: How can you work around Web3 1.0s bug to check for transaction confirmation?

texts:
The following includes a null Tx id:

web3.eth.getTransaction('0x2fc36f9c6593bc1232b3466832c6ee38b5b2b3b4a54be3f6c68fb06e8d82e452', function(error, result){
  if (!error) {
    console.log(result.blockNumber)
  }
})

You would expect this to log null or undefined, but it throws in Web3.js 1.2.1. This makes it impossible to use getTransaction with polling to see if a transaction is confirmed.

checkTx()
function checkTx() {
    web3.eth.getTransaction('0x2fc36f9c6593bc1232b3466832c6ee38b5b2b3b4a54be3f6c68fb06e8d82e452')
        .then((result) => {
            if (result.blockNumber != null) {
                console.log(result.value)
            } else {
                console.log('Not confirmed.')
                setTimeout(() => { checkTx() }, 1000)
            }
        })
}

In both case you get this error when the Tx blockNumber is null: TypeError: Cannot read property 'blockNumber' of null

How can I check that a transaction id is confirmed by polling if I can't evaluate the property of the blockNumber?


texts: Trying to sync fast but get "flag provided but not defined"

texts:
Blockchain sync was taking forever, so I tried running get --fast after extracting keychain keys and the chaindata folder and the running get --fast. I get "flag provided but not defined".

How should I go about this. I'd like to sync the whole blockchain from scratch quickly.


texts: Time-dependent test unexpected behavior at 1st attempt, expected behavior at 2nd attempt

texts:
I'm trying to test a contract in which functions should require certain timestamps. Parts of code are eliminated for readability:
Here's the problematic part of the contract :
PCE_Contract.sol
pragma solidity ^0.7.0;

contract PCE_Contract{

constructor(uint256 newStartTime, uint256 PERIOD)
{
_PERIOD     = PERIOD * 1 days  ;
 initiation = newStartTime     ;
}

 function enter() payable public
  {
    require(( block.timestamp < (initiation + _PERIOD) ),
     "Period for this function has ended." );
    // do stuff
  }
}

I'm simulating time using the info found in this article.
PCE_Contract_test.js
const expected_period           = 7     ;
const SECONDS_IN_DAY            = 86400 ;

const Mon_01_Jun_00_00_UTC_2020 = 1590969600; // 06-01-2020 @ 12.00 am (UTC)
const Mon_09_Jun_13_00_UTC_2020 = 1591660800; // 06-09-2020 @ 01.00 pm (UTC)

contract('PCE_Contract', async (accounts) =>
{
  before( async () => {

    instance_1 = await PCE_Contract.new(Mon_01_Jun_00_00_UTC_2020 ,expected_period );
    instance_2 = await PCE_Contract.new(Mon_09_Jun_13_00_UTC_2020 ,expected_period );
  });
const expected_address          = accounts[1];

// more tests using instance_1

  it("No entry after period is over, OK", async() =>
  {
    await test_helper.advanceTimeAndBlock(SECONDS_IN_DAY * (expected_period ));

    await instance_2.enter({ from: expected_address, value: String(1e18)});

  });

}

I expected the test to fail, since _PERIOD time has passed since instance_1. However, in the first test run the test passes.
The interesting part is that when I run the test for a second time (which will start from the timestamp 1st test ended at) The test fails (expected behavior).
Why does the 1st test's time-simulation fail even though I can see time has passed in ganache-cli ?
How can I fix the issue so that I can test functions in two time periods ?
ganache-cli output for two tests that have time-jump between:
  Transaction: 0xbb9e5b0e3ee1bc266d79ebe169061259c4832cbbc175b63ff1719aa125cf06a3
  Gas usage: 40655
  Block Number: 10
  Block Time: Mon Jun 01 2020 03:00:24 GMT+0300 (GMT+03:00)
  Runtime Error: revert
  Revert reason: ERROR

eth_call
eth_blockNumber
evm_increaseTime
evm_mine
eth_getBlockByNumber
eth_getBlockByNumber
eth_getBlockByNumber
eth_sendTransaction

  Transaction: 0x43578162490a3edf734c17462056f2090b3775a2a90228a0097da53c42319afb
  Gas usage: 112357
  Block Number: 12
  Block Time: Tue Jun 09 2020 03:00:24 GMT+0300 (GMT+03:00)

Truffle v5.1.49
Ganache CLI v6.12.1 (ganache-core: 2.13.1)
Node v12.18.4


texts: Hey is it possible to run Geth/Parity + mine on a Windows 32bit machine? I'm having trouble finding anything.


texts: How can I get Digix Dao ethereum tokens off of an exchange (coinbase)

texts:
Basically what happened is that I tried to trade 30 ether for digix dao tokens using shapeshift. I entered an ethereum address on myetherwallet as the destination address where I wanted the DGD to go since I would actually have access to the tokens there. Instead, shapeshift apparently had problems with the trade initially so I emailed them. After 3 days, they finally sent the DGD tokens but they didn't send them to the address I provided, but instead sent them to the address I originally sent the ether from, which is a coinbase wallet. WTF why do you think I wanted you to send them to a different address?

I can now see when looking up this ethereum address on etherscan that the DGD tokens are there, but I don't have access to them because these idiots sent my tokens to an exchange. Basically what I want to know is how can I get these tokens off of my coinbase address and into the myetherwallet address where I wanted them to go originally? Since coinbase doesn't keep track of any token balances so these tokens will not show up in my coinbase account. Is there anyone I could contact at coinbase who might be able to help? I already tried sending a regular support ticket to coinbase and that got me nowhere, which doesn't surprise me because I'm pretty sure it's not every day someone has a problem like this.

The thing I'm most concerned about is not being able to collect the quarterly rewards that you get with the digix dao tokens if they remain on an exchange which is the main reason I want to get them off.

TL, DR: I have DGD tokens in an ethereum wallet on coinbase. How do I transfer these tokens to a different ethereum wallet? If you want to know why I have DGD tokens in a coinbase wallet, you would actually have to read the whole thing.


texts: How to backup and restore a Geth server in full mode?

texts:
I had the experience of losing a Geth server due to some unknown software issues and whatever I could do for that time was moving keystore files to a new server. But it was a Geth server in fast mode.
After that, I ran a new server in full mode and it tooks much time to be synced completely. I wonder to know how can I backup a Geth server completely and run a new server using the backup file?
I did something in this case but none of them was not successful.
Scenario 1:

Create a new server to restore (Server #2)
Copy all keystore files to new server from server #1
Copy all files in ~/.ethereum/geth/chaindata from server #1 to the same path in server #2
Run the Geth on server #2 using the same command as server #1

Scenario 2:

Create a new server to restore (Server #2)
Run geth export filename on server #1 and move the file to server #2.
Run geth import filename on server #2.
Run the Geth on server #2 using the same command as server #1

Note:
I was expected the export feature will create a full backup of server and after running import command, I would have a complete restored server, but this did not happen!
Regarding to what is mentioned above, my questions are:

What does export & import command do exactly and how can I use them in an appropriate way?
What is the best way of backup a Geth server in full mode with a huge amount of data and restore it completely on a new server?


texts: MetaCoin contract initializing with no value - Issue with Solidity contract constructor

texts:
I'm currently trying to get my contract Guess own another contract, MetaCoin, so that it initializes with 10k MetaCoin.

Here is the MetaCoin contract:

contract MetaCoin {
 address owner;

 mapping (address => uint) balances;

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

 function MetaCoin(address caller) {
      owner = caller;
      balances[msg.sender] = 10000; //Although this uses msg.sender, I've tried using owner and caller as the arg as well.
 }

 function coinsOwned() returns(uint){
      return balances[this];
 }

 function getOwner() returns(address){
      return owner;
 }

 function sendCoin(address receiver, uint amount) returns(bool sufficient) {
      if (balances[msg.sender] < amount) return false;
      balances[msg.sender] -= amount;
      balances[receiver] += amount;
      Transfer(msg.sender, receiver, amount);
      return true;
 }

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

}

The owner is properly initialized (getOwner correctly returns Guess's address), but the balance is not. I'm unsure on what the issue is, whether it's the constructor, or the way I'm deploying it through truffle.
I don't believe that the coin is being sent to another account, because none of the accounts generated by testrpc have the 10k, and neither Guess nor MetaCoin own the coin either. Does anyone know what's happening?

Here is my deploy code as well (using Truffle)

module.exports = function(deployer) {
  deployer.deploy(Guess).then(function(){
    return deployer.deploy(MetaCoin, Guess.address);
  });
};

The contract Guess is essentially blank, with a no arg constructor that doesn't do anything.


texts: Jaxx transaction stays on pending confirmation

texts:
Last night I tried to send ether to an address from my jaxx wallet. But seems that the fee which I set (80000 gas limit -> 10 Gwei) is very low and the transaction stayed in pending status for over 10 hours. Can I somehow cancel this from the jaxx wallet and resend it - I don't see such a button. Or to restore my wallet to MyEtherWallet and try to resend the transaction with bigger fee from there. If the second is completed is the first will be cancelled automatically when there are no sufficient funds once it is tried to be sent some day in the future.
Thanks for your help,
Georgi


texts: Is it possible to pass multiple arguments in require() in solidity

texts:
I was going through the Solidity Exception-Handling examples and I saw below example:

pragma solidity ^0.4.0;
contract VendingMachine {
function buy(uint amount) payable {
    if (amount > msg.value / 2 ether)
        revert("Not enough Ether provided.");
    // Alternative way to do it:
    require(
        amount <= msg.value / 2 ether,
        "Not enough Ether provided."
    );
    // Perform the purchase.
 }
}

I'm getting multiple errors when trying to execute it on Remix saying that the 2 arguments given expected 1.
So, I want to know that Is this support is deprecated now or Do I have to use a specific solidity version?

link: Exception-handling example