texts: Setting mapping value in constructor has no effect?

texts:
In the following smart contract:

pragma solidity ^0.4.20;

contract MyCoin {
  uint _totalSupply;
  mapping(address => uint) public balances;

  function MyCoin() public {
    _totalSupply = 1;
    balances[msg.sender] = 1;
  }
}

If I create the contract as myAddr, and then call balances(myAddr), I should expect to get back 1, right? However, I get back 0 as the result. What is the explanation?

Maybe worth noting that I'm using remix and the Javascript VM for this, perhaps it's a bug in this particular VM implementation? Still, it seems too basic to be a bug.


texts:
I'm new in solidity language and i want learn but when i try to use approve, allowance and transferFrom on testnet of bsc.
I'm looking for a simple contract that will allow me to take user funds and send them to another address.
I'm just looking for a sample contract with approve, transferFrom and solidity 0.8.
Thanks for reading
pragma solidity ^0.8.4;

interface IERC20 {
/**
 * @dev Returns the amount of tokens in existence.
 */
function totalSupply() external view returns (uint256);

/**
 * @dev Returns the amount of tokens owned by `account`.
 */
function balanceOf(address account) external view returns (uint256);

/**
 * @dev Moves `amount` tokens from the caller's account to `recipient`.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transfer(address recipient, uint256 amount) external returns (bool);

/**
 * @dev Returns the remaining number of tokens that `spender` will be
 * allowed to spend on behalf of `owner` through {transferFrom}. This is
 * zero by default.
 *
 * This value changes when {approve} or {transferFrom} are called.
 */
function allowance(address owner, address spender) external view returns (uint256);

/**
 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * IMPORTANT: Beware that changing an allowance with this method brings the risk
 * that someone may use both the old and the new allowance by unfortunate
 * transaction ordering. One possible solution to mitigate this race
 * condition is to first reduce the spender's allowance to 0 and set the
 * desired value afterwards:
 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 *
 * Emits an {Approval} event.
 */
function approve(address spender, uint256 amount) external returns (bool);

/**
 * @dev Moves `amount` tokens from `sender` to `recipient` using the
 * allowance mechanism. `amount` is then deducted from the caller's
 * allowance.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

/**
 * @dev Emitted when `value` tokens are moved from one account (`from`) to
 * another (`to`).
 *
 * Note that `value` may be zero.
 */
event Transfer(address indexed from, address indexed to, uint256 value);

/**
 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
 * a call to {approve}. `value` is the new allowance.
 */
event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract Owner
{

    //0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12Ee busd

    //IERC20(0x98e0Ce598a5536C89C5d1D4264f0Fa4E21FA16fF);

function balance() external view returns (uint256) {
    return IERC20(0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12Ee).balanceOf(msg.sender);
}
function approbation(uint _amount) external returns (bool) {
    return IERC20(0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12Ee).approve(address(this), _amount);
}

function allowance(address owner, address spender) external view returns (uint256) {
    return IERC20(0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12Ee).allowance(owner, spender);
}
function transferFr(uint _amount) external {
    IERC20(0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12Ee).transferFrom(msg.sender, address(this), _amount);
}
}


texts:
I need some help in translating a simple contract from Solidity into Vyper.

contract myCoin {
        mapping (address => uint) coinBalanceOf;
        string coinName;
constructor(uint _supply, string memory _name) {
        coinBalanceOf[msg.sender] = _supply;
        coinName = _name;
}
function sendCoin(address receiver, uint amount) public {
        if (coinBalanceOf[msg.sender] >= amount) {
                coinBalanceOf[msg.sender] -= amount;
                coinBalanceOf[receiver] += amount;
        }
}
function balance() public view returns (uint) { return coinBalanceOf[msg.sender]; }
function name() public view returns (string memory) { return coinName; }
}

Can anyone help me out?
Many thanks in advance!
BG,troy


texts: Are there different clients for Quorum compared to Ethereum?

texts:
Is it correct to say the following?

Ethereum clients run Ethereum nodes. Geth and Parity are examples of Ethereum clients.

Quorum clients run Quorum nodes.  Is there an equivalent to Geth and Parity for Quorum or can they also be used to run Quorum nodes?

Thanks
Madeline


texts:
I am a beginner.

I would like to 3 mappings

I know 2 mapping looks like this:

mapping (address => mapping (address => uint256)) public allowed;

and my question is: is 3 mappings look like this ?

mapping (address => mapping (address => mapping (address => uint256))) public allowed;

anyone can answer my question I will be appreciated


texts:
Mist shows that I have 1 ETH in my account. When I check etherscan see exactly 0.99895 ether in my account....

I would like to send all 0.99895 ether to another address. When I try to send exactly that amount, I get an error saying not enough funds.

MIST also shows me "0.00105 ETHER FEE". When I deduct that from the total (try to send 0.99790) it also tell me not enough funds.

How on earth do I sent this entire amount? Thanks!


texts:
I know that generally it cost 5,000 gas to initialize memory variable. But simple smartcontract shows me that I misunderstand something.

pragma solidity ^0.4.24;

contract MemConsumption {
    uint256 a;
    uint256 b;
    uint256 c;
    uint256 d;

    struct My {
        uint256 a;
        uint256 b;
        uint256 c;
        uint256 d;
    }

    function set(uint256 _a, uint256 _b, uint256 _c, uint256 _d) public {
        a = _a;
        b = _b;
        c = _c;
        d = _d;
    }

    function test() public view returns (uint256) {
        return calc(My(a,b,c,d));
    }

    function calc(My my) private pure returns (uint256) {
        My memory m = My(my.a, my.b, my.c, my.d);

        return m.a + m.b + m.c + m.d;
    }
}

Function set expectedly cost ~100k gas - allocates 4 32-bytes words in storage.

But call of test confused me. I supposed it will cost me:

transaction call cost (~20,000);
gas for memory allocation of  parameter My instance (it is passed by value as memory one) i.e. 5,000 * 4 = 2,0000;
gas cost of memory instantiation of memory m variable;

But in Remix I see that transaction cost is 22745. Why?


texts: Remix IDE: How to get rid of the stated warning message on the online Remix IDE

texts:
I am trying to compile the following contract on Remix IDE.

pragma solidity ^0.5.1;

contract ProofofExistence{
   event ProofCreated(
      uint256  indexed id,
      bytes32 documentHash);//an event can be listened by any client

   address public owner;//getters are already generated for public variables
   mapping  (uint => bytes32) hashesById;

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

   modifier noHashExistsYet(uint256 id) {
      require(hashesById[id] == "");
      _;
   }//The modifeir can be prepended to any function

   constructor() public {//constructor is executed when the contract s created
      owner = msg.sender;
   }

   function notarizeHash(uint256 id, bytes32 documentHash) onlyOwner noHashExistsYet(id) public{
      hashesById[id] = documentHash;
      emit ProofCreated(id, documentHash);//Proof created event is emited to the block chain
   }//The core function of this contract allows its owner
   //to confirm a document id with a certain content

   function doesProofExist(uint256 id, bytes32 documentHash) public view returns (bool) {
      return hashesById[id] == documentHash;
   }//view/constant functions are read-only and do not cost gas
}

I am getting following warning message:

  Use assert(x) if you never ever want x to be false, not in any
  circumstance (apart from a bug in your code). Use require(x) if x can
  be false, due to e.g. invalid input or a failing external component.

Can somebody please guide me how to get rid of the above warning message?

Zulfi.


texts:
I am wondering, what is the purpose of the EXTCODECOPY bytecode instruction? I don't see any advantage in copying the code of another contract in memory.

I am a little bit confused, because of the existence of other instructions, such as DELEGATECALL that really "use" the code of another contract


texts: Can I mine on my private blockchain using geth with rpc?

texts:
I am using the web3 api and want to try out mining using rpc.
The usual miner.start() (which is used on terminal) does not work even after including the miner api when starting geth and I get the following error.

  Error: Cannot read property start of undefined.

What am I missing?


texts:
In hardhat, I want to access a contract outside my project in my tests.
In my hardhat.config.js I am able to reference external contracts no problem with an ABI and a contract address, like so:
const tkn1 = new ethers.Contract(ADDRESS, ABI, signer)

However, in my test files, I am getting ethers is not defined when trying to do the same thing. Where am I going wrong?


texts:
So I was using keythereum to generate public and private keys.
const dk = ethereum.create();
parameters.address = ethereum.privateKeyToAddress(dk.privateKey);
parameters.pKey = dk.privateKey.toString('hex');

Now I have send some ETH to the generated wallet and it worked. The challenge I am facing is with withdrawal.
Anyone knows how I can withdraw the ETH from the generated wallet, I tried searching with no luck.
I know for BTC we can use blockchain.info to import the private keys. Is there a similar service for ETH too.
Thank you so much


texts:
How to sign on ethereum a pdf like on this video?

I'm asking specifically about what happens at 00:40 where you have a user
uploading the file and then it get stored and cryptographic signature is receive,
how to create that functionality?
https://vimeo.com/239155784


texts: Cannot connect myetherwallet to a geth private chain: (error_33) Could not connect to the node

texts:
I follow the MyEtherWallet: Use Your Own Server Guide to use MyEtherWallet on my private ethereum network. I am doing this setup on my node, where my ethereum node runs. My node runs fine, it can mine and connect to other peers.

I get error 33 when I try to connect to custom node with MEW on my server.

Started the node on my server  like this:

nohup sudo geth --port 30304 --rpc --rpcaddr "0.0.0.0" --rpcport 8101 --rpccorsdomain "*" --rpcapi="eth,net,web3,utils" --datadir myDataDir --networkid 19720502 --bootnodes="enode:////cf2a1e3bb2cfe5a8aed058b609d6f4c844238e44425a7b24e422ce61cd971257859db2a8c4584acfe9bd65ffbec78d7db5cba14cbf32953f8f5c94e08135b20c@46.231.206.125:30304" &

On my server I downloaded MEW 3.11.2 changed nodeIP.json and put in the IP adress 46.231.206.125 instead of x.x.x.x changed the ports from 8584 to 8101 in the file response.js made sure ssl is installed (https://sslanalyzer.comodoca.com/?url=46.231.206.125).

Switched off apache (because port 80 was busy) using https://www.cyberciti.biz/faq/ubuntu-linux-start-restart-stop-apache-web-server/

Then I typed:

sudo node runServer.js

it runs without errors however if I try to connect via MEW custom node https://46.231.206.125 port 8101 clicking on custom and networkid in eip1155

I get

(error_33) Could not connect to the node. Refresh your page, try a different node (top-right corner), check your firewall settings. If custom node, check your configs.

Question: What can I do to find out what the problem could be?
Question: Where can I find the source of this error?

Here is some background information:

However if I do this locally on my machine it all works, I can access the local node when I do this:

change nodeIP.json and put in the IP Address 127.0.0.1, change in response.js the ports to 8101, sudo node runLocalServer.js and access it by opening MEW locally and using http://127.0.0.1 port 8101 clicking on custom and typing in the correct networkid in eip1155.


texts: Making function calls exclusive per block

texts:
I have the requirement that in my smart contract certain functions cannot be called, if another function already has been called inside the same contract during the same transaction.
Imagine I have the functions A, B and C. If function A or B is called, function C should not be callable inside the same transaction.
This is my approach so far: When A or B is called, store the following values with a modifier

tx.origin: I can't rely on msg.sender, as someone could deploy 2 smart contracts in one transaction, call A with one contract and C with the other
block.number

when C is called, check if tx.origin and block.number are the same as the stored values and revert if necessary.
This should ensure that C cannot be called if A or B were called in the same block by the same person. Is there a flaw in my logic here?


texts: How to get value of input parameters from Transaction history

texts:
I would like to read a successful transaction on an ETH block and I would like to get the values of input parameters that were passed to the function for that transaction. I am not talking of the
data field in the transaction. And I am aware of using TransactionReceipt from web3 in my webapp to look at other details of this transaction.

For example, I have a method in the contract:

 function setName(string n) {.....}

Now when this function was called as contract.setName("Abcde")....
Now sometime in future as part of audit, I would like to use the transaction id and read transaction details and read the value "Abcde" that was passed to this function for that particular transaction.

I want to know if this is possible and if it is, how do I do it.


texts: What is the username / node ID in an enode URL?

texts:
Looking at https://github.com/ethereum/wiki/wiki/enode-url-format and https://github.com/ethereum/go-ethereum/wiki/Connecting-to-the-network I can see that the enode URL includes some information about the node.

Here's an example enode URL: enode://3414c01c19aa75a34f2dbd2f8d0898dc79d6b219ad77f8155abf1a287ce2ba60f14998a3a98c0cf14915eabfdacf914a92b27a01769de18fa2d049dbf4c17694@[::]:30303 - the part between // and @ is the username.

Everything else seems ok, but what is the username / node ID part? The answer at https://ethereum.stackexchange.com/a/1196/31933 says it's some public key, but a public key for what?

As accounts and nodes are not directly related (accounts just utilize nodes) it can't be anything account-specific (such as account's public key). So if it is a public key, who has the private key and what can it be used for?


texts: Why does solidity check only the first 4 bytes of the calldata to determine the method?

texts:
I was doing research on EVM and solidity and I came across this fact that the calldata/input data is created using RLP encoding and stuff. I know the process and I don't want to elaborate on that. My question is, what is the logic or maths behind choosing the first 4 bytes of data for identifying the method? Why not 5? Why not some other number?
For example if the call data is:    0xee919d50000000000000000000000000000000000000000000000000000000000000001
Then why do we take only the first 4 bytes, i.e., ee919d50 as the method id and not more or fewer bytes?

I also read from the first answer to this question: How does the EVM find the entry of a called function? that said that if you want to implement your own logic, you can consider the first 8 bytes of data instead of first four bytes. I am interested in knowing the actual reason for selecting the number "4".

I would appreciate if someone could explain or point a resource that has a detailed explanation of this question.


texts: How does one retrieve revert/require error messages from RPC

texts:
In both of these questions, the user is asking if it's possible to get the error string from a revert or require. The answers say, basically, "Yes" and point to Truffle or other methods.

VM Exception while processing transaction: revert message

Getting error message from require()

My question is not "Can you get the error string?" but "How do you get the error string?"

Can someone explain to me how one might get the error string by querying directly against the node with the RPC (i.e. by using curl or similar, not using web3.js).


texts:
We're working with the project in which we're storing some confidential details (different for each user)in smart contract, we don't want to show this information to anyone else even miner, thus we are planing to use pure function. As pure function will not change the state of the Blockchain and miner won't execute pure function's transaction.

But that all are our assumption, we would like to understand how pure function works!

For instance, consider following smart contract.

contract Sample {

    function mul(uint _a, uint _b) external pure returns(uint) {
        return (_a * _b);
    }
}

1) Where the pure function get executed?

2) Anything which change the state of the blockchain is verified by miners. Will miner perform any role in this type of execution?

3) If miner will execute it, will they able to see the value of a and b?

Edit:

We're working on some requirement, where each user can claim the reward, but we don't want to make it visible(reward amount) to other users, only admin and particular user who got reward only should be knowing the same.


texts:
How do i convert a string into a int?
here is my code:

   pragma solidity ^0.4.6;

contract MyContract {
    string public a;
    /* Constructor */
    function MyContract() {
        a = "0.12312317314571638713891378174163782169246891247193811231231731";
    }

    function bytesToUInt(uint v) constant returns (uint ret) {
    if (v == 0) {
        ret = 0;
    }
    else {
        while (v > 0) {
            ret = uint(uint(ret) / (2 ** 8));
            ret |= uint(((v % 10) + 48) * 2 ** (8 * 31));
            v /= 10;
        }
    }
    return ret;
}

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


texts: How to verify a deployed contract on etherscan

texts:
I would love to get some help with this as I'm wracking my brain with how to get this done.

I have gone through this link to verify my contract:
https://etherscan.io/verifyContract

I am puzzled with where to start, I created a Wallet Contract in Ethereum Wallet, and not sure where to gather this info to paste in there.

If someone can help me I would gladly tip some ETH to make it worth your time to walk a newb through the process.


texts: Smart contract not deploying complaining of gas ()

texts:
Here is the error it shows

Here are the warnings

https://gist.github.com/libracoder/82b52edf45e1e389fc0ea832c4b88307


texts: Altering / overriding the method from main contract

texts:
I am using openzeppelin to create a ICO as a CappedCrowdsale and TimedCrowdsale as mentioned in the example mentioned in the below link.

Reference : https://github.com/buddies2705/Solidity-Tutorial/blob/master/contracts/ExampleTokenCrowdsale.sol

The finalized() method in FinalizableCrowdsale is the accessible method in the contract as shown in MEW. This method is as of now checking only whether the contract is closed or not by checking only the closing time. I want to alter this method to finalize it even if the cap is reached (or) time is over.

Question:

How to alter the finalize() method in FinalizableCrowdsale from SampleCrowdsale. This is to include the capReached() check ?
How to change the variable _finalized which is in finalize() method of FinalizableCrowdsale. Please note that I need to do this from SampleCrowdsale contract without altering the open-zeppelin library  ?

Please assist

contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale {

constructor(
uint256 openingTime,
uint256 closingTime,
uint256 rate,
address wallet,
uint256 cap,
ERC20Mintable token,
uint256 goal
)
public
Crowdsale(rate, wallet, token)
CappedCrowdsale(cap)
TimedCrowdsale(openingTime, closingTime)
RefundableCrowdsale(goal)
{
//As goal needs to be met for a successful crowdsale
//the value needs to less or equal than a cap which is limit for accepted funds
require(goal <= cap,"Goal <= Cap is an requirement");
}

}

Below contracts are from open-zeppelin library which I do not want to alter

RefundableCrowdsale

contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;

// minimum amount of funds to be raised in weis
uint256 private _goal;

// refund escrow used to hold funds while crowdsale is running
RefundEscrow private _escrow;

/**
* @dev Constructor, creates RefundEscrow.
* @param goal Funding goal
*/
constructor(uint256 goal) internal {
require(goal > 0);
_escrow = new RefundEscrow(wallet());
_goal = goal;
}

/**
* @return minimum amount of funds to be raised in wei.
*/
function goal() public view returns(uint256) {
return _goal;
}

/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
* @param beneficiary Whose refund will be claimed.
*/
function claimRefund(address beneficiary) public {
require(finalized());
require(!goalReached());

_escrow.withdraw(beneficiary);
}

/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return weiRaised() >= _goal;
}

/**
* @dev escrow finalization task, called when finalize() is called
*/
function _finalization() internal {
if (goalReached()) {
_escrow.close();
_escrow.beneficiaryWithdraw();
} else {
_escrow.enableRefunds();
}

super._finalization();
}

/**
* @dev Overrides Crowdsale fund forwarding, sending funds to escrow.
*/
function _forwardFunds() internal {
_escrow.deposit.value(msg.value)(msg.sender);
}

}

FinalizableCrowdsale

contract FinalizableCrowdsale is TimedCrowdsale {
using SafeMath for uint256;

bool private _finalized;

event CrowdsaleFinalized();

constructor() internal {
_finalized = false;
}

/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() public view returns (bool) {
return _finalized;
}

/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public {
require(!_finalized);
require(hasClosed());

_finalized = true;

_finalization();
emit CrowdsaleFinalized();
}

/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super._finalization() to ensure the chain of finalization is
* executed entirely.
*/
function _finalization() internal {
}
}


texts: Solidity & truffle: get elements from strings array

texts:
i'm glad to follow this forum, it is very helpful.
I'm using truffle to develop contracts and i just found that dynamic arrays are not yet suported, for that reason i was using string arrays with a fixed lenght and i found that the element with index 0 is not showing anything and last one says undefined. do you know ay reason of that?, do i have to get elements in a different way??

This is the function in solidity:

pragma solidity ^0.4.21;
pragma experimental ABIEncoderV2;

contract Example {
    function getStringArray() public returns (string[]) {
        string[] memory resultStr = new string;
        resultStr[0] = "355555555";
        resultStr[1] = "2";
        resultStr[2] = "8888";
        return resultStr;
    }
}

I also did a test with truffle like this:

in javascript i test getting elements one by one and i got this:

var ExampleCont = artifacts.require("Example");

contract('ExampleCont', async(accounts) => {
    before(async () => {
    ExampleContract = await ExampleCont.new();
    });
    it('Upload File', async () => {
        let stringArray = await ExampleContract.getStringArray.call();
        console.log("list size=" + stringArray.lenght+"0="
              + stringArray[0] + "1="+stringArray[0]+", 2=" + stringArray[1] + "3=" + stringArray[2]);
    }
}

list size=3, value 0= , 1=355555555, 2=2, 3=undefined

any idea about what's happening in this case?, how do i have work well with string arrays to get all elements?


texts: Parsererror : expected identifier got 'Assign'

texts:
I am doing a udemy course and can't get the code to work even though I copied from the instructor to try and get it to work.

Error: Parsererror: expected identifier, got 'Assign' totalSupply = initialSupply;

Thanks in advance!

Here is the full code:

pragma solidity ^0.4.16;

contract Token {
mapping (address => uint256) public balanceOf;
string public name;
string public symbol;
uint8 public decimal = 18;
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);

function Token(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits){
 balanceOf[msg.sender
 ]= 1000;
 totalSupply = initialSupply;
 decimal=decimalUnits;
 "GD" =tokenSymbol;
 "gadget" = tokenName;
}

//Might have to check > signs
function transfer(address _to, uint256 _value){
    require(_to != 0x0);
    require(balanceOf[msg.sender] >_value);

    require(balanceOf[_to] +_value > balanceOf[_to]) ;

    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;
    Transfer(msg.sender, _to, _value);

}

}

contract AssetToken is admined, Token {

function AssetToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits, address centralAdmin) Token(0, tokenName, tokenSymbol, decimalUnits){
totalSupply = initialSupply;
if(centralAdmin != 0){
    admin = centralAdmin;
}
else
{
    admin = msg.sender;
}
balanceOf [admin] = initialSupply;
totalSupply = initialSupply;
}}

function mintToken(address target, uint256 mintedAmount) onlyAdmin{
    balanceOf[target] += mintedAmount;
    totalSupply += mintedAmount;
    Transfer(0, this, mintedAmount);
    Transfer(this, target, mintedAmount);
}
}

function(address _to, uint256 _value){
    require(balanceOf[msg.sender] <0);
    require(balanceOf[msg.sender] <_value);

    require(balanceOf [_to] + _value < balanceOf[_to]);

    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += value;
    Transfer(msg.sender, _to, _value);
}
}
}
}


texts: After transfered the ownership to one contract, how to transfer it to others?

texts:
Here 2 contracts: contract A and contract B
If I (deployer/owner) transferred the ownership of contract A to contract B, is there any solutions that can transfer the ownership of contract A from contract B to others?
What I can come up with is I have to write some functions in contract B to transfer the ownership of contract A to others. Any other better ideas?
THank u very much!


texts: How one can verify a proxy contract, like OpenZeppelin Upgrade Proxy, on EtherScan?


texts: Ethers and Web3-React: Cannot estimate gas when trying to connect with contracts deployed on testnet and using Alchemy as node provider

texts:
I'm trying to connect with contracts deployed on the Rinkeby testnet using a node provider. When I was testing using hardhat as a local node, the contracts are called with no problem, but when I change to Rinkeby, I get an error cannot estimate gas; transaction may fail or may require manual gas limit (error={"code":-32000,"message":"execution reverted"}, method="call" for all the contract functions I'm trying to call. I've seen forums saying that it's usually due to the node being unable to estimate the gas limit and that I should manually set it.
By the way, Web3-React and Ethers.js don't contradict each other despite the naming. Web3-React is simply a React state machine that dynamically keeps track of my current wallet address, chain id, and browser provider Web3Provider, which I also use to create Contract instances using its signer. I use Ethers to create the Contract instances, format and parse data, and use its getDefaultProvider method to connect me to Alchemy. I made sure my rinkeby account had ether, and to change my local contract address variables to those of the ones deployed.
I'm also honestly a bit confused on what to do next, shouldn't the app suffice with just the Web3Provider instance from Web3-React? I've read on a lot of tutorials but nothing that explains something like this specifically.
Some example code below to show how the project is structured:
I've been keeping track of variables from Web3-React globally via React Context like this:
const value = useMemo<ContextWallet>(
    () => ({
      ...
      isActive: web3React.active,
      account: web3React.account ?? undefined,
      chainId: web3React.chainId,
      library: web3React.library,
      ...
      connect,
      disconnect,
      ...
    }),

For clarification, web3React.library essentially returns new Web3Provider(window.ethereum) where Web3Provider is imported from @ethersproject/providers. web3React.account returns from the ethereum request eth_accounts, web3React.chainId is from the request eth_chainId or net_version, and web3React.isActive lets us know whether the connection is working or not.
To create a contract instance via a signer I use the following functions:
export function getContract(address: string, ABI: any, library: Web3Provider, account?: string): Contract {
  if (!isAddress(address) || address === AddressZero) {
    throw Error(`Invalid 'address' parameter '${address}'.`)
  }

  const contract = new Contract(address, ABI, getProviderOrSigner(library, account) as any)
  return contract
}

export function getProviderOrSigner(library: Web3Provider, account?: string): Web3Provider | JsonRpcSigner {
  return account ? getSigner(library, account) : library
}

function getSigner(library: Web3Provider, account: string): JsonRpcSigner {
  return library.getSigner(account).connectUnchecked()
}

As for the provider to Alchemy, I did it like this but I don't really know what to do next:
getDefaultProvider(getNetworkName(Number(CHAIN_ID)), { alchemy: ALCHEMY_API_KEY })

The next snippet is an example of how I call a contract function:
const depositEth = async (amount: number, gas: any) => {
    setLoading(true)
    if (!farmContract || !vaultContract) return
    try {
      const tx = await farmContract.depositEth({
        value: parseEther(amount),
        gasPrice: gas,
      })
      await tx.wait()
      await farmContract.once('EthDeposited', (sender, amount, tx) => {

        // At this point, the transaction should have been mined already
        console.log('EthDeposited event detected: ', tx)
        wallet.reload()
      })
    } catch (err) {
      console.log('error depositEth ', err)
      wallet.reload()
    }
  }

Can someone offer some suggestions or advice on how to solve this step?
Thanks!


texts: Is it possible to figure out whether the network is mainnet or testnet (Ropsten) from web3.js? Or through MetaMask?


texts:
I could not find any library that, given an hex value, returns true if the given string is a valid ether private key.

Any hints?


texts: How to connect etherwallet to my private blockchain?

texts:
I am unable to make etherwallet v3.4.2 to connect to my private blockchain.

The way I run my private network: (please note that it works perfectly fine)

geth --port 3000 --networkid 23422 --identity node1 --verbosity 3 --nodiscover \
--nat none --datadir="/home/MyEthereumEbloc" --rpc --rpcaddr="localhost" --rpcport \
8545 --rpccorsdomain="*" --ipcapi "admin,eth,net,web3,debug" \
--rpcapi "admin,eth,net,web3,debug" --autodag=true

In order to use etherwallet in private chain setup, I completed following guide  and answer : As guided, I am able to get blank page for the http://< my_ip >:8000/api.mew and the index.html opens on http://< my_ip >:8000. Everything is in order and fine. But the moment I open the webpage I see following error on the output of node runLocalServer.js and this error message keep repeat itself.

node runLocalServer.js
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

In addition to that as an example, I create new account address on etherwallet. And inside geth I tried to send some ether to that address. Transaction successfully completed, but on the etherwallet, account balance of that account is still empty. Also I send a transaction inside etherwallet, which won't show up on my private blockchain.

I have been told that etherwallet can't find my eth node, hence there is disconnection between them. But I could not figure it how I could fix this problem.

Setup Custom Node:

On the website at http://< my_ip >:8000, Top Right Box => Add Custom Node:
Than I set Node Name: node1, URL: https://<my_ip> and port: 8545 as on the example window popped up.

After that on the top of the page I see the following error:

Please note that I tried < my_ip > as 127.0.0.1 and original ip address of my server but both showed that error. In order to connect to the local node, because of the --rpc flag I assume only localhost can connect into my node. So maybe I need to make modifications on Response.js file via web3 to connect my node?

Thank you for your valuable time and help. I am sorry if there is grammar errors.


texts:
My front-end displays the timestamps of various contract actions that have taken place.

However, the current block.timestamp it's using isn't very accurate, because the miner has some leeway in setting it.

Can a front-end get an accurate timestamp of a block that's already been mined? So instead of relying on a contract to out block.timestamp in an event, we can simply query some third party for getTimestampForBlock(blockNumber)?

Seems wasteful to output block.timestamp in an Event, when that data should be queried after the fact... Is there any other way to record / access timestamps for transactions?


texts: How to allow owner to select facilitators

texts:
I am very new to solidity and quite honestly I'm scratching my head a lot.

I am trying to create a contract where a company can facilitate donations. Anyone can apply for a donation, supplying their name, organization type and some general contact details. In order to receive, donations applicants need to be approved first. The owner can select people that are able to approve organizations

I have set up my modifiers and i want to write the first function of allowing the owner to select people to be facilitators that can approve applicants. How would I do this?

contract DonationContract
{
    address owner;

    struct Applicant
    {
        address Appl;
        string Name;
        string OrgType;
        string Number;
        string Email;
        uint256 Funds;
        bool approved;
    }

    mapping (address => Applicant) applicants;

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

     modifier Approved()
    {
        require(applicants[msg.sender].approved == true);
        _;
    }

    function approve(address Org) Owner public
    {
        applicants[Org].approved = true;
    }
}


texts:
I use ganache-cli --db to create a private test chain and save it on my computer,
and the result is below:

I use web3py w3.personal.newAccount('1') to add a new address, and I use print(len(w3.personal.listAccounts)) to show the amount of accounts, and the result is below

but when I shut down(ctrl +c) and turn on the  ganache-cli again, I find there is no account saved.


texts:
Sometimes we need to use string instead of byte32 only because of one byte (or one character) and this increases the gas and the cost of transaction.

For example, I want to store the assets state of a building in blockchain. We have several  specific actions for these assets such that we have to mention exactly the title of an action ex. Check operation of low water level float that is 41 bytes. So we cannot use byte32 to store this action. And we need string.

According to this article

  Logs were designed to be a form of storage that costs significantly less gas than contract storage. Logs basically cost 8 gas per byte, whereas contract storage costs 20,000 gas per 32 bytes.

However,I am not sure in case of using string in event, how much the cost will be decreased?

What is the reason that string is more expensive than other types ? Solidity or Ethereum ? It depends on consensus mechanism used in the blockchain ? And can it will resolved in future ?

Here is some part of my Solidity code (I tried to summarize the code to be more clear. However, if you need more, please let me know.)

struct StateStruct {
                    mapping(bytes32 => bytes32) subState;
                }

                struct AssetStruct {
                    StateStruct state;
                    address owner;
                    bool isAsset;
                    bytes32 review;
                    bytes32 action;
                    bytes32 player;
                    bytes32 actionState;
                    bytes32 assetSite;
                    bool isOwner;
                }

            mapping(uint256 => AssetStruct) assetStructs;
                uint256[] public assetList;

                uint256 public _public_id = 0;

       event LogNewAssetOneAction(uint256 indexed _id, bytes32 _action, bytes32 _player, bytes32 _actionState,  address _owner);

            function newAssetOneActionManualID(uint256 _id, bytes32 _action, bytes32 _player, bytes32 _actionState,  address _owner, bytes32 _assetSite) public returns(bool success) {
            require(!isAsset(_id));

            assetStructs[_id].owner = _owner;
            assetStructs[_id].isAsset = true;
            assetStructs[_id].assetSite = _assetSite;

            assetStructs[_id].action = _action;
            assetStructs[_id].player = _player;
            assetStructs[_id].actionState = _actionState;

            assetList.push(_id);

            emit LogNewAssetOneAction(uint256(_id), bytes32(_action), bytes32(_player), bytes32(_actionState), address(_owner));

            return true;
        }


texts: Is it possible to do a reverse crowd sale? e.g. send tokens to a smart contract to get ether back. Or would this require to load the contract with WETH or something in advance?


texts: How would Proof of Stake affect rigs running GPUs (480,580)

texts: I noticed through a few articles about how proof of stake is a likely progression for the ETH project.  I agree with the principles and the security benefits it gives, but how would it in real terms affect the physical process of mining with a GPU?


texts: Why am I seeing only one transaction per getting mined per contract per block?

texts:
I am creating large contracts A and T (not real names) that represent actual business needs and these contract have several setters (A.setXXX, A.setYYY, T.setZZZ ...) functions to initialize the storage of the contracts.

I am working on the pattern that 1) first I create the contract with the basing info and then the end user (java script) set the other info from outside with several transactions.

I then realise that each transaction on the same contract are mined one at at time. If I have in javascript

A.setXXX();
A.setYYY();

then it takes 2 blocks to have them both processed

However if I call

A.setXXX();
T.setZZZ();

Both transactions are included in the same block

So i conclude that the miner only take one transation for each object and discard the other transactions for later processing.

My questions are:

Is this rule normal?
What is the reasoning?
Is there a way around this?
Am I using an incorrect pattern for populating large contract?

Thanks for advises

Note that I selected this pattern because I could find solution to call a transaction with a large structure as parameters.


texts: How does the Open Zeppelin ERC721 preset work?

texts:
I'm using the ERC721 preset from Open Zeppelin. If I'm understanding the contract correctly, one of the main differences from the standard ERC721 is that the latter only has to be deployed once and anybody can call the mint function without any access control:
function _mint(address to, uint256 tokenId) internal virtual {
    require(to != address(0), "ERC721: mint to the zero address");
    require(!_exists(tokenId), "ERC721: token already minted");

    _beforeTokenTransfer(address(0), to, tokenId);

    _balances[to] += 1;
    _owners[tokenId] = to;

    emit Transfer(address(0), to, tokenId);
}

whereas the preset requires a new contract to be deployed each time a new token is minted. And only the deployer of the contract has the access to call the function:
function mint(address to) public virtual {
    require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");

    _mint(to, _tokenIdTracker.current());
    _tokenIdTracker.increment();
}

Is this correct? If so, does this mean all of the dependencies of the preset like following have to be deployed each time a new token is to be minted adding to the cost of the gas?
import "../ERC721.sol";
import "../extensions/ERC721Enumerable.sol";
import "../extensions/ERC721Burnable.sol";
import "../extensions/ERC721Pausable.sol";
import "../../../access/AccessControlEnumerable.sol";
import "../../../utils/Context.sol";
import "../../../utils/Counters.sol";

Not sure if I'm missing something, but if the main selling point of the preset is the token ID and URI autogeneration, this seems like a minor gain in exchange for an exorbitant cost of the gas in the deployment.


texts: What does `call.value` mean and how did it allow the attack to The DAO?

texts:
I'm trying to get some sense from the hysteria around the attack performed to The DAO smart contract.

I understand the high level explanations, but I'd like to grasp how this attack was performed.

I've read somewhere that this is related to the call.value() statement, but I don't understand why this is any different from regular CALLs.


texts: What is the default ordering of transactions during mining?

texts: I know that the yellow paper does not specify how transactions are to be ordered in a block and this is up to the miner to decide. But I am interested in how this is practically handled (I assume not calling some rand function to get ordering). This answer to a related question suggests that gas price plays a role. How does, e.g. geth order transactions during the mining process?


texts: can an ethereum contract control alternative assets like btc?

texts: can ethereum contracts control other assets, where the actual contract owns the btc and will only release it back to the address it was sent from (to avoid a DAO type hack) once a certain signal is recieved to release, and have it run autonomous?


texts: Why no dapps in the Google Play Store? Why Ethereum not accessible by default in smartphone?

texts:
Before I create a decentralized application, I want to know whether it already exists. I thought the first step would be to search the Google Play Store, but it appears dapps are not available on the Google Play Store, that users must install additional software and search within that software instead. Why are dapps not available in the Google Play Store? How is the Ethereum network not directly accessible to smartphone users like the Internet network?

Are these questions answered in State of the Dapps' recommended reading?


texts: send data & ether to other contract in the same method

texts:
I need to call a function from another contract
(the function take a parameter and need 1 Ether to execute) like this:

    pragma solidity ^0.4.4;
    contract ContractONE {
       uint public i;
       function register(uint _i) payable{
          if(msg.value > 1 ether){
             i = _i;
          } else {revert();}
        }
       ...
    }

............................................

pragma solidity ^0.4.4;
  import "./ContractONE.sol";
  Contract contractTwo {

     address addofContract1;
     uint i ;
     ....
     function changeNum(uint _i) payable{
         i = _i;
         ContractONE c = ContractONE(addofContract1);
         //// problem here:
         c.register(_i); //will revert, cause it does not send ether!!
        ////
      }
    }

the second Contract has already some Ether in it.

is there a method to do that? maybe like c.register(_i).transfer(amount)!
 or a trick with addofContract1.call(.....,.....)


texts: Provable API for calling ETH-USD price in a contract

texts:
This contract is hosted at https://github.com/provable-things/ethereum-examples/blob/master/solidity/truffle-examples/kraken-price-ticker/contracts/KrakenPriceTicker.sol

I have made the constructor payable and transferring ether while deploying, The original contract was calling update method recursively from __callback but I have removed it.

pragma solidity >= 0.5.0 < 0.6.0;

//import "github.com/provable-things/ethereum-api/provableAPI.sol";
import "https://github.com/provable-things/ethereum-api/provableAPI_0.5.sol";

contract KrakenPriceTicker is usingProvable {

    string public priceETHXBT;

    event LogNewProvableQuery(string description);
    event LogNewKrakenPriceTicker(string price);

    constructor()
        public
        payable
    {
        provable_setProof(proofType_Android | proofStorage_IPFS);
        update(); // Update price on contract creation...
    }

    function __callback(
        bytes32 _myid,
        string memory _result,
        bytes memory _proof
    )
        public
    {
        require(msg.sender == provable_cbAddress());
        // update(); // Recursively update the price stored in the contract...
        priceETHXBT = _result;
        emit LogNewKrakenPriceTicker(priceETHXBT);
    }

    function update()
        public
        payable
    {
        if (provable_getPrice("URL") > address(this).balance) {
            emit LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee!");
        } else {
            emit LogNewProvableQuery("Provable query was sent, standing by for the answer...");
            provable_query(60, "URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHXBT).result.XETHXXBT.c.0");
        }
    }
}

I cant even deploy this contract, Error I am getting is

VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.  Debug the transaction to get more information


texts:
I have setup a geth node on AWS for a DAPP I've created.
So there's a specific geth process running.

I've found that this shuts down every now and then.  Any recommendations on how I can monitor this process and restart it should it go down?


texts: Can Ethereum DApps work without downloading all blocks in the network?

texts:
I've just downloaded Mist (the Ethereum wallet) and am waiting for all blocks to download. I'm on the test network and its been 24 hours with only 50% of the blocks downloaded.

My question is, if one had to build a distributed app using Solidity and Ethereum would all users have to download all the blocks in the network? i.e. wait 48 hours before they could use the app.

I couldn't find anything on Google so this is obviously a really dumb question... but I had to ask anyway.


texts: How to connect a NodeJS App to locally running Ganache

texts:
Most of the tutorials I have found so far connect a FrontEnd App (say, React) through the web3.js that gets injected by Metamask.

I have been asked to produce an NodeJS App that connects to a locally running Ganache instance. Is that possible? If so, can someone point me to a tutorial for this.


texts:
I just opened up the Oraclize website and copied their 'Quick Start' ethereum contract and pasted it into Solidity online compiler to try it out (environment is Javascript VM). When I change the value from 0 to something like 10 or 20 and then hit create, I'm expecting the contract to call the constructor, which calls the updatePrice() function and then a query should be sent. What happens instead is that I get an error:

  Exception during execution. (invalid opcode). Please debug the transaction for more information.

Why am I getting an error if I just copied and pasted code in the documentation?


texts: Can I check whether any deployed contract has implemented some particular interface or not?

texts:
My concern is whether I can do interface detection with my own interface,,,
Like suppose, i have implemented some interface say loyalty interface in my one contract and I have deployed that contract ,, can i check in my another contract using the previous contract's contract address whether that has implemented loyalty interface interface or not ?


texts:
What options to use to start the server with four protocols [eth/62], [eth/63], [les/1], [les/2]?

Now my node is working on three protocols : [eth/63] [les/1], [les/2]
I use next options: geth --cache 1024 --lightserv 25 console

I think that because of this my light client does not synchronize with my server.

About my Server Node:
Geth/v1.8.0
Windows 10 amd64


texts: Can Ethereum execute a function automatically based on a state change?

texts:
I'm trying to make a smart contract and have a function executed on state change. In my example below, this function is finish. It must run automatically when the state changes to end. Is this possible with Solidity?

pragma solidity ^0.4.16;

contract SmartContract {
  address owner;
  string state;
  string status;
  function SmartContract() public {
    status = 'Pending';
    owner = msg.sender;
  }

  event update(string _msg, string _state);

  function getState() public constant returns(string) {
    return state;
  }

  function getStatus() public constant returns(string) {
    return status;
  }

  function setState(string _state) public returns(string) {
    state = _state;
    return state;
  }

  function finish() public {
    if (keccak256(state) == keccak256("end")) {
        status = 'Completed';
        update("Completed", state);
        selfdestruct(owner);
    }
  }

  function () public payable {

  }
}


texts: Pending transactions at the client machine, but minter is not minting a new block since there are no pending transactions

texts:
I am running Blockbench on Quorom Raft using smallbank workload: 4 minters and 4 clients. Following the logs, I found that sometimes 1 specific client (Client 4) has pending transactions but the minter stop minting as there is no transactions to mint. Do you have any idea what the issue could be.

Quorom start mining:

PRIVATE_CONFIG=ignore nohup ${QUORUM} --datadir $QUO_DATA --rpc --rpcaddr 0.0.0.0 --rpcport 8000 --port 9000 --raft --raftport 50400 --raftblocktime 70 --mine --rpcapi admin,db,eth,debug,miner,txpool,personal,web3,quorum,raft --unlock 0 --password <(echo -n "") > $QUO_DATA/../raft_quorum_log 2>&1 &

Genesis:

  "alloc": {
     "eb6902c98ed64b7b16f743a7c09b36b8fa1aff59": {
      "balance":"1000000000000000000000000000"
    },
    "981010def42136f95ad6f302052e660bac5f2b3f": {
      "balance": "1000000000000000000000000000"
    }
  },
   "coinbase": "0x0000000000000000000000000000000000000000",
  "config": {
    "homesteadBlock": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock":0,
    "chainId": 10,
    "eip150Block": 0,
    "eip155Block": 0,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip158Block": 0,
    "isQuorum": true
  },
  "difficulty": "0x0",
  "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x1FFFFFFFE0",
  "mixhash": "0x00000000000000000000000000000000000000647572616c65787365646c6578",
  "nonce": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp": "0x00"
}

Starting Client:

nohup ./driver -db ethereum -ops 10000 -threads $1 -txrate  $4 -st $5 -fp stat.txt -endpoint $ip:8000 > $LOG_DIR/host_$ip"_"$1"_"$6 2>&1 &

threads: 4
txrate: 500
st: ~ 600 seconds

Note that I always found this in the log files either there was pending transactions or not:
VM returned with error                   err="gas uint64 overflow"


texts:
I have started an rpc server as follows :

 geth --datadir ./chaindata --rpc --rpcapi="db,eth,net,web3,personal,web3"

It says  that an http endpoint is started . But i cant access this endpoint through metamask . Is there something Im missing . It is working fine with testrpc


texts: Upgrading the truffle Migrations contract

texts:
In the standard truffle migrations contract the purpose of the upgrade function is upgrade the Migrations contract itself by copying the last_completed_migration of the old Migrations contract to the new Migrations contract.

I'm wondering what would actually call this function? Would it need to be called explicitly from the migration .js script that deploys the new Migrations contract? Or does it get called automatically from the truffle migrate command when the new Migrations contract is deployed?

Also I wonder why the upgrade function doesn't call selfdestruct on the old contract after the Migrations contract is upgraded?  Or is this also a job for the .js migration script?

This is a follow up to Truffle Migrations contract constructor argument


texts:
Since the Geth issue it's been near impossible to keep up with the blockchain syncing, because it will often get stuck on one block forever.

I've been trying to copy these instructions from a similar question that got lots of upvotes:

If you are on a Mac, you would do this...

Right click on the ethereum-wallet.app and select 'show package contents'
Open 'contents', then 'frameworks', then 'node', then 'geth' and voila.
Then you should right click on geth and select 'show info'.
Copy the location marked 'Where:'.
Open Terminal and type 'cd `
Then type: ./geth --fast

However these instructions make no sense to me. The whole instruction says to copy a location and then proceeds to do nothing with that information.

What am I doing wrong? I tried the commands on the last two points in succession and nothing happened.


texts: The object could not be cloned. && DOMException: Failed to execute 'postMessage' on 'Window'

texts:
When I try to sign a message with this simple function const signatue = await window.web3.eth.sign(hash, userAddress) I get an error.

In firefox I get Unhandled promise rejection DOMException: "The object could not be cloned."

The actual data I put into this function for example are: hash 0x2339863461be3f2dbbc5f995c5bf6953ee73f6437f37b0b44de4e67088bcd4c2 account_address 0x627306090abab3a6e1400e9345bc60c78a8bef57

I am using "web3": "^1.0.0-beta.47" and Metamask 6.1.0.

In "1.0.0-beta.46" Iam getting error I have already mentioned there Cannot sign a message with web3js (invalid from address)

In beta "^1.0.0-beta.37" everything works fine.

Please help me :(

The same error in chrome

              if (!error) {
                resolve(response);
              }
   ...<omitted>... } could not be cloned.
    at i._write (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:114976)
    at b (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:133822)
    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:136934
    at i.g.write (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:136961)
    at e.exports.y (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:126211)
    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:37123
    at e.exports.s.emit (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:37193)
    at w (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:121050)
    at _ (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:120865)
    at e.exports.b.push (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/inpage.js:1:121676)```


texts: Best practices for a secure Ethereum private network?

texts:
What are the best practices for an Ethereum private network with n nodes (programmed with Geth), to be secure from possibles external attacks?

I mean, which config parameters are recommended during the initialization of the nodes, to achieve a better security? Should I put --nodiscover? Is it recommended to enable/disable rpc/ipc? Etc...


texts:
I have to ethereum geth node runing as testnet syncmode=full on aws  both running on same hardware and bandwidth why one is syncing very slow and other one is syncing fast?

and if I will stop the geth via ctrl+c and start again it stating sync faster.

What's the reason actually behind?


texts: AZTEC validateProof and validateProofByHash sender / signer addresses

texts:
The AZTEC Crypto Engine lets you validate proofs and cache them for future re-use, since they are fairly expensive (around 800,000 gas for a 4-note join-split proof before Istanbul, and now about 200,000 gas). This question refers to aztec.js 0.9.1.

The proofs contain a signer, the address of the owner of the notes to operate on, and a sender or validator, the address of the (possibly a contract) sender of the proofs to ACE.

When you validate the proofs and cache them, you provide one address, which is called the sender

https://github.com/AztecProtocol/AZTEC/blob/2e30619dd39182982a0d6cce57de2cd015c1e8d0/packages/protocol/contracts/ACE/ACE.sol#L179

This is a mutator method and I would expect an EVM revert if it fails.

When you want to read from the cache, you also provide an address called sender, which I expect to be the same as sender used in the call above to write to the cache, and the proofHash:

https://github.com/AztecProtocol/AZTEC/blob/2e30619dd39182982a0d6cce57de2cd015c1e8d0/packages/protocol/contracts/ACE/ACE.sol#L287

My question is: do the calls to either or both of ace.validateProof and ace.validateProofByHash have to come from the same address as the sender address parameter?

To test this, I first make a call from Javascript that relays a call to ace.validateProof via a contract called TradeValidator

      const sellerValidation = await result.minedTx(
        result.validator.validateAndGetFirstProofOutput,
        [result.seller.jsProofData, result.validator.address] )

The Solidity code of the method validateAndGetFirstProofOutput is

   function validateAndGetFirstProofOutput(
        bytes memory _proofData,
        address _proofSender
    ) public returns (bytes memory, bytes32) {
        bytes memory formattedProofOutput = ace.validateProof(JOIN_SPLIT_PROOF, _proofSender, _proofData).get(0);
        lastProofOutput = formattedProofOutput;
        lastProofHash = keccak256(formattedProofOutput);
        return (lastProofOutput, lastProofHash);
    }

I've verified that the proofHash is what I expect from Javascript, and then I also tried to verify that this proof is cached by calling from Javascript

      const validateResult2 = await result.ace.validateProofByHash(
        JOIN_SPLIT_PROOF, result.seller.jsProofHash, result.validator.address,
      )
      assert( Boolean(validateResult2['0']),
        'seller proof hash is not associated with transferer/sender, when sent from Javascript user'
      )

My expectation is that ace.validateProofByHash would succeed if proofHash matches JOIN_SPLIT_PROOF type and sender address, when called from anywhere, whether it's a Solidity contract, a Node command-line user, or webpacked JS code in a browser. However, this second call is currently failing.

Two ways I can test this:

Does ace.validateProof revert if the sender parameter is incorrect, or if it comes from a different sender?
Can I make a Solidity method in the validator contract that also calls ace.validateProofByHash, but coming from the same sender address as the parameter?


texts: How do I call my smart contract functions through web3 js?

texts:
So I am very new to Blockchain development so sorry in advance!

I have deployed a very basic Smart Contract to the Ropsten testnet. I am developing a front-end and from here, I want to withdraw ether/wei from the contract address(using a withdraw method), to the account calling the function(injected Metamask). It works perfect when I go onto etherscan to my contract and use the withdraw function there directly. I just don't know how to call the withdraw function through web3 js properly. I keep getting the following error message...

https://imgur.com/a/RSVrJIF

Can someone help point me in the right direction? Thanks!

pragma solidity ^0.5.0;

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

    function deposit() public payable{
        balances[msg.sender]+=msg.value;
    }
    function withdraw(uint amount) public{
        if(balances[msg.sender]>=amount){
            balances[msg.sender]-=amount;
            msg.sender.transfer(amount);
        }
    }
}

Web3 = require('web3');

if (typeof web3 != 'undefined')
{
    web3 = new Web3(web3.currentProvider);
    console.log("existing web3: provider " + typeof web3);
    console.log(web3.currentProvider);
}
else{
    //To Do..
    web3 = new Web3(new
    Web3.providers.HttpProvider("https://ropsten.infura.io/"));
    console.log("new provider " + web3);
}

console.log(web3.isConnected());
console.log(web3.eth.accounts[0]);

abi = JSON.parse('[{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getMyBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"}]');

var bankContract = web3.eth.contract(abi);
contractInstance = bankContract.at('myaddressishere');
console.log (contractInstance);

function withdraw() {
    contractInstance.withdraw(300000000000000000, { from: web3.eth.accounts[0]})
}


texts: Unexpected behavior with storage keyword?

texts:
Could someone explain to me what exactly happens when I declare a storage pointer?
This example highlights the issue that I have encountered:
contract minimum {

  uint256[] a = [1,2,3,4];

  function createOffersAsList() public returns (uint256[]) {

    uint256[] storage b;
    uint256 i = 0;

    Logger("Before loop", b);
    // What I expected it to return: '"Before loop", ""'
    // What it actually returns: '"Before loop", "1, 2, 3, 4"'

    while (i<4) {
        b.push(a[i]);
        i++;
    }
    Logger("After loop", b);
    return b;
    // What I expected it to return: '"After loop", "1, 2, 3, 4"'
    // What it actually returns: '"After loop", "1, 2, 3, 4, 1, 2, 3, 4"'
  }

  event Logger(string s, uint256[] u);
}

It seems to me, that when I declare b that it is automatically assigned to the storage of a. Why is that? I would have thought that it is just assigned to some free space?
And if I need to use a local dynamically sized array, how would this look like?
Thanks in advance and best regards,
carbee


texts:
I stupidly invested in weeCoin (WMA) last year and was advised that I need to buy etherium to use as "gas"
I still have both the WMA tokens and the Etherium I sent showing in the weeWallet but I cannot figure out for the life of me how to transfer the Etherium out of the weeWallet into another wallet.
The weeWallet does not appear to have a section where I can input the address of the wallet I want to transfer to.
Any help would be greatly appreciated.


texts: I was viewing the verified ethereum smart contracts on Etherscan and noticed that a lot of the smart contracts had same names and versions but different contract addresses with varying transaction counts. What does this mean? Does this mean that the contract was deployed several times and the different transaction counts accounts for the transaction made with that specific deployment?


texts: Creating keyfile and address from private key

texts:
What is the logic behind Ethereum creating key file and account account address from the private key. I am able to import a ECDSA private key to create an account. Same account address is generated for one specific private key.

I am looking to generate the public ethereum address and the key file outside of ethereum.


texts: Deinstall geth builded from source completely together with the blockchain and every piece of data

texts:
I use Lubuntu 17.10.

I have followed the steps in the tutorial to build geth from source. (here)

I have abandoned the idea of mining ether with my crappy hardware.

How can I deinstall the big fat blockchain and every single piece of data that goes with the source install, that eats up my limited space on my precious hard drive?


texts:
I use Truffle and Ganache and I want to test some contracts that use the ERC820 Registry. I'm new to Truffle (and JavaScript in general) and I'm struggling to follow the instructions described in EIP-820 to get the registry deployed.

I have a 1_initial_migration.js and a 2_deploy_contracts.js file in my migrations folder. That look like:

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

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

and

var Registry = artifacts.require("./ERC820Registry.sol");
var Token = artifacts.require("./Token.sol");

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

This obviously deploys the ERC820 to another address than 0x820b586C8C28125366C998641B09DCbE7d4cBF06.

How would I have to change my deployment file for it to be able to deploy the ERC820 Registry to its correct address?


texts: Parity Ethereum Public Node Operation not working

texts:
Can't get parity --public-node to operate properly over LAN.

I am able to connect to the UI from another browser except it endlessly asks for a new signer token and does not let me get past.

Is this an issue that has been resolved?  Or is there something I'm overlooking?


texts:
When I run a (custom dev and test network) parity node on my mac from the command line, it starts up and displays my enode as enode://c2f9c6a...85b1d@192.168.0.241:99999 where the IP address is my router assigned ip 192.168.0.241.

This means that although I can connect to the bootnode peers which have been set up (I have a remote one on a VPS), and the bootnode peers record that my node is connected, no other remote nodes are able to connect to me using the enode URL that my node has.

For example, when other remote colleagues start their nodes, they also can connect to the bootnode, but are not able to discover my node nor am I able to discover them as they are also behind routers and they have the same issue. Therefore this is not a peer-to-peer network, it is centralised around the bootnode as node discovery appears not to be working.

So my question is actually two related questions, "How to get my enode URL to use/show external IP, and how can I be discoverable?", and if that is not possible then "how is peer-to-peer achieved on the public ethereum chain and can I apply it to my custom chain?".


texts: One time catastrophic solidity bug suddenly vanished

texts:
I'm writing a Blackjack game in solidity. In the following function, the player ended up winning one time with a hand strength of 30 after doubling down even though they should have busted. Unfortunately I was just testing locally on testrpc and thus have no record of this.

    function _DoubleDown() public payable requireHandActive(true) requirePlayerActive(true) {
    require(msg.value == betAmount[msg.sender]);
    require(playerCards[msg.sender].length == 2);
    require(isSplit[msg.sender] == false);
    uint newCard = randgen();
    playerCards[msg.sender].push(newCard);
    betAmount[msg.sender] += msg.value;
    uint handPower1 = card2PowerConverter(playerCards[msg.sender]);
    if (handPower1 > 21) { //player busted
                processHandEnd(false);
            }
    else {
        isPlayerActive[msg.sender] = false;
        checkGameState();
        }
}

function processHandEnd(bool _win) internal { //hand is over and win is either true or false, now process it
    if (_win == false) {
        }
    else if (_win == true) {
        uint winAmount = betAmount[msg.sender] * 2;
        msg.sender.transfer(winAmount);
        payoutAmount[msg.sender]=winAmount;
    }
    gamestatus[msg.sender] = 5;
    isActive[msg.sender] = false;
    broadcastHand();
}

Until now however I've been unable to replicate the bug. Does anyone know what might have been wrong? I cannot release this app knowing this bug was present and observed, even though I cannot replicate it.

Full source code is here: https://ropsten.etherscan.io/address/0xcd9eba98aa4854246467248f8f814f3bc01e4c21#code


texts: Need for Merkle path of a transaction to verify its membership in a particular block

texts:
I have read about the Merkle path of a transaction (path in Block B's Merkle tree from the txn T to the Merkle root) being needed to verify that txn T is included in block B, and I understand that.

My question is (perhaps a naive one):

Is it not enough to check the block number in the object returned by web3.eth.getTransaction(txnHash [, callback]) to verify that a txn is included in a particular block?


texts: Not able to connect metamask account with remix

texts:
Error: -
Cannot get account list: Error: The method personal_listAccounts does not exist/is not available.
Pop containing above message appears again and again.
Privacy Mode in metamask is disabled.


texts: Remix shows values from getters only declaring "constant"

texts:
pragma solidity ^0.4.0;

contract MyFirstContract {
    uint private age;

    function setAge(uint newAge) {
        age = newAge;
    }

    function getAge() returns (uint) {
        return age;
    }
}

When I create the contract in remix and then set for example the number 3 to the variable age, then when I call getAge() it shows nothing. But if I add "constant" like:

function getAge() constant returns (uint) {
    return age;
}

then it works. I saw some video that the same code was working without declaring "constant", so I dont really undestand why it is not working for me.


texts: Casper, Serenity, Constantinople, Ethereum 2.0

texts:
I hear alot about the terms:

Casper
Serenity
Constantinople
Ethereum 2.0

At some point I thought that all are the same, the next release of Ethereum, but apparently there’s an upcoming fixes patches before the proof of stake release.

Can someone please explain what does each term stands for?

And which if them may lead to hard-forking the system?


texts: can a developer delete balances trough a contract update using openzeppelin

texts:
I am new to this and just have some arbitrary questions regarding upgradeable smart contracts.
If a Developer would update his contract, could he modify all mappings / variables entirely? Wipe balances, reset values?


texts: Problem creating my own wallet with multiple accounts

texts:
I have a local blockchain where I have deployed a contract. I want to interact with it sending multiple responses at the same time. For this propose, I cannot use Metamask to confirm each transaction. I need to create my own wallet and send the tx signed. I have my own wallet with an account using ethers.js:

var password = "xxxx";
var json = JSON.stringify(data); //data = content of the keystore file of an account
ethers.Wallet.fromEncryptedWallet(json, password).then(function(wallet) {
    App.Wallet = wallet;
    App.Wallet.provider = new ethers.providers.JsonRpcProvider(`http://localhost:3002`, { chainId: 15 });
});

var account = App.Wallet.address;
let rawtx = {from: App.Wallet.address, to: App.contracts.MyContract.address, gasPrice: 18000000000, gasLimit: 20000000000, data: getdata }

var signedTransaction = App.Wallet.sign(rawtx);
var transaction = ethers.Wallet.parseTransaction(signedTransaction);
var sendTransactionPromise = App.Wallet.sendTransaction(transaction);
sendTransactionPromise.then(function(transactionHash) { console.log(transactionHash); });

It works, but just with one account. Is there any way to create a wallet with multiple accounts? or how could I send multiple transactions from different accounts with my own wallet?

I am trying just with a for, but it is a bit dirty and my browser is not responding correctly, each time that i call ethers.Wallet.fromEncryptedWallet for each account the program is broked. I am also trying with web3.eth.accounts.wallet but I always get the error "undefined" and I am using web3 1.0.


texts: Two ways of assigning a pointer. Is there a difference?

texts:
Here's one way to assign a pointer to variable z:

function f(uint8[] memoryArray){
    var z = memoryArray;
}

and here's another

function f(uint8[] memoryArray){
    uint8[] memory z = memoryArray;
}

I've tried to pass these variables to other functions and I didn't notice any difference in how they behave. Is there any difference between the two?


texts: What is a Erc20 (UBT) token I received in my wallet according to EtherScan?

texts:
I look in my EtherScan and it says that 5 days ago and 10 in value I received a token called Erc20(UBT) and I click on it, it's a Universal Bonus Token that came from an address = 0x00000000000... When I click on my token balances there's the 10 UBT and above it is the ERC20 contract address.

What is this?


texts: How to calculate the difference between what was transferred and what was sent / received?

texts:
Hi I'm trying to get some clarity as to what the difference is between what was

Transferred
Sent
Received

Shouldn't what's transferred and received be the same? Transferred means the amount that was sent after costs, no?

Also, what how would I calculate the difference between what was Sent and what was Transferred? Is that just Sent amount - (gas used * gas price)?

Here is a concrete example: https://etherscan.io/tx/0xbcdd4b6f28b10a61d5279bd017f555a4edcb233374fbe9e67df1ba3e38ff749a

Would this be correct?:

Transferred: 6.0099999 ETH
Sent: 6.0099999 ETH + (21000 gwei * 0.000000009 Ether)
Received: 6.0099999 ETH


texts: Syntax Error when trying to run ganache-cli with node v6.14.3

texts:
My environment

ganache-cli 6.4.4
node v6.14.3
Mac OS Terminal

I run the following commands to install ganache-cli

Aseems-MacBook-Pro:bdnd aseem$ nvm use v8.11.3
Aseems-MacBook-Pro:bdnd aseem$ npm install -g ganache-cli
/Users/aseem/.nvm/versions/node/v6.14.3/bin/ganache-cli -> /Users/aseem/.nvm/versions/node/v6.14.3/lib/node_modules/ganache-cli/cli.js
/Users/aseem/.nvm/versions/node/v6.14.3/lib
└── ganache-cli@6.4.4

My node version is

node -v
v6.14.3

But when I try to run ganache cli I get this

Aseems-MacBook-Pro:bdnd aseem$ ganache-cli
/Users/aseem/.nvm/versions/node/v6.14.3/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:47
!function(){var r,a={};function i(){}function o(e){return e}function c(e){return!!e}function f(e){return!e}var s="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||this;function d(e){return function(){if(null===e)throw new Error("Callback was already called.");e.apply(this,arguments),e=null}}function u(e){return function(){null!==e&&(e.apply(this,arguments),e=null)}}null!=s&&(r=s.async),a.noConflict=function(){return s.async=r,a};var l=Object.prototype.toString,b=Array.isArray||function(e){return"[object Array]"===l.call(e)};function p(e){return b(e)||"number"==typeof e.length&&e.length>=0&&e.length%1==0}function h(e,t){for(var r=-1,n=e.length;++r<n;)t(e[r],r,e)}function m(e,t){for(var r=-1,n=e.length,a=Array(n);++r<n;)a[r]=t(e[r],r,e);return a}function x(e){return m(Array(e),function(e,t){return t})}function v(e,t){for(var r=0;r<e.length;r++)if(e[r]===t

SyntaxError: missing ) after argument list
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/aseem/.nvm/versions/node/v6.14.3/lib/node_modules/ganache-cli/cli.js:12:13)

According to the github page I should Make sure you have Node.js (>= v6.11.5) installed. which I did. The FAQ does not contain anything about syntax errors. Is the documentation incorrect or am I missing something else?


texts: Is Atomic swapping between ETH and ETC possible?

texts: Wondering if cross chain atomic swapping between ETH and ETC without using poloniex, then the world can be merged in more cool way.


texts: Is it possible to use geth attach with a different keystore?

texts:
I have set up geth to run as a systemd service (in Ubuntu 18.04 LTS) as system user ethereum. The datadir is set to /blockchain/ethereum. After fiddling with permissions and groups, I managed to add my standard user account to the same group as my geth user, and I can use geth --datadir /blockchain/ethereum attach from a terminal to access the geth console.

My problem is that I have my keystore in my home directory, and when I try geth --datadir /blockchain/ethereum --keystore ~/.keystore attach and I check the personal object, I do not see my account listed.

So my question is, is it possible to connect to a running geth from a different user if I specify my own keystore?


texts: Why doesn't bytecode match the opcodes on Etherscan?

texts:
I'm just going through the first few opcodes on this contract: https://etherscan.io/address/0xab7c74abc0c4d48d1bdad5dcb26153fc8780f83e#code.

Which are (according to the opcodes view):

PUSH1 0x60
PUSH1 0x40
MSTORE
CALLDATASIZE
ISZERO
PUSH2 0x00f8

Based on What OPCODES are available for the Ethereum EVM?, I would expect the bytecode to be 0x6060604052156100f8....

But the bytecode is: 0x60606040526002610108..., which I'm reading as

0x60 0x60      ;; PUSH1 0x60
0x60 0x40      ;; PUSH1 0x40
0x52           ;; MSTORE
0x60 0x02      ;; PUSH1 0x02???
0x61 0x01 x08  ;; PUSH2 0x01 0x08???

What am I doing wrong?


texts: Is there any limitation for the number of (sub) Wallet?

texts:
Is there a limitation for the number of wallet generated from Etherbase?

Thank you in advance for cooperation!


texts: how do i call a constructor from another constructor?

texts:
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {

    constructor(uint supply) public {
        // how do I call the constructor of ERC20 ?
    }

}

how do I call the constructor of ERC20 ? like for example super("arg1", "arg2") but this doesn't work.
I know that it's possible like this:
constructor(uint supply) public ERC20("arg1", "arg2") {

}

But still want to call it from the actual constructor.


texts:
Given two structures,
struct travel {
    string name;
    uint USN;
}
struct class {
    uint classID;
    string ProfessorName;
    student[] students;
}
mapping(uint => class) selectedClass;

A student can be entered only once. So while adding a new student to a class, I want to have a require statement which ensures that the USN is not present in class.
require(USN != selectedClass[ID].students[1])

I'm getting an error saying "Operator != not compatible with types uint256 and struct class.student storage ref".
How to correct this?


texts: Does ganache only store the most recent transaction's events?

texts: I can log them to the console in each transaction with subscribe, but the ganache UI only ever shows the latest one, as does web3.eth.getPastLogs.


texts: ENS Error: 'It seems this transaction will fail' when executing ethRegistrar.unsealBid() from Mist

texts:
When I want to execute the follwing transaction in Mist UI:

ethRegistrar.unsealBid(web3.sha3('name'), web3.toWei(1, 'ether'), web3.sha3('secret'), {from: web3.eth.accounts[0], gas: 500000});

I get:

What does that mean? How can I get this transaction executed that it won't fail? I already tried to increase the gas provided, but this doesn't change anything.


texts:
I'm trying to get solidity installed so that I can write contracts in Atom. I got this Atom package: https://atom.io/packages/atom-ethereum-interface

In it, it says to run geth --rpc --rpcapi="db,eth,net,web3,personal" --rpcport "8545" --rpcaddr "127.0.0.1" --rpccorsdomain "localhost" console and then eth.getCompilers() to make sure solidity is installed. I don't get any results, so I went to try to install solidity.

I found this article: http://solidity.readthedocs.io/en/latest/installing-solidity.html followed all of the steps in it, then ran the two commands to start geth and check for compilers, still nothing.

So I found this article: http://dipl.me:3000/greeter which says to run:

brew update
brew install cpp-ethereum
brew linkapps cpp-ethereum
which solc

Take note of the path given by the last line, you'll need it soon.

Again, I get no errors, but do not get any results in the prompt when I type which solc.

So I ran the geth command again and checked for compilers, still nothing. What am I doing wrong and how can I get this thing running on my mac?


texts: trouble matching gas used in transaction with difference in account balance

texts:
I've fired up my testrpc and deployed a simple HelloWorld contract using truffle. I send a simple transaction to my contract and I log my account balance before and after the transaction. Unfortunately, this does not add up to the gasUsed parameter I see in the transaction.

contract HelloWorld {

    uint public x;

    function HelloWorld() {
        x = 5;
    }

    function set_x(uint _x) returns(uint x) {
        x = _x;
        return x;
    }

}

And my javascript

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

module.exports = function(callback) {}

from_wei = web3._extend.utils.fromWei

var account1 = web3.eth.accounts[0];
var start_balance = web3.eth.getBalance(account1).toNumber();

HelloWorld.deployed().then(function(instance) {

    return instance.set_x(500)

}).then(function(tx) {

    console.log(tx)
    var new_balance = web3.eth.getBalance(account1).toNumber();

    console.log(start_balance + " initial balance");
    console.log(new_balance + " balance after transaction");
    console.log((start_balance - new_balance) + " difference");
    console.log(from_wei(start_balance - new_balance) + " difference (from_wei) ?");
    console.log(web3.eth.gasPrice.toNumber() + " gas price")

})

Outputs something like this:

{ tx: '0x1a2876b330618c75c7e264becbee75c491b47b5a17a0f9f9fe7fb124f0e93113',
  receipt:
   { transactionHash: '0x1a2876b330618c75c7e264becbee75c491b47b5a17a0f9f9fe7fb124f0e93113',
     transactionIndex: 0,
     blockHash: '0xf30134cac3be167d6053a21953b87010ce7145ccb36775e76d38458dddfa81b9',
     blockNumber: 16,
     gasUsed: 21736,
     cumulativeGasUsed: 21736,
     contractAddress: null,
     logs: [] },
  logs: [] }
99939363900000000000 initial balance
99937190300000000000 balance after transaction
2173600000000000 difference
0.0021736 difference (from_wei) ?
20000000000 gas price

It looks like the difference in my account balance IS the same as the gas used, just a different magnitude. So I'm confused? Are these numbers expressed in wei? I thought I needed to multiply by the gas price to see how much the transaction would affect my account balance...? How can I get GasUsed to equal the difference in my account balance?


texts: Check if user exists using mapping in solidity

texts:
I use solidity to store users information so before that i want to check if the user id already exist or no, Can any one help me with this code ?

i see some solution using array or require all parameters of structure and i don't prefer that, can i do this without these choices?

this function to store user information, if any one have a better code for that, i will appreciate it.

contract Contract {

    struct User{
    string fname;
    string Email;
    uint256 age;
    }

    mapping(uint => User)public users;

 function addDoctor(uint _id, string memory fname, string memory Email,
    uint256 age) public {

         users[_id] = User(fname,email,age);

     }
 }

thanks in advanced.


texts:
Does encodeABI() just do a decimal to hex encoding or is something more going on under the hood?

http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-encodeabi


texts: Can CREATE2 with the same salt override existing contract?

texts:
Deployed: https://rinkeby.etherscan.io/address/0x121e370ae349425d0d744f6db43c2f43e777f972#code
pragma solidity 0.8.3;

contract Test {
    uint256 public a;
    constructor (uint256 _a) public {
        a = _a;
    }
}

contract DeployTest {
    function deploy(bytes32 _salt, uint256 param) public {
        new Test{salt: _salt}(param);
    }
}

Transaction 1

Salt: 0x7465737400000000000000000000000000000000000000000000000000000000
Param: 1
TX: https://rinkeby.etherscan.io/tx/0x7a7a6db558dd049f2318b72719ec8f9c9ad918ef153b18af5dcfc7547301e5c5#internal
Deployed: https://rinkeby.etherscan.io/address/0x8a3c2609403d812de94179a7fffe182ea5efe97d#readContract

Transaction 2

Salt: 0x7465737400000000000000000000000000000000000000000000000000000000 (same)
Param: 2
TX: https://rinkeby.etherscan.io/tx/0x951ad8b244b2d02ff6ff79125547dabafa0f6a97a1019f7d36765f1d17ad9ace#internal
Deployed: https://rinkeby.etherscan.io/address/0xe1127decf6f9ad9b414540238490bc53badb0f00#readContract

I was expecting that the new deployment will override the old one?

I was looking at this article: https://hackernoon.com/using-ethereums-create2-nw2137q7

In Solidity assembly, create2() takes 4 parameters:
1: The amount of wei to send to the new contract as msg.value. This is 0 for this example.
2–3: The location of the bytecode in memory
4: The salt — that we will calculate in step 3. We leave this as a parameter so it can we provided after we have calculated it.

I'm not using assembly. I'm using Solidity code and constructor parameters.
I will do some more experiments but maybe you'll know - can I override the existing contract if I use the same salt but different constructor parameters?


texts: Identical contract functions in interface with different inputs

texts:
In the ERC721 interface, you have two functions with the same name:

   function transferFrom(address _from, address _to, uint256 _tokenId) public;
  function transferFrom(address _from, address _to, uint256 _tokenId, bytes data) public;

Just wondering what the point of this is and why you wouldn't just want to have two different functions if the end goal is different


texts: How to get a transaction fee in a Truffle test

texts:
I would like to test a Solidity function that looks like this and check if a correct amount of ether was sent to a sender:

function withdraw() public {
    uint contributed = amounts[msg.sender];
    amounts[msg.sender] = 0;

    msg.sender.send(amounts)
}

To implement a test that checks if a particular amount of ether was sent I need to get a subtract balances of an account after a transaction and before a transaction. But to have an accurate check I need to take a transaction fee into account.

Is it possible to get this in a Truffle test?


texts:
ALL
I WANT learn about smart contract trading.
I see on etherscan many bot making big money daily with smart contract.
E.g
I see bot are work single transaction swap weth to token to Eth
In than bot input 1 eth and out like 1 to 1.15 eth so in single transaction bot make profit 0.10 eth.
So I want find how work that
I am not coder if anyone having information please share in simple form.
Simple web3 connection and interact with smart contract.
See e.g.
https://etherscan.io/tx/0x183fd2d3b5ac4eefa562978ec42f9b7e851da38b513ca132489710b580620a24
https://etherscan.io/tx/0xb318e7c7a698562a960c15a489e9cf5d58eb57999fe48c6b2c77a437df449064


texts: Send endorsement message after finding new block Go Ethereum

texts:
When miner successfully found a new block's nonce, it then seal this block and broadcast/announce to peers in network. I want to add endorsement feature after miner found a nonce. This requires sending a message to all peers in the network. Trusted peers receive a message, then reply back to miner. Then, miner continue on committing, and broadcasting.
go-ethereum/consensus/ethash.go:

default:
        // We don't have to update hash rate on every nonce, so update after after 2^X nonces
        attempts++
        if (attempts % (1 << 15)) == 0 {
            ethash.hashrate.Mark(attempts)
            attempts = 0
        }
        // Compute the PoW value of this nonce
        digest, result := hashimotoFull(dataset.dataset, hash, nonce)
        if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
            // Correct nonce found, create a new header with it
            logger.Trace("Nonce was found at this time", "attempts", nonce-seed, "nonce", nonce)
            time.Sleep(3 * time.Second)

            header = types.CopyHeader(header)
            header.Nonce = types.EncodeNonce(nonce)
            header.MixDigest = common.BytesToHash(digest)

            ethash.passEndorse = false
            if (ethash.passEndorse){
                select {
                case found <- block.WithSeal(header) :
                    logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
                case <-abort:
                    logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
                }
                nonce++
            }else {
                logger.Trace("Nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
                logger.Trace("Wait 15s before starting new search")
             // calling function from go-ethereum/eth/tracers/handler.go
             // to send message to peers
             // handler.go takes care of broadcasting and announcing block
             // to peers
                eth.sendEndorseMessage("foo")
            }
            break search

However, adding import "github.com/ethereum/go-ethereum/eth" will give error "import cycle not allowed". Is there anyway to avoid import cycle? Or Should I create the function somewhere else and how to invoke it?


texts:
Apart from the public modifier Ethereum introduces the external one. Both may be called outside of the contract and inside (the later one by this.f() pattern). Moreover, according to the docs:

  External functions are sometimes more efficient when they receive
  large arrays of data.

but there is no further information what does actually sometimes mean and if this efficiency gain is held also for internal calls.

What are the best practices of using external vs public keyword? Are there any patterns or recommendations?


texts: Funds sent to a contract does not show up in the contract

texts:
I have this simple contract which has a payable method.

contract Betting is usingOraclize {
  function Betting() {
    //...
  }
  function sendEther() payable returns (uint) {
    return msg.value;
  }

The expected behavior is to accept ether and store it in the contract address.
Everything works fine including the transaction except that the balance doesn't show up. It remains zero. Here is the etherscan details of the contract.

The last 2 transactions were made using the sendEther method invoked used web3.js. Still the balance of the contract is zero.


texts: how to send tokens back from escrow smartcontract to wallet

texts:
i am trying to send tokens out from escrow smartcontract to seller's address and for tokens i am using different ERC2O standard smart contract. so i can send like buyer can send from ERC20 smartcontract to escrow. but how can i send those token from escrow smartcontract to seller's wallet

suppose buyer send tokens to escrow and after condition escrow send to seller then how to code that same transfer method in solidity and i am using ERC20 standard.


texts: In a HTML user interface how can we alert user when it inserts incorrect password/address?

texts:
I'm trying to design a user interface for private blockchain using Ethereum to test my contracts. So, users with different password and account address login.

I'm aware of this question, but it was posted a long time ago.

I want a way to alert a user when it put in incorrect password/account_address to unlock its account. But the problem is that,

web3.personal.unlockAccount(account,password)

doesn't return false, when it cannot unlock.

Question: How can I alert a user when it inserts wrong password or address?

In my HTML/.js file I have a login like this:

var password="";
var account="";
// user inserts its password and account_address using "onclick"
// then logIn() is called

function logIn(){

 var pass= document.getElementById("pass").value;
 var addrx =document.getElementById("addrx").value;
 //var myaddress = document.getElementById("myaddress").value;
 password=pass;
 account= addrx;
 if (!web3.personal.unlockAccount(account,password)) // here is where I want to detect incorrect inputs.
 alert("Password/address is incorrect");
}


texts: slow start of block synchronization in geth

texts:
What can I improve or debug to find causes of a delayed start of the block synchronization in geth?

I am running the latest geth (1.4.5-stable-a269a713) on Ubuntu 15.10, I noticed this behavior already on 1.4.4. It takes ~10min to get the first batch of blocks.

The latest output before it stalls for quite a while is > I0524 22:54:51.049035 eth/downloader/downloader.go:299] Block synchronisation started

Then the block synchronization slowly picks up, am I not getting all blocks from the bootstrap nodes and have to wait for more connections first?

I0524 22:54:51.049035 eth/downloader/downloader.go:299] Block synchronisation started
I0524 23:06:25.499404 core/blockchain.go:959] imported 3 block(s) (0 queued 0 ignored) including 5 txs in 2.434135699s. #1569355 [53a9c813 / d03631ff]
I0524 23:06:59.999931 core/blockchain.go:959] imported 37 block(s) (0 queued 0 ignored) including 182 txs in 31.936571292s. #1569392 [e45b1b93 / 37fc5741]
I0524 23:09:32.401927 core/blockchain.go:959] imported 256 block(s) (0 queued 0 ignored) including 1642 txs in 2m32.37937655s. #1569648 [44757652 / f611a137]
I0524 23:11:39.648649 core/blockchain.go:959] imported 256 block(s) (0 queued 0 ignored) including 1518 txs in 2m7.245587819s. #1569904 [842ff283 / 525a3769]
I0524 23:13:19.716431 core/blockchain.go:959] imported 256 block(s) (0 queued 0 ignored) including 1151 txs in 1m40.066272988s. #1570160 [28f1684e / 50b11832]


texts: How to integrate ERC 721 and 20 to create semi-fungible tokens?

texts:
ERC 721 defines non-fungible tokens where each token is unique. But if one needs to create a token where there is a limited supply of various types, is there a an effective way to accomplish this by mixing both standards without essentially just creating multiple ERC 20 with limited balances?

The goal is to have provable creation and burn of a limited supply of a multitude of related tokens. Some of these would have a total balance of 1 and essentially be standard ERC 721, but others would have a larger supply.


texts:
I've wrangled an old altcoin mining machine into an ethereum mining rig, it has two Radeon 280X cards in it.

I'm running geth, with two instances of ethminer, one per card.  However the output of ethminer is nothing like what I'm used to with the bitcoin equivalent miners.  It is very minimal.... it just continually prints:

i  <timestamp>|gpuminer0  WorkLoop 1 #1250db29... #1250db29...

over and over.

I've seen posts saying you can benchmark your cards with ethminer -M -G but that just crashes my rig.

Is there any way to get some kind of additional output that could show hashrate?


texts: Making a data Registry - does reading from other contract view function cost gas?

texts:
As known, reading view functions is free, but is it also free if I use it between two contract?
Let's say I have a contract Registry which has mapping that stores string => uint, nextly I pay some wei for a transaction "setValue" to set "test" => 5.

Now I make a new contract, load Registry and call view function "getValue" with argument "test". Will it cost an extra wei, more than using for example enum which will return me 5? Using global registry contract can be extremely handy, especially with web3js, but I wonder if this convenience costs extra gas.


texts: sendRawTransaction results in queued TXs

texts:
I attempted to send raw TXs via eth.sendRawTransaction API but get stuck. I'm using EthereumJS to generate and sign TXs, and indeed, I can submit TXs through eth.sendRawTransactin, but the TXs always result in queued (non-processable, per geth doc).

I called eth.sendRawTransactin from a geth console, and it returns a hash as usual. I can get transaction details by that hash:

> eth.getTransaction(hash)
{
  blockHash: null,
  blockNumber: null,
  from: "0x89b44e4d3c81ede05d0f5de8d1a68f754d73d997",
  gas: 90000,
  gasPrice: 50000000000,
  hash: "0x69b4a0768e72c3a679a1ae6fb490a831509c3c0a04674b646362d0a3d74689a4",
  input: "0x",
  nonce: 10,
  to: "0xb7e13de69228c37cdff506ea474f31343af33c05",
  transactionIndex: null,
  value: 2000000
}

But the TXs are queued forever:

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

Also sending address is rich enough to pay off the gas:

> eth.getBalance("89b44e4d3c81ede05d0f5de8d1a68f754d73d997")
20000000000000000020

To compare, this is a valid transaction (created and sent by some client)

> eth.getTransactionFromBlock(11)
{
  blockHash: "0x41919469d7ed9232adbcacc820e61ad508b30eb5fc4750d3cebd748c22b110b8",
  blockNumber: 11,
  from: "0xb7e13de69228c37cdff506ea474f31343af33c05",
  gas: 90000,
  gasPrice: 50000000000,
  hash: "0xa4d4a22aa1fed291a7da00e24304f7093b4fc09b1c6a18692e4240d6d913d674",
  input: "0x",
  nonce: 4,
  to: "0x89b44e4d3c81ede05d0f5de8d1a68f754d73d997",
  transactionIndex: 0,
  value: 20000000000000000000
}

Since geth can parse them, the format of my TXs has to be correct. I guess the only thing left is the signature. But I'm pretty sure the TX has been properly signed.

Is there a way to get more information about why a TX can't be processed? I'm using geth on my own blockchain so I can modify the source code if that helps.