texts: Signature not matching the sig obtained from MyEtherWallet

texts:
I am serializing the unsigned txn in C, then I found Keccak-256 hash and I signed it with the privatekey. However, the resulting signature is not the same as in MyEtherWallet for the same values(sender,to, value..)
void main()
{
    uint8_t digest[32];
    uint8_t sig[64], sig2[64], priv[32], *pby, unsigned_txn[200]={0};
    const ecdsa_curve *curve = &secp256k1;

    uint8_t txLen_,txLen, nonce_, gasPriceLen_,gasPrice_[33],gasLimLen_, gasLim_[33],toLen_, to_[21], valLen_,value_[33], data_, chainId_;

    //hardcoding the txn components for now
    memcpy(&txLen,"\x2b",1);     //actual length of the txn (for printing here)
    memcpy(&txLen_,"\xeb",1);      //length specified in unsigned txn
    memcpy(&nonce_,"\x02",1);
    memcpy(&gasPriceLen_, "\x84",1);
    memcpy(&gasPrice_, "\x3b\x9a\xca\x00", 4);
    memcpy(&gasLimLen_, "\x82",1);
    memcpy(&gasLim_, "\x52\x08", 2);
    memcpy(&toLen_, "\x94", 1);
    memcpy(&to_, "\x8f\x87\xd7\x0d\xb7\x15\xae\x66\xba\xd9\x8e\x6f\x36\xa0\x6e\x45\x39\x45\x0a\x3c", 20);
    memcpy(&valLen_, "\x88",1);
    memcpy(&value_, "\xb1\xa2\xbc\x2e\xc5\x00\x00", 8);
    memcpy(&data_, "\x80",1);
    memcpy(&chainId_,"\x04",1);
    struct unsignedTxn tx={txLen_, nonce_,gasPriceLen_, gasPrice_,gasLimLen_, gasLim_,toLen_, to_,valLen_, value_, data_, chainId_};

    //RLP encoding of the unsigned txn

    memcpy(&unsigned_txn, &txLen_, 1);
    memcpy(&unsigned_txn[1], &nonce_, 1);
    memcpy(&unsigned_txn[2], &gasPriceLen_, 1);
    memcpy(&unsigned_txn[3], &gasPrice_, (int)(gasPriceLen_)-128);
    memcpy(&unsigned_txn[3+(int)gasPriceLen_-128], &gasLimLen_, 1);
    memcpy(&unsigned_txn[4+(int)gasPriceLen_-128], &gasLim_,(int)gasLimLen_-128);
    memcpy(&unsigned_txn[4+(int)gasPriceLen_-128 + (int)gasLimLen_-128], &toLen_, 1);
    memcpy(&unsigned_txn[5+(int)gasPriceLen_-128 + (int)gasLimLen_-128],&to_, (int)toLen_-128);
    memcpy(&unsigned_txn[5+(int)gasPriceLen_-128 + (int)gasLimLen_-128+(int)toLen_-128], &valLen_, 1);
    memcpy(&unsigned_txn[6+(int)gasPriceLen_-128 + (int)gasLimLen_-128+(int)toLen_-128], &value_, (int)valLen_-128);
    memcpy(&unsigned_txn[6+(int)gasPriceLen_-128 + (int)gasLimLen_-128+(int)toLen_-128+(int)valLen_-128], &data_, 1);
    memcpy(&unsigned_txn[7+(int)gasPriceLen_-128 + (int)gasLimLen_-128+(int)toLen_-128+(int)valLen_-128], "\x04\x80\x80", 3);

    uint8_t message[200];
    memcpy(&message, "\x19Ethereum Signed Message:\n", 25);
    memcpy(&message[25], &unsigned_txn, (int)txLen+1);

    printf("\nSerialized Unsigned Transaction\n");

    for(int i=0; i<25+(int)txLen+1; i++)
    {
        printf("%02x", message[i]);
    }

    keccak_256(message, 25+(int)txLen+1, digest);

    printf("\nUnsigned Transaction Digest\n");

    for(int i=0; i<32; i++)
    {
        printf("%02x", digest[i]);
    }

    ecdsa_sign_digest(curve,priv,digest,sig,&pby,NULL);

    printf("\nSignature (64 bytes)\n");

    for(int i=0; i<64; i++)
    {
        printf("%02x",sig[i]);
    }
}

Here is my output:
Serialized Unsigned Transaction
9e7468657265756d205369676e6564204d6573736167653a0aeb02843b9aca00825208948f87d70db715ae66bad98e6f36a06e4539450a3c88b1a2bc2ec500000080048080

Unsigned Transaction Digest
df7419e94bfa4901441c60ca7155e7a6da2a9e73674605a0df3ff71b3ba31f18

Signature (64 bytes)
bbf9e67ad1b0dafdcab382b6efafe6e792c120dbffcf9d10cabeb6dd7c515fc866db3ae2635fc14a4d6204e46e22e4c0825a2acceded4943187e96d902a5a1e2

Here is the signed transaction on MyEtherWallet:


texts: Smart contracts code: what are nodes in Ethereum actually agreeing upon during the consensus process?

texts: When a contract is triggered, all nodes execute the code; where exactly does consensus come in?  Are they agreeing upon the OUTPUT or just the code itself?


texts:
I started with smart contracts and now having tons of doubts and expecting answers from experts. I read in one of the tutorials with insurance as an example - if 'date = '01-01-2019' then 'send money to all clients aged > 60'. Now this is the smart contract. Now i have the following questions

1) This is now getting pushed to the nodes in the block chain and why everyone is expected to execute this ?

2) If everyone is executing then will not the "then" condition executed that many times? i.e. wont the clients > 60 get the money == no of nodes / miners executing ?

3) If i try to relate this with Bit Coin, the miner does the proof of work and whoever finds the nonce with the HASH will be the winner - In this case - who gets the Ether ? - If everyone is executing who decides who is the winner and should get the 5 Ether?

4) Who pays the ether -i assume in this example the insurance company does that - please advise if i am not correct .

5) The smart contract code says - send money to all clients > age 60. Are all the clients expected to be in the Block Chain network with their address ? - Are they expected to have a wallet or account or client so that they get registered in the ledger .

Apologies if these are basic questions and i request the team to help for me to proceed to next stage ....thanks a bunch in advance.


texts: Error linking library when deploying with via Infura (ropsten)

texts:
I'm trying to deploy via Infura to ropsten and get this error.

The local deployment works without a hitch.

Linking SafeMath to contracts
Error encountered, bailing. Network state unknown. Review successful transactions manually.
undefined
truffle(ropsten)> Error: Cannot link library: SafeMath has no address. Has it been deployed?

The relevant lines from the deployment script are:

return deployer.deploy(SafeMath, {from: owner}).then(() => {
    console.log("Linking SafeMath to contracts");
    return deployer.link(SafeMath, [Cx1, Cx2]).then(() => {
        ...
    });
    ...
});

Am running from within truffle console --network ropsten  with ropsten configured for Infura.  The migration of the migration contract seems to work fine.

I'm doing doing a deploy.

It seems that unlike in local deployments, truffle is not updating the .json files.  Could this be the problem?


texts: Hello, I am new to dapp development, I am trying to start a geth node on android

texts:
but my application crashes after launching it, here is the error it tells me in my logcat
In my MainActivity.java

Blockquote

public class MainActivity extends AppCompatActivity {

   //private TextView accDisplayTextView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       //accDisplayTextView = findViewById(R.id.acc_display_textview);

       try {
           NodeConfig nc = new NodeConfig();
           Node node = Geth.newNode(getFilesDir() + "/.ethNode", nc);
           node.start();

           GethNodeHolder gethNode = GethNodeHolder.getInstance();
           gethNode.setNode(node);

       } catch (Exception e) {
           Log.e("error: ", e.getMessage());
           e.printStackTrace();
       }
   }
}

and my other error is that java cannot resolve the keystore class from org.ethereum.geth package

Blockquote

import org.ethereum.geth.KeyStore;

Can you Help me please


texts:
Using Web3, we are able to estimate the amount of gas needed for a transaction

let estimatedGas = web3.eth.estimateGas({
    to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
    data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})

contractObject.deploy().send({gas:estimatedGas, gasPrice: 2e9, ...})

Question: How can we estimate the gasPrice to use, instead of defining a static value like 2 Gwei?


texts:
I want to learn ethereum from the ground up. Is ethereum written in python or golang or another langauge?

With written I mean the reference implementation.


texts: Mining with ethermine, still nothing showing up in MyEtherWallet

texts:
Just a few days ago, I started mining with Claymore's Dual Miner on EtherMine.org. I have double checked my address on my batch file, etc. but there is still nothing showing up in my 'wallet'. Am I doing something wrong?

By the way, I am still pretty new to this, so don't judge!


texts: Garbage Value on Truffle console while executing the commands from a tutorial

texts:
I am following the tutorial at:
JustDev tutorial on medium
When I execute the command:
truffle(ganache)> Victim.deployed().then(contract => victim = contract)

I am getting a huge output which is something like that:

TruffleContract {   constructor:     { [Function: TruffleContract]
  _constructorMethods:

   { configureNetwork: [Function: configureNetwork],

     setProvider: [Function: setProvider],

     new: [Function: new],

     at: [AsyncFunction: at],

     deployed: [AsyncFunction: deployed],

     defaults: [Function: defaults],

     hasNetwork: [Function: hasNetwork],

     isDeployed: [Function: isDeployed],

     detectNetwork: [AsyncFunction: detectNetwork],

     setNetwork: [Function: setNetwork],

     setNetworkType: [Function: setNetworkType],

     setWallet: [Function: setWallet],

     resetAddress: [Function: resetAddress],

     link: [Function: link],

     clone: [Function: clone],

      still goes down to several pages which I am not showing due  to shortage of space

Somebody please guide me what is the problem.
Zulfi.


texts: what is the use of difficulty in ethereum blockchain?

texts:
Why ethereum has introduce difficulty and what is the use of difficulty in blockchain?
I have seen that we can use static difficulty for blockchain . So why we not use static difficulty for public blockchain.


texts: How to make API calls from a .NET Application to an Ethereum Private Network

texts:
I'm starting on blockchain development and I have a question:

I was wondering if it is possible to make RPC calls to a private ethereum network (handling user private keys is not a problem in our scenario) from a ASP.NET MVC application using web3js for example (or maybe other framework/library more suitable).

The calls would have as objectives sending tokens from one user to the other and checking a given user's balance.

Thanks in advance for your answers!!

Kind Regards,
Daniel Costa


texts: Unable to transfer ETH from contract wallet to main account

texts:
I have installed Mist 0.9.3 on Linux.
I have a main account with 0 ETH and a contract wallet with 0.21 ETH.
I am in full sync.

I try to transfer ETH from the contract wallet to the main account in Mist: the 'transfer' window shows the icon for my main account (with 0 ETH) but displays: My wallet: 0.21 ETH.
when I try to transfer, I get 'insufficient funds for gas * price + value, probably because it's trying to draw from the main account, which has 0 ETH.

How can I transfer the ether from my contract wallet to my main account?
I've tried on myetherwallet, but that only imports the keystore for my main account, which has 0 ETH. I think I'd need to import from the contract wallet first - so back to square one.

This is similar to Can't send from wallet contract to main account with Ethereum Wallet 0.9.0 - but with version 0.9.3

I'd try on Windows but I am not sure how to import my contract wallet there. I will soon run out of space with this full sync mode, but I do not think the light (beta version would work better).


texts: ethereum - call and delegatecall not working

texts:
pragma solidity >=0.4.22 <0.7.0;
contract D {
  uint public n;
  address public sender;

  function callSetN(address _e, uint256 _n) public {
    _e.call(abi.encode(bytes4(keccak256("setN(uint256)")), _n));
  }

  function delegatecallSetN(address _e, uint _n) public {
    _e.delegatecall(abi.encode(bytes4(keccak256("setN(uint256)")), _n));
  }
}

contract E {
  uint public n;
  uint public test;
  address public sender;

  function setN(uint256 _n) public {
    n = _n;
  }
}

That's my 2 example contracts. I am trying to understand call and delegatecall.
Problem 1: When I call callSetN in contract D and pass contract E's address and number: 20, it seems like that E contract's setN function gets called, but n variable doesn't become 20 in contract E.
Problem 2: When I call delegatecallSetN in contract D and pass contract E's address and number: 20, it still calls that function, but now, D contract's variable n doesn't become 20. Also at some point, I realized that for this one, setN doesn't called called at all.
Problem 3: I am starting to wonder why I'd need to use delegateCall in my code at all ? call seems enough and sufficient. Any example ?
Both of the problems seem to be related to how badly I use encode and _n variable.. Any ideas?


texts:
I checked the documentation about the msg object, but I could not find any explanation about how the msg is created. My interest is to understand the scope of msg and also if that object could be corrupted by a hacker (eg by changing msg.sender).

Has anyone any details about how msg is created in Ethereum?


texts:
There is something i do not understand about Polkadot.
Can we say Polkadot is a sidechain of Ethereum ? Or is it contestant of Ethereum ?
Is it correct to say "Polkadot is not a Layer 2 of Ethereum but a Layer 1 sidechain" ?
Thanks


texts: Any reason not to use Browser Solidity's "Enable Optimization"?

texts:
I found that when I had "Enable optimization" activated while writing a very simple contract with browser Solidity, it reduced a total of two SSTORE opcodes to one.  That resulted in 5000 gas saved.

Are these kinds of results typical?  Are there any trade offs?  Is there any reason not to have "Enable optimization" ticked?

Thanks.


texts: How to connect with smart contract using provider using node js?

texts:
When I am doing the following I'm getting this error:

var result = this.provider.send(payload);
TypeError: this.provider.send is not a function

What is the solution?


texts: Do calls from one contract to another contract get recorded as a transaction?

texts:
I know that you can call the method on the contract only by creating the transaction with the appropriate to field specifing the address of the contract to call.

But when you use a solidity contract to call a method on another contract, does it create a transaction or not? And why?


texts: How to process sending ether from contract address to an account

texts:
Let's say there's a button in html that can claim winnings.

<button type="submit" (click)="claimWinnigs()">Claim Winnings</button>

A user with account address 0xf17...b732 claimed winnings by clicking the button. What I want here is I want that user to be able to withdraw eth from the contract address (0x8f...b90f). Metamask is the tool I'm using.

simplified solidity:

mapping(address => uint256) public balanceOf

function claimWinnings() returns (bool) {
    balanceOf[msg.sender] = 20
    withdraw();

    return true;
}

function withdraw() public {
    uint256 balance = balanceOf[msg.sender];
    balanceOf[msg.sender] -= balance;
    msg.sender.transfer(balance);

    LogWithdrawal(msg.sender, balance);
}

Below is my angular web3 code:

claimWinnings(): Promise<any> {
    return this.TestContract.deployed().then((instance) => {
        return claimWinnings({
            from: contractAddress,
            gas: 1000000
        });
    })
    .then((value) => {
        return value;
    })
    .catch((e) => {
        console.log(e);
    });
}

But when I execute this, I get an error

Unknown address - unable to sign transaction for this address: "0x8f...b90f"

I'm testing with Ganache fyi.

What am I doing wrong here? and how can the user receive ether from the contract?


texts: smart contract containing Payable function is not working when deployed using new version of metamask. can anyone please resolve this issue?


texts: How to create withdrawal function from my contract

texts:
I want send ether from my contract to my address(owner). How can I transfer ether from my contract balance(this.balance) to my address(owner)? I use myEthterWallet to do this things. Address of this contract in the Ropsten testnet is 0x614Fe0B3C9E5E2157Ab76F0E91B819279854f709 .

I have contract:

pragma solidity ^0.4.15;

contract WithdrawalContract {

    address public richest;
    address public owner;
    uint public mostSent;

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

    }

    mapping (address => uint) pendingWithdraws;

    function WithdrawalContract () payable {
        richest = msg.sender;
        mostSent = msg.value;
        owner = msg.sender;
    }

    function becomeRichest() payable returns (bool){
        require(msg.value > mostSent);
        pendingWithdraws[richest] += msg.value;
        richest = msg.sender;
        mostSent = msg.value;
        return true;
    }

    function withdraw(uint amount) onlyOwner returns(bool) {
        // uint amount = pendingWithdraws[msg.sender];
        // pendingWithdraws[msg.sender] = 0;
        // msg.sender.transfer(amount);
        require(amount < this.balance);
        owner.transfer(amount);
        return true;

    }

    function getBalanceContract() constant returns(uint){
        return this.balance;
    }

}


texts: How can I return string array in solidity?

texts:
This is my struct:

struct Token {
    address tokenAddress;
    uint256 minAmount;
    bool emergencyUnlock;
    TokenStatus status;
    string name;
    uint256 decimal;
    string thumbnailUrl;
}

and a mapping:

mapping(address => Token) private _token;

A function returns details of the token when I asked given the indexes:

function getTokens(uint256 start, uint256 length) external view returns(
    address[] memory tokenAddresses,
    uint256[] memory decimals,
    string[] memory name
)
{
    tokenAddresses = new address[](length);
    name = new string[](length);
    decimals = new uint256[](length);

    require(start.add(length) <= _tokens.length, "Lock: Invalid input");
    require(length > 0 && length <= 15, "Lock: Invalid length");
    uint256 count = 0;
    for(uint256 i = start; i < start.add(length); i++) {
        tokenAddresses[count] = _tokens[i].tokenAddress;
        count = count.add(1);
        decimals[count] = _tokens[i].decimal;
        name[count] = _tokens[i].name;
    }
    return(
        tokenAddresses,
        decimals,
        name
    );
}

Now, the problem is that, it asks me that it is not supported to return array of string.
Error is below:

TypeError: This type is only supported in the new experimental ABI encoder. Use "pragma experimental ABIEncoderV2;" to enable the feature.
string[] memory name

Does anyone know the work around?
I know that name will not be more than 20 characters long ever.


texts:
I have found a link for replaying tx.origin vulnerability at:

Unable to replicate tx.origin
 I can’t understand the use of interface. Is it necessary to use interface? I am also getting a syntax error in case of interface because it has the same name as the name of user wallet?

Some body please guide me:

What is the use of interface in tx.origin vulnerability?
Should I not change the name of interface?.

Zulfi.


texts: How to transfer Ether between accounts in Solidity?

texts:
I'd like get ether balance of account in solidity. I tried the following, but it didn't work. Could you tell me how to do it?

contract MultiplyContract{
    address public buyer;
    address public seller;
    uint public price;
    function MultiplyContract(
      address _buyer,
      address _seller,
      uint _price,
      ){
      buyer = _buyer;
      seller = _seller;
      price = _price;
    }
    function Execution (address _buyer, address _seller) {
    eth.getBalance(_buyer) -=  price;
    eth.getBalance(_seller) += price;
  }
}


texts: Web3.py Sending Transaction Not Updating Contract

texts:
I'm new to the world of Web3.py however I have an ERC20 compliant contract and I am tryin to call the transfer() method on it to simply transfer some tokens from sender to receiver.

I am testing it by running a local Parity node on the dev chain parity --tracing=on --chain=dev (so everything is local)

My ERC20 contract has been created and tested externally so I know the contract itself works.

However, my python code is thus:

from web3 import Web3

### sender_address, receiver_address and private keys are initialised here ###

url = 'http://localhost:8545'
web3 = Web3(Web3.HTTPProvider(url))
print('Connected?', web3.isConnected()) # OUTPUT ==> True

token_address = '0x731a10897d267e19B34503aD902d0A29173Ba4B1'
abi = open('contract.abi', 'r').read()
contract = web3.eth.contract(address=token_address, abi=abi)

print(contract.functions.balanceOf(sender_address).call())   # OUTPUT ==> 3000000000000000000
print(contract.functions.balanceOf(receiver_address).call()) # OUTPUT ==> 0

nonce = w3.eth.getTransactionCount(sender_address)
tx = contract.functions.transfer(receiver_address, 123456789).buildTransaction({
    'chainId': web3.eth.chainId,
    'gas': 70000,
    'gasPrice': w3.toWei('1', 'gwei'),
    'nonce': nonce
})
signed_tx = w3.eth.account.signTransaction(tx, private_key=sender_pk)
tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)

mine_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
print(mine_receipt)

print(contract.functions.balanceOf(sender_address).call())   # OUTPUT STILL ==> 3000000000000000000
print(contract.functions.balanceOf(receiver_address).call()) # OUTPUT STILL ==> 0

The mine_receipt outputs:

AttributeDict({
    'blockHash': HexBytes('0x688e1f44bd2720d9581ad1e24c765bc1ef210d6431dd39d7d26c73a58f1ea11a'),
    'blockNumber': 60,
    'contractAddress': None,
    'cumulativeGasUsed': 24300,
    'from': '0x0D366F25CC54F1DCfD15c135C03a3D493636A730',
    'gasUsed': 24300,
    'logs': [],
    'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'),
    'status': 0,
    'to': '0x731a10897d267e19B34503aD902d0A29173Ba4B1',
    'transactionHash': HexBytes('0x76d8adb4489a3c725665694da173b800691b2f20778f96eb1c5c66abb18a4b20'),
    'transactionIndex': 0
})

And the Parity node logs:

2020-05-09 01:04:29  Transaction mined (hash 0x76d8adb4489a3c725665694da173b800691b2f20778f96eb1c5c66abb18a4b20)
2020-05-09 01:04:29  Imported #60 0x688e…a11a (1 txs, 0.02 Mgas, 0 ms, 0.66 KiB)

So it clearly accepts the transfer call, however as you can see by the last two print lines calling the balanceOf of both users again their balnce values have not changed at all.

Any help on what might be happening here would be appreciated.


texts: Is Ethereum a decentralized or distributed blockchain? I read the documentation but I can't understand.


texts: How can I check if a variable or an array is set or empty or null?

texts:
How can I check if a variable or an array is already set, empty or null in solidity?

For example,

  mapping (string => address) addresses;

How can we know addresses[key] is set or not?


texts: Testing payable functions with truffle console - where do you input msg.value?

texts:
Trying to test my token contract using truffle console + ganache, lets say I have a payable function someFunc(string _string, uint256 _int), how would I call it with arguments "hello", 100 and msg.value = 2 eth?

As a side q, where does the gas eth come from? is it taken from msg.value?


texts: How do I set up Ethereum / Mist wallet to watch for GNT

texts: I'm interested in exchanging some ETH for GNT, and send it to my Ethereum wallet. I understand that as a token, I will send it from the exchange to my Mist wallet address. Then how to I configure Mist, so that it watches and displays the GNT tokens?


texts: Vote counting issue in the Ethereum Association DAO example?

texts:
My question is about the Ethereum DAO Association example found here.

My question is on this bit of code:

struct Proposal {
    address recipient;
    uint amount;
    string description;
    uint votingDeadline;
    bool executed;
    bool proposalPassed;
    uint numberOfVotes;
    bytes32 proposalHash;
    Vote[] votes;
    mapping (address => bool) voted;
}
/*....*/

function vote(uint proposalNumber, bool supportsProposal)
    onlyShareholders
    returns (uint voteID)
{
    Proposal p = proposals[proposalNumber];
    if (p.voted[msg.sender] == true) throw;

    voteID = p.votes.length++;
    p.votes[voteID] = Vote({inSupport: supportsProposal, voter: msg.sender});
    p.voted[msg.sender] = true;
    p.numberOfVotes = voteID +1;
    Voted(proposalNumber,  supportsProposal, msg.sender);
}

function executeProposal(uint proposalNumber, bytes transactionBytecode) returns (int result) {
    Proposal p = proposals[proposalNumber];
    /* Check if the proposal can be executed */
    if (now < p.votingDeadline  /* has the voting deadline arrived? */
        ||  p.executed        /* has it been already executed? */
        ||  p.proposalHash != sha3(p.recipient, p.amount, transactionBytecode)) /* Does the transaction code match the proposal? */
        throw;

    /* tally the votes */
    uint quorum = 0;
    uint yea = 0;
    uint nay = 0;

    for (uint i = 0; i <  p.votes.length; ++i) {
        Vote v = p.votes[i];
        uint voteWeight = sharesTokenAddress.balanceOf(v.voter);
        quorum += voteWeight;
        if (v.inSupport) {
            yea += voteWeight;
        } else {
            nay += voteWeight;
        }
    }

    /* execute result */
    if (quorum <= minimumQuorum) {
        /* Not enough significant voters */
        throw;
    } else if (yea > nay ) {
        /* has quorum and was approved */
        p.executed = true;
        if (!p.recipient.call.value(p.amount * 1 ether)(transactionBytecode)) {
            throw;
        }
        p.proposalPassed = true;
    } else {
        p.proposalPassed = false;
    }
    // Fire Events
    ProposalTallied(proposalNumber, result, quorum, p.proposalPassed);
}

Specifically,

If we add new votes doing voteID = p.votes.length++; p.votes[voteID] = /*...*/ and then count them doing (uint i = 0; i <  p.votes.length; ++i) isn't there an index problem?

Here is the reasoning:

Initially the votes array is 0 hence p.votes.length = 0  and p.votes.length++ = 1 and then we increase from there. However, the loop starts counting from 0.


texts: retrieving an original data from a hash: is it reliable?

texts:
Normally, one of the purposes of hashing a string (such as a transaction) is summarizing the data to save the size because of the space limitation.

If this proposition is true, now assume we need to read the original data and so we need to extract the exact original data (with all details).

Now the question is if the extracted data from the hash data is exotically equal to the original data?

And if yes, is there any tool to do this? (for example, for retrivieng the original data from SHA256 hashing algorithm).

And if we cannot retrieve the original data from a hashed value, how hashed data can help us for validating an original data?


texts: Are there any ways that can check whether the data I am trying to store is already existed in the blockchain or not?

texts: I'm trying to store user data ( name, national identity number, birthday,etc.) by converting all data into hash and store it in the input field of block in the Blockchain. But , the problem is that how can I know  data I am trying to store is already existed in the blockchain cause I want to prevent data duplicate . I am running my blockchain on local private network using geth. By the way, is my data storing method okay or should I change to use smart contract for storing data.


texts: blockhash refactoring, if hashes are relative to latest block, are all stored in contract?

texts: The blockhash refactoring EIP included in Constantinople expands the range of blocks that can be accessed with blockhash(). Besides the last 256 blocks, 256 multiples of 256^1, and 256 multiples of 256^2 can also be accessed. The EIP also stores the blockhashes to a contract (was my impression). Since the range of blockhashes are from the latest block, does that mean that depending on the refence frame, all blockhashes will be available? For example, that over 256 blocks, the 256s multiples of 256^1 will provide every single block within that range (up to 256^2 blocks)? Is yes, why not just allow access to all those blocks from any reference frame?


texts: How to use truffle and testrpc and simulate function call masquerading as another user?

texts:
I have setup testrpc with two accounts using this syntax basically:

testrpc -h 0.0.0.0 --account=0x93e707aa1e3ada62,10000000000000000000 --account=0x47e7625a68200ea9,1000000000000000000

I can transfer eth between the two accounts using MetaMask.

I then used the Crowdfuding example as described here:

https://dappsforbeginners.wordpress.com/tutorials/contracts-that-send-transactions/

This defines two functions, newCampaign:

function newCampaign(address beneficiary, uint goal, uint deadline) returns (uint campaignID) {
    campaignID = numCampaigns++; // campaignID is return variable
    Campaign c = campaigns[campaignID]; // assigns reference
    c.beneficiary = beneficiary;
    c.fundingGoal = goal;
    c.deadline = block.number + deadline;
}

And, contribute:

//function to contributes to the campaign
function contribute(uint campaignID) {
    Campaign c = campaigns[campaignID];
    Funder f = c.funders[c.numFunders++];
    f.addr = msg.sender;
    f.amount = msg.value;
    c.amount += f.amount;

}

I can compile the contract successfully, and deploy seems to work.

I then jump into truffle console. I'm trying to create a new campaign with the first user, and then contribute to it with the second user.

From within truffle, I run this code:

CrowdFunding.deployed()
.then( function(inst) {
  return inst.newCampaign( "0x30924cD9D8e3644B1c186e3381694403A77f87b6", 50, 50 ); } )
.then( function(id) {
  console.log( "ID:", id ); });

This does not print out the expected campaign ID, as I expected. Instead it prints out:

ID: { tx: '0x3afb822beb6dae9d73db0505ba0ee1056902e5c968bd8a6888fe0024f633f8e4',
  receipt:
   { transactionHash: '0x3afb822beb6dae9d73db0505ba0ee1056902e5c968bd8a6888fe0024f633f8e4',
     transactionIndex: 0,
     blockHash: '0xccd15e9cb18c9b0d8d9c4298bb886c427f155318755c241515796cb0483ff66d',
     blockNumber: 9,
     gasUsed: 88745,
     cumulativeGasUsed: 88745,
     contractAddress: null,
     logs: [] },
  logs: [] }
undefined

Q1: So, that's my first problem, how do I get the campaignId supposedly returned from the newCampaign call?

Q2 Obviously I will then want to call the contribute function. But, I'm confused as to how I masequerade as the second user? I can get their address from MetaMask, but do I do something like this:

CrowdFunding.deployed()
.doTheThingsToGetCampaignId(). // fix the above code...
.then( function(inst) {
  tx = { from: 0x132123 # The second account's address?
  return inst.contribute( campaignId, 50 ).call( tx ); // What should be here?
} );

Q3: I see various examples like inst.contribute.call(...). What's the right way to call contribute from truffle?


texts: How many smart contracts one should have?

texts:
Suppose there are 4 entities, A, B, C and D. A provides its identifier to B and seeks its decision. B needs to call C providing it with the identifier of A and some other parameters so that it can arrive at some decision. Similarly, C needs to call D. And maybe so on.
Should there be a single contract or multiple contracts and between whom? Should there be a single contract among all the entities with different methods which are supposed to be called by expected entities? Or, there should be one contract between A and B, one contract between B and C, one contract between C and D and so on?


texts:
I want to import my account of MetaMask(testnet) to the geth accounts list.

First I copied the private key from MetaMask and saved to a txt file.

After that I run this command :

geth account import /path/to/file.txt --testnet console

Absolutely, I get my account to the list:

geth account list

But in MetaMask I have some ethers, but from the geth console when I want to check my balance for the same account, I get 0 ether.

Is it possible to sync the balance ?,by the way I run the update command:

geth account update 0x....

I got the same problem.


texts: Problem getting data from a different deployed contract - Solidity

texts:
I've been working on the cryptozombies tutorial and now i want to go further but when trying to deploy the contract on REMIX to test it i'm having problems. I get:

transact to ZombieFeeding.feedOnKitty errored: VM error: revert.
revert  The transaction has been reverted to the initial state.

Note: The constructor should be payable if you send value.  Debug the transaction to get more information.` error.
The code is:

pragma solidity ^0.4.24;
import "./zombiefactory.sol";

contract KittyInterface {
    function getKitty(uint256 _id) external view returns (
       bool isGestating,
       bool isReady,
       uint256 cooldownIndex,
       uint256 nextActionAt,
       uint256 siringWithId,
       uint256 birthTime,
       uint256 matronId,
       uint256 sireId,
       uint256 generation,
       uint256 genes
     );
}

contract ZombieFeeding is ZombieFactory {

KittyInterface kittyContract;

    modifier onlyOwnerOf(uint _zombieId) {
        require(msg.sender == zombieToOwner[_zombieId]);
        _;
    }

    function setKittyContractAddress(address _address) external onlyOwner {
        kittyContract = KittyInterface(_address); //0x06012c8cf97bead5deae237070f9587f8e7a266d
    }

    function _triggerCooldown(Zombie storage _zombie) internal {
        _zombie.readyTime = uint32(now + cooldownTime);
    }

    function _isReady(Zombie storage _zombie) internal view returns (bool) {
        return (_zombie.readyTime <= now);
    }

    function feedAndMultiply(uint _zombieId, uint _targetDna, string   _species) internal onlyOwnerOf(_zombieId) {
        Zombie storage myZombie = zombies[_zombieId];
        require(_isReady(myZombie));
        _targetDna = _targetDna % dnaModulus;
        uint newDna = (myZombie.dna + _targetDna) / 2;
        if (keccak256(abi.encodePacked(_species)) == keccak256("kitty")) {
            newDna = newDna - newDna % 100 + 99;
        }
        _createZombie("NoName", newDna);
        _triggerCooldown(myZombie);
    }

    function feedOnKitty(uint _zombieId, uint _kittyId ) public {
       uint kittyDna;// = 456127291358119496194667091109459857780766667351016867864478616867222987;
       (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
       feedAndMultiply(_zombieId, kittyDna, "kitty");
    }
}

And after debugging I've noticed that if i set the kittyDna variable to something by myself instead of using the (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId); line then everything works. My guess is that the way i am implementing the Kitty interface is wrong? BTW I'm not using the mainnet. What i want to do is get the genes value from the cryptokitties getKitty contracts function. Thanks in advance for any help !


texts: Flash loan compile error with function() external payable

texts:
I am attempting to compile a flash loan contract. I am having issues with the external payable function. I've tried adding fallback or receive as the error message suggests but I still receive the same error. Is there a particular way this line of code needs to be written? All help appreciated. Thanks.
contract FlashLoanReceiverBase is IFlashLoanReceiver {
    using SafeMath for uint256;

    address constant ETHADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    ILendingPoolAddressesProvider public addressesProvider = ILendingPoolAddressesProvider(
        0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
    );

    function() external payable {}

    function transferFundsBackToPoolInternal(address _reserve, uint256 _amount)
        internal
    {
        address payable core = addressesProvider.getLendingPoolCore();
        transferInternal(core, _reserve, _amount);
    }

    function transferInternal(
        address payable _destination,
        address _reserve,
        uint256 _amount
    ) internal {
        if (_reserve == ETHADDRESS) {
            //solium-disable-next-line
            _destination.call.value(_amount)("");
            return;
        }

        IERC20(_reserve).transfer(_destination, _amount);
    }

    function getBalanceInternal(address _target, address _reserve)
        internal
        view
        returns (uint256)
    {
        if (_reserve == ETHADDRESS) {
            return _target.balance;
        }

        return IERC20(_reserve).balanceOf(_target);
    }
}


texts:
When ti try to estimate gas for my contract to deploy, I always get undefined result.

This is my code:

const toDeploy = contract.deploy({
    data: '0x' + bytecode,
    arguments: [[web3.utils.asciiToHex('Name1'),web3.utils.asciiToHex('Name2')]]
});

const getGasPrice = () => {
    return new Promise((resolve, reject) => {
        web3.eth.getGasPrice((error, result) => {
            if (error) reject(error)

            console.log('Gas price: ', result);
            resolve(web3.utils.toHex)
        })
    })
}

const getGasLimit = (toDeploy) => {
    return new Promise((resolve, reject) => {

        toDeploy.estimateGas((error, result) => {
            if (error) reject(error)

            this.gasLimit = result
            this.minGasLimit = result

            console.log('Gas : ', result); // PROBLEM HERE!
            resolve(web3.utils.toHex(parseInt(result * 1.1)))
        })
    })
}

Promise.all([getGasPrice(), getGasLimit(toDeploy)])
    .then(values => {
        const opt = {
            from: web.eth.accounts[0],
            gas: values[1],
            gasPrice: values[0]
        }
        return opt
    })
    .then(opt => {
        toDeploy
            .send(opt)
            .then((instance) => {
                console.log("Contract mined at " + instance.options.address);
                contractInstance = instance;
            });
    })
    .catch(e =>
        console.log(e)
    );

Can anyone help me?
Thank you


texts:
I have a deployed contract (contract A) which should act as a storage (let's say 0xD7ACd2a9FD159E69Bb102A1ca21C9a3e3A5F771B).
Now from my ERC20 Token contract (contract B), I am calling approve to the contract A to allow it to "withdraw" my tokens.
Would it be possible to call trasnferFrom of contract A inside another function of contract B?
I am trying with (inside the code of B)
address A = 0xD7ACd2a9FD159E69Bb102A1ca21C9a3e3A5F771B;
...
approve(A,_amount);
A.call(bytes4(keccak256("transferFrom(address, address, uint256)")), (_B, msg.sender, _amount));

But it doesn't work since I am giving too many arg to the call function.
What would be the best way to transfer automatically my token (contract A) to a deployed ERC20 contract from within the contract B itslef?
EDIT
So on my receiver contract A, I added the function:
    function getTokens (address from, uint256 value) public returns (bool) {
        transferFrom(from, address(this), value);
        return true;
    }

And on my sender contract B I am calling:
    address contract_address = 0x09943Fa8DD32C76f7b880627a0F6af73e8f5A595 ;

...
        approve(contract_address, _value);
        contract_address.call(abi.encode("getTokens(address, uint256)",msg.sender, _value));
...

But even if tx is succesfull, when I check balance of contract A, it's 0.
I don't know exactly what I am missing.


texts: How to get blockNumber of contracts deployed with truffle?

texts:
We deploy our contracts with truffle migrate.

We need the blockNumber of the contract deployment transaction in the webapp.

We could use web3.eth.getTransaction(txhash).blockNumber() but can't get txhash in the app because JSON files generated by truffle doesn't contain it.

How can I retrieve contract deployment blockNumber on front end app?


texts: Is it possible to interact with smart contracts on mainnet but from a testnet?

texts:
I am writing a script in web3js to interact with a smart contract that is on the mainnet. This is not a smart contract I control.

I want to test / develop using a testnet. So how can I check my script runs correctly without directly interacting with it on mainnet? Or do I have to rely on that smart contract being deployed on one of the testnets?


texts: Filtering on events of the entire blockchain not possible in testrpc via truffle

texts:
A contract I wrote has an event in its constructor.
Since I want to find it back in the logs it doesn't seem possible to start listening to the latest block.
Because the event is already 'fired' during the creation of the instance.

So I lookup the event throughout the entire chain starting at the genesis block:

instatiatedEvent = instance.InstatiatedEvent({'senderAddress': senderAddressMock,
'ownerAddress': ownerAddressMock}, {fromBlock: 0, toBlock: 'latest'});

Both event parameters are indexed.

I tested it on a private blockchain and it the filtering worked, but when I test it on TESTRPC, it returns all the events of the contract instance - without filtering.

Can someone confirm that this functionality isn't working in TESTRPC?


texts: how to read smart contract A's data from other smart contract B in ethereum?

texts:
Currently, we can read the contract A data with the help of getters functions defined in contract A.
But I want to do something like contract A puts some data in ethereum blockchain but do not define the getters or other functions to access it. And then using another smart contract B, I want to access smart contract B data directly from blocks fo ethereum blockchain.


texts: Truffle - Error: sender doesn't have enough funds to send tx

texts:
truffle(development)> app.waterTree(0, {value: .0000000000001})
Error: sender doesn't have enough funds to send tx. The upfront cost is: 1188468318377797839569896498995073351059306341883237633081 and the sender's account only has: 99909466300000000000

I've tried two different functions and got the same result:

function waterTree(uint id) public payable {
    trees[id].ethValue += msg.value;
    //valueOfTree[id] += msg.value;
}

I have gas price set to 1 wei on Ganache and the gas limit is sitting at 7m.


texts:
Is there a method to wait a certain amount of seconds in idle?

I want to simulate a production process within a prototype smart contract and therefore i want to wait 5 seconds to represent this process.


texts: Transfer ERC20 token in mainnet with web3js(succeed in ropsten, failed in mainnet)

texts:
I want to transfer some ERC20 tokens in ethereum. I did some preparation work and tried in ropsten, it succeed. Then I changed the used api, wallet address, httpProvicer, contract address, and ran the code, but it failed. I didn't find why. Could you help me?

Below is the main part of my code.

web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/xxxx"));
let WALLETBASE = "xxx";
let contractAddr = "xxx";
let gasPrice = web3.utils.toHex(41 * 10^9); //41gwei

let abi = JSON.parse(fs.readFileSync("./file.abi").toString("utf8"));
let contractInstance = new web3.eth.Contract(abi, contractAddr);
function setAllocation(_nonce, _to, _amount){
console.log('prepare for new transaction: %s %s', _to, _amount);
var transfer_amount = _amount + '000000000000000000';
let data = web3.utils.sha3("transfer(address,uint256)").substr(0,10)
            + "000000000000000000000000"
            + _to.substr(2,40)
            + "00000000000000000000000000000000"
            + toHex32(transfer_amount);
var noncehex = "0x" + _nonce.toString(16);
// console.log('data: ' + data);

web3.eth.estimateGas({
    "from" : WALLETBASE,
    "nonce": noncehex,
    "to"   : contractAddr,
    "data" : data
}).then((value) => {
    console.log("gas limit: " + value);
    var signedTx = {
        "from"      : WALLETBASE,
        "nonce"     : noncehex,
        "gasPrice"  : gasPrice,
        "gasLimit"  : value,
        "to"        : contractAddr,
        "value"     : "0x00",
        "data"      : data,
        "chainId"   : 1
    }

    var privateKey = new Buffer.from("xxxx", 'hex');
    var tx = new Tx(signedTx);
    tx.sign(privateKey);
    var serializedTx = tx.serialize();

    try{
        web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),
            function(err, hash) {
            if (!err) {
                console.log("-------------------");
                console.log("to: " + _to);
                console.log("TxHash: " + hash);
            } else {
                console.log("=====error occur=====");
                console.log(err);
            }
        });
    }catch(err){
        console.log('ERROR: ' + err);
    }
});
}

when i run the code, it takes a long time without any response. for about 5 mins, I got the error:

(node:1336) UnhandledPromiseRejectionWarning: Error: Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
at /Users/.../node_modules/web3-core-method/src/index.js:392:42
at process._tickCallback (internal/process/next_tick.js:178:7)
(node:1336) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1336) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

PS: the wallet address does not belong to me. The owner gave me the private key and i transfer tokens on behalf of him. Is there any identity authorization issues?


texts: If me and a friend mine on different computer, how can we not process the same hash when mining?

texts:
So I was thinking if 2 people are mining or 10 what to stop each one of the miners from going over the same hash twice on different machines?

Here's an example.

Say if I had 5 machines all identical in hardware and software, If I set them to mine at the exact same time will they all go through the same hashes at the same time essentially making the 5 machine just as powerful as the 1?


texts:
My code to calculate the dividend someone is owed is as such :

function ViewDividendOwed(address) public view returns (uint256) {
  if (!RestrictedFromDividend[msg.sender]) {
    return _balances[address(this)].div(100000000).mul(_balances[msg.sender]);
  } else {
    return 0;
  }
}

In my testing I used the following numbers:
300 for the contract holding

99,000,000 for the msg.sender balance

Which should do the following, once accounted for decimals

300/100000000*99000000 = 270

However, for some reason, it returns 2100000000000000 once accounted for decimals, and under no circumstances is it possible to reach this final answer with the numbers given. What has gone wrong?


texts:
I want to use the following code to monitor the latest block
from web3 import Web3
import asyncio
def handle_event(event):
    print(event)
    # and whatever
async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event['transactionHash'])
        await asyncio.sleep(poll_interval)

def main():
    w3 = Web3(Web3.WebsocketProvider('wss://mainnet.infura.io/ws/v3/xxx'))
    block_filter = w3.eth.filter('latest')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(block_filter, 2)))
    finally:
        loop.close()

if __name__ == '__main__':
    main()

，Can you help me? I just want to get the latest transaction and address in the block, but why the output of the above code is garbled
b'G~Cz\x80\xa2\xe6\xaa\x81h\xab\xd9\xc6[\x03I0Hwu\xfc\xedw\r \x7fv~Z`\xf5\xea'
b'\x9d\x0b\xb1\xd6\x93\xb1JT\x99\xd8p\x00\xc0q\x8fjA\xf7e\xb1sz\xc6V\xf4\x8fB\xbb(\x08V\xc4'


texts: Are there any rinkeby testnet faucets that don't require social network accounts?

texts:
Are there any rinkeby testnet Faucet's that don't require social network accounts?

https://www.rinkeby.io/#faucet wants requests centralized twitter/g+/fb posts.


texts: UTXO vs Account scalability paradigms and Merkle proof of ownership

texts:
From Ethereum's design rationale:

Potential scalability paradigms: UTXOs are more theoretically
compatible with certain kinds of scalability paradigms, as we can rely
on only the owner of some coins maintaining a Merkle proof of
ownership, and even if everyone including the owner decides to forget
that data then only the owner is harmed. In an account paradigm,
everyone losing the portion of a Merkle tree corresponding to an
account would make it impossible to process messages that affect that
account at all in any way, including sending to it. However,
non-UTXO-dependent scalability paradigms do exist.

I don't really understand the difference. In Bitcoin's UTXO paradigm, the owner of some coins must hold a private key for the destination address of an UXTO to prove ownership of the coins. If the key is lost, the coins are lost.
As I understand, the same would happen in the account paradigm, except the owner would lose an account balance instead of an unspent transaction. What else would be lost in an account paradigm? How is that related to scalability?
Also, I understand what Merkle trees are and how they are used for storing transactions but what is a "Merkle proof of ownership"?
Thanks in advance.


texts: How is the EVM initialized for a message call transaction?

texts:
I'm reading the yellow paper, but there are several aspects of how the EVM execution model is initialized for each message call transaction that aren't really clear.  Where does the message call data go?  Does it become the initial stack contents or memory contents?  Whichever it becomes, is the other just initialized to zero?

Also, does the program counter always initialize to zero?  I don't see anywhere in the transaction structure that allows you to initialize it to something else.  I guess this would mean that one contract is like one function in a "traditional" procedural programming sense, but with a wei balance and dedicated storage attached.


texts: How to prevent token transfer until certain day in my smart contract

texts:
I have made this smart contract test, but I need to add the function to prevent any wallet to transfer token until the first of January of 2018.

What would be the code needed to achieve this?

Thanks


texts: Wallet transactions call functions in (ERC20) token contract to send tokens?

texts:
Firstly, thank you for helping me out in understand this. Suppose, if I have an ERC20 token contract (with all the required functions implemented including Transfer() function) deployed on the blockchian and a wallet implemented with basic functionality, say send tokens from my address to another wallet address.

To send tokens, my wallet creates a transaction, signs it and sends it to the blockchain. If I am not wrong, this transaction invokes Transfer() function which subtract tokens in my account and adds them to the receiver account. On successful invocation, the tokens are transferred.

Similarly, all the other functions are invoked through my wallet right? Sorry, if it is a silly question to ask.

Thanks Muni


texts: getTransactionCount always returns 1048576, no matter what address

texts:
No matter what random address I use, web3.eth.getTransactionCount always prints 1048576

web3.eth.getTransactionCount("0xb222a0f8f77dbbc3a0fc87f77717ddc59cf225d7")

1048576

Let say, I change a simple character in the address (the last character from 7 to 8)

web3.eth.getTransactionCount("0xb222a0f8f77dbbc3a0fc87f77717ddc59cf225d8")

1048576

Shouldn't it display 0? Interestingly, the number 1048576 is 0x100000 in hexadecimal.

Perhaps I'm doing something very stupidly wrong... but I can't get behind it.


texts:
pragma solidity ^0.4.4;
import "./strings.sol";

contract XFinance {
   using strings for *;

    address addr;
   uint coin;
   Shipment shipment;

function XFinance(uint balance) {
    coin=balance;
    shipment=new Shipment();

  }

function changeShipmentStatus(string shipmentId,string st,address driverAddress){

            shipment.setShipmentId(shipmentId);
            shipment.setStatusOfShipment(st);
        processPayment(driverAddress);
}

function processPayment(address driverAddress){
    string currentStatus=shipment.getStatusOfShipment();
    if(currentStatus.toSlice().equals('RAP'.toSlice())){
        shipment.setAddressOfDiver1(driverAddress);
        sendPayment(driverAddress);
    }
    else if(currentStatus.toSlice().equals('DAL'.toSlice())){
        shipment.setAddressOfDiver2(driverAddress);
        sendPayment(driverAddress);
    }

    else
    if(currentStatus.toSlice().equals('ATD'.toSlice())){
        shipment.setAddressOfDriver3(driverAddress);
        sendPayment(driverAddress);
    }
}

function sendPayment(address beneficiary) payable returns(bool success) {
  if(msg.value==0) throw;
  if(!beneficiary.send(msg.value)) throw;
  return true;
}

function getBalance() returns(uint){
    return coin;
}

function getStatus() returns(string){
    return shipment.statusOfShipment;
}

function getAddress() returns(address){
    return addr;
}

}

contract Shipment{
    string public shipmentId;
    string public statusOfShipment;
    address public driver1;
    address public driver2;
    address public driver3;

    function Shipment(){}

    function setShipmentId(string shId){
    shipmentId=shId;
    }
    function getShipmentId() returns(string){
    return shipmentId;
    }

    function setStatusOfShipment(string st){
    statusOfShipment=st;
    }
    function getStatusOfShipment() returns(string){
    return statusOfShipment;
    }

    function setAddressOfDriver1(address d1){
    driver1=d1;
    }
    function getAddressOfDriver1() returns(address){
    return driver1;
    }

    function setAddressOfDriver2(address d2){
    driver2=d2;
    }
    function getAddressOfDriver2() returns(address){
    return driver2;
    }

    function setAddressOfDriver3(address d3){
    driver3=d3;
    }
    function getAddressOfDriver3() returns(address){
    return driver3;
    }
}

This is my contract

I get error while compiling it

C:/Users/User(LPT-APR2015-02)/solidity-experiments/contracts/XFinance.sol:35:2: Error: Type inaccessible dynamic type
is not implicitly convertible to expected type string storage pointer.
        string currentStatus=shipment.getStatusOfShipment();
        ^-------------------------------------------------^
,C:/Users/User(LPT-APR2015-02)/solidity-experiments/contracts/XFinance.sol:37:3: Error: Member "setAddressOfDiver1" no
t found or not visible after argument-dependent lookup in contract Shipment
                shipment.setAddressOfDiver1(driverAddress);
                ^-------------------------^


texts: Blockchain sync... what am I doing wrong?

texts:
Okay,

I know this has been asked a thousand times (i know this because I've seen all the post/threads) but I have to ask again in hopes something has changed.

I am trying to run a node and no matter what I do it never seems to sync. Its made it to block #1.6M after TWO DAYS but my computer crashed.

This last run I used (after clearing my db):

geth --fast --cache=1024

It took almost two days for it to get to block # 1.6M and then my machine locked up. After a reboot I saw it started back on block 0 and is very slow.

I made a copy of my chaindata before booting up geth in case it cleared out for some reason.

What can I do to increase this sync time?!


texts: Is is possible to do something with this NMR token send to ethereum wallet?

texts:
You can see the transaction here:
Too much money for sure and for me. Is it lost? Hope not, tried to send by using myetherwallet they ask to have at least 0.1 ETH (30$), I have only 2$.

Is it possible to send via downloading full block-chain?


texts: how to import multiple files on remix IDE using github url?

texts:
i'm using the following way! but got error URL not parseable: Ownable.sol!!

import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";


texts: Is it feasible to write a DApp that targets multiple blockchains

texts:
This question does not target Ethereum specifically, but I hope you can help me out! If my questions are too specific, I apologize in advance.
I'm trying to utilize Blockchain's immutable + provable nature of transactions. As I currently have only one node, I assume I can only utilize a public Blockchain and hook up a DApp to it.
I know of various frameworks for Ethereum DApps (like Nethereum), though I don't want to be restricted solely to the Ethereum Blockchain. This includes various other Blockchain-specific frameworks.
Are there any frameworks which allow for changing the framework to a different Blockchain, without too much trouble?
Also if this does not exist, would such an approach be feasible for one person without a framework?
I did quite a broad research, but sadly did not find any answers. Only assumption I have is that it's not possible due to only Ethereum being Turing-complete, thus limiting smart-contracts for other blockchains.


texts: How do I deploy a contract, then send and retrieve a string from it?

texts:
I wish to store strings on-chain.

From what I understand so far, I need to set up a contract, then I can send transactions (with a string) to that contract which will be stored. Is this the best way to do this?

So far I have been able to setup a contract, though if my previous method is suitable, how would I:

Setup my contract to receive & send a string
Setup my transaction to send & receive a string

Contract so far:

contract mortal {
    /* Define variable owner of the type address */
    address owner;
    string str;

    /* This function is executed at initialization and sets the owner of the contract */
    function mortal() { owner = msg.sender; }

    /* Function to recover the funds on the contract */
    function kill() { if (msg.sender == owner) selfdestruct(owner); }

    function set(string val) public {
        str = val;
    }

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

Not sure how to proceed with a send/receive transaction? Would I need to invocate both web3.eth.sendTransaction to send & web3.eth.call to receive? If so how could I do this?


texts: What is the most preferred way to listen to events

texts:
After studying about solidity events, my understanding is that receiving an event doesn’t guarantees that the transaction is final. Transaction may yet to be included into the block. And even if it gets included in the block, it can get removed later on because of an uncle block.

I also read that Exchanges usually use some N block confirmation or even more, to make sure transaction is irreversible.

My questions are :

How can I implement a N block confirmation in dapp design and make it foolproof.
Consider a case wherein we need to add/update data in an off-chain base based on events, then how and when should we decide that transaction has been written to the blockchain and we can commit data to the off-chain database ?
How to handle case if the block containing the transaction has become an Uncle Block? Again how and when to update the off chain data.

I am curios to know how production grade dapps which run on main net handle these scenarios and maintain data integrity in case they have any logic which depends on events.


texts: Warning! Error encountered during contract execution [Reverted] - Missing SNX Tokens


texts:
I am not sure how to accept a decimal input to the function then calculate with token decimal.

Said the token decimal is 18
If the function wants to accept the value 123.4567, how to get the output result in 123456700000000000

I tried the following won't work because the input type already cut the decimal before it entered into the function

function chkAmt(uint _amt) view public returns(uint256){
     uint256 finalAmt = amt;
     return finalAmt;
}

This output 123 without the remaining number. I think the uint _amt already ignore the decimal as it is unsigned integer.

I tried the following also failed. If I input with 123.34567

uint8 public token_decimal = 18;
function chkAmt(uint _amt) view public returns(uint256){
    uint256 decfactor = 10**uint256(token_decimal);
    uint256 rtnamt = _amt.mul(decfactor);
    return rtnamt;
}

The output is 123000000000000000000 which is not right.

What is the correct way to input 123.4567 and get the output to 123456700000000000000???


texts: How does the gas pricing work exactly, and why does it change to execute the same transaction?

texts:
I have been trying to understand exactly how the gas pricing works in the Ethereum Wallet. I wanted to estimate the gas consumption for the transfer of 1 ETH from one account to the other, so I simulated this transfer with the testnet.

In the first time I did it, the estimated fee consumption was 0.00042 ETH for the tranfer of 1 ETH from one account to the other. I tried to do it again to see if anything changes, and I realized the fee varies around this value, sometimes above it, like 0.00045 and sometimes below it, like 0.00038. I've executed the tranfer of 1 ETH again but this time with 0.00038 ETH and it worked perfectly.

So, if the gas price is limited to 10 Szabo for now, why does this variaton occur, even if it is a small one? And also, if 0.00042 ETH is only an estimated fee and the real fee may be below it (which would explain why the transaction with 0.00038 ETH worked), then why the remaining gas that was not used didn't return?

Thank you very much


texts: How storing private key in blockchain is secure (FADB paper by Hui Li)?

texts:
I am a newbie in blockchain and smart contract. I was reading the following paper.
FADB: A fine-grained access control scheme for VANET data based on blockchain
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9086009
The paper stored private key in Identity Blockchain (Section IV.A.4, page 5-6). I was somewhat confused here. Since blockchain is public, is it not insecure? I think I am missing some basic point. Can somebody help me understand how storing private key in blockchain here is secure?


texts:
I accidentally sent 10 Ethereum to my Ethereum Classic wallet in Bittrex. Please help i’m despirate. I’m very new to this crypto currency and this is a hard earned money.

Bittrex replied they only recover if the value is more than $5,000 for a fee of 0.1 Bitcoin. Mine has a value of only $2,500.

Is there a way to recover this?

Thank you do much.


texts: Etheruem Wallet: Can't Switch Back To Main Network

texts: When I open my Ethereum Wallet, I'm automatically assigned to Test-Net. I can switch to a private network I created. Then I have the option to go back to the Main network, from the menu options, but when I do so, I'm automatically placed in Test-Net. Any ideas how to get back to Main?


texts: What is SSZ SimpleSerialize and why was it developed?

texts:
We were looking at the latest spec and it didn't have much background information or explanation on what SSZ is trying to achieve. What are the key goals of SSZ?

Examples of its serialization and Merkleization advantages would be very helpful as this may be a canonical question.


texts: Which password is required to unlock my accounts?

texts: What password is my geth 1.3.5 ethereum wallet asking for when I try to send a transaction? I am having trouble figuring this out since I don't remember a wallet password on setup.


texts: Deploy smart contract on Ropsten with Truffle without truffle-hdwallet-provider

texts:
Here is my truffle-config.js

networks: {
 ropsten: {
  network_id: 3,
  host: '127.0.0.1',
  port: 8545,
  gas: 4000000,
  from: "address_in_metamask"
},

I ran a geth node using the command:

geth --cache=1048 --testnet --unlock "address_in_metamask" --rpc --rpcapi "eth,net,web3" --rpccorsdomain '*' --rpcaddr localhost --rpcport 8545

After this in another tab, I ran the command

truffle migrate --network ropsten

I expected the smart contract to be deployed. But then I get the message as

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Migrations dry-run (simulation)
===============================
> Network name:    'ropsten-fork'
> Network id:      3
> Block gas limit: 0x1e8480

1_initial_migration.js
======================

Deploying 'Migrations'
----------------------
Error: Error: Error:  *** Deployment Failed ***

"Migrations" -- sender account not recognized.

at Object.run
(/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-
migrate/index.js:84:1)
at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.0.18 (core: 5.0.18)
Node v10.16.0

I have given the correct account address from Metamask which has enough ethers, yet it's not working. Please help.

Thank you.


texts: web3.js Contract returning null instead of an array

texts:
Simple contract:

contract ex {
   address[] users;
   function addUser() public {
        users.push(msg.sender);
   }

   function returnUsers() constant returns (address[]) {
       return users;
   }
}

In web3js I have the contract instance exInstance:

var abi = { /* some ABI */ };
var exInstance = web3.eth.contract(abi).at(someaddress);

function getUsers(){
   let users = exInstance.returnUsers.call();
}

And the result is that users is a null.
Tried async:

function getUsers(){
   exInstance.returnUsers.call(function(error, users)
      /// some actions
}

But still null.

Am I doing something wrong or I just should iterate it in web3js and in contract just use something like returnUsers(uint i) constant returns (address) { return users[i]; } ?


texts: Transfer ERC20 Token - Encountered during contract execution [Reverted]

texts:
When trying to sent some ERC20 Token from wallet getting following error:

 Warning! Error encountered during contract execution [Reverted]

This error returned when i call transferFrom()( I made approve() before it ) and transfer(). Furthermore, I have of lot gas/token amount of my addresses/wallets.

Smart
Contract code :

pragma solidity ^0.5.7;

contract ERC20 {
   //core ERC20 functions
  function allowance(address _owner, address _spender) public view returns (uint remaining);
  function approve(address _spender, uint _value)  public returns (bool success);
  function balanceOf(address _owner) public view returns (uint balance);
  function totalSupply() public view returns (uint);
  function transfer(address _to, uint _value) public returns (bool success);
  function transferFrom(address _from, address _to, uint _value) public returns (bool success);
// logging events
  event Approval(address indexed _owner, address indexed _spender, uint _value);
  event Transfer(address indexed _from, address indexed _to, uint  _value);
}

contract Transfer  {
    ERC20 public token;
    uint public balance = 0;
    address public owner;
    constructor (address _tokenAddress) public {
        owner = msg.sender;
        token = ERC20(_tokenAddress);
    }

    function() payable external {
        balance += msg.value;
    }

    function transferETH(address payable _to, uint256 _value) public onlyOwner returns (bool){
        _to.transfer(_value);
        return true;
    }

    function transferEth2Many(address payable[] memory _receivers, uint[] memory _values) public onlyOwner returns (bool) {
        require(_receivers.length == _values.length && _receivers.length >= 1);
        for (uint j = 0; j < _receivers.length; j++) {
            _receivers[j].transfer(_values[j]);
        }
        return true;
    }

    function totalSupply() public view returns (uint) {
        return token.totalSupply();
    }

    function balanceOf(address who) public view returns (uint) {
        return token.balanceOf(who);
    }

    function allowance(address _owner, address _spender) public view returns (uint){
        return token.allowance(_owner, _spender);
    }

    function approve(address _spender, uint _value) public returns (bool success){
        return token.approve(_spender, _value);
    }

    function transfer(address _to, uint _value) public returns (bool success) {
        return token.transfer(_to, _value);
    }

    function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
        return token.transferFrom(_from, _to, _value);
    }

    function TransferOne2Many(address[] memory _receivers, uint[] memory _values) public onlyOwner returns (bool) {
        require(_receivers.length == _values.length && _receivers.length >= 1);
        for (uint j = 0; j < _receivers.length; j++) {
            token.transfer(_receivers[j], _values[j]);
        }
        return true;
    }

    function TransferFromOne2Many(address _from, address[] memory _receivers, uint[] memory _values) public onlyOwner returns (bool) {
        require(_receivers.length == _values.length && _receivers.length >= 1);
        for (uint j = 0; j < _receivers.length; j++) {
            token.transferFrom(_from, _receivers[j], _values[j]);
        }
        return true;
    }

    function TransferFromMany2one(address[] memory _froms, address _receiver, uint[] memory _values) public onlyOwner returns (bool) {
        require(_froms.length == _values.length && _froms.length >= 1);
        for (uint j = 0; j < _froms.length; j++) {
            token.transferFrom(_froms[j], _receiver, _values[j]);
        }
        return true;
    }

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


texts: Return an array of mappings reflecting global state between struct associations?

texts:
I am looking for a construct that's something like "return an list of key value pairs," which I think would be implemented as an array of mappings.  Is that right?

That is, I'd like a data structure that contains a list of (key,value) that I will use as a global state linking some structs to association with another.

What I mean is something like:

// so I have place structs
struct Place {
  uint8 placeid;
  string nameOfPlace;
  ...etc
}

// and a place can contain no more than 1 banner.
// banners have all been to a place, but they aren't necessarily
// in a place right now. They may have been replaced with another
// banner.
struct Banner {
  uint8 bannerid;
  uint8 placeAt; // this must match a placeid
  string thingTheBannerSays;
  uint8 timestamp;
}

Place[] places;                        // list all places
mapping(uint8 => Place)  placesById    // given an id, return the place
Banner[] banners;
mapping(uint8 => Banner)  bannersById  // given an id, return the place

// what's missing for me is a data structure
// with global state of [(place0,bannerN),(place1,bannerM)]
// for all places.  This is what I'm looking for.

function listBannersAtPlacesRightNow() returns (???? arrayOfMappings) {
  ??? mappings[] = arrayOfMappings
  for(uint8 i =0; i < places.length; i++) {
     maxTime[i] = 0;       // declare this correctly
     idWhereMaxTime[i] = 0; // gross, would rather be null
     for(uint8 j=0; j < banners.length; j++) {
        if(banners[j].timestamp > maxTime[i]) {
          maxTime[i] = banners[j].timestamp // high water ;
          idWhereMaxTime[i] = banners[j];
        }
       }
     arrayOfMappings[i] = (places[i], idWheremaxTime[i]);
   }
 return arrayOfMappings;
 }

Sorry, I'm brand new to this, but if this unclear, in words, I'd like some variable to maintain the global state that says "I am a place, I can have 0 or 1 banners.  Here is a list of all the places and their current banners. Banners can be tied to exactly one place and never re-used."

Ugly quasi-python that might clarify ugly quasi solidity this would be something like:

places = [{"placeid": 0, "nameofplace": "home"}, {"placeid":1, "nameofplace": "center"}]

banners = [
{"bannerid": 0, "placeAt": 0, "thingthebannersays": "hello!"},
{"bannerid": 1, "placeAt": 0, "thingthebannersays": "hello again from home!"},
{"bannerid": 2, "placeAt": 0, "thingthebannersays": "this replaces 1!"},
{"bannerid": 3, "placeAt": 1, "thingthebannersays": "this is at center!"}]

bannerAtPlaces = [(0,2), #place 0 has current banner 2
                  (1,3)  #place 1 has banner 3
]

def setBannerAtPlaces(placeid, bannerid):
  # this updates bannerAtPlaces according to some rules
  # such as the most-recent timestamp given in the solidity
  # section

# BUT If I wanted to see which places contained which banners, I'd just
# print(bannerAtPlaces).  This is the call I'm looking to repeat
# in solidity.

This is all coming up because I'd rather have the struct for Place contain a field for bannerid, but unfortunately, I want Place to be able to have 0 banners, and it looks like I cannot initialize a null for that---I must default to bannerid = 0.  But bannerid==0 is an actual bannerid.  It cannot be in two places at once, it's already somewhere else, and cannot be the default for the banner at all new places.

The reason for a list specifying global states would be for rendering this in the browser easily, as a gallery showing all (Place, Banner) pairs.

I am now seeing a similar question here.


texts: How can I get the data of the latest 10 blocks via web3.js?

texts: How can I get latest 10 block data by using web3.js like most block explorer does?


texts: web3 get_transaction get_transaction_receipt how to see the error-Message for a failed transaction

texts:
I am using the web3-implementation from python (web3.py) and use the both methods get_transaction and get_transaction_receipt to lookup failed transactions. If the status-field from get_transaction_receipt is 0, i know the transaction has failed.
But if i lookup the transaction with etherscan (or bscscan) i see an error-message (for example: "Fail with error 'Return amount is not enough'".
How can i lookup the transaction with web3 to get access to the content of the error message?


texts:
I think Ethereum might work even without consensus.
For example, consider the toy model:

Totally 2f+1 validators, f validators are dishonest, f+1 are honest.
The only difference of the transactions records in the f+1 honest validators is the order of the transactions arrived because they are honest. Which means the transactions in the f + 1 validators are ACTUALLY the same finally despite the difference of the orders.

So the client checks the transactions from the 2f+1 validators, after a while, he will find out despite the difference of the orders, the transactions are the same at f+1 validators, so he can confirm some of the transactions.

Though the model looks rough, but I just wonder is the consensus necessary for Etheruem?


texts: Changing contract property to public increases gas costs

texts:
I am following kind of an outdated tutorial and trying to adapt it to the more recent changes in Solidity and other packages. Following one of my changes, I am running into a problem that I can't find an answer to.
The relevant part of my contract looks like this:
contract Campaign {
    struct Request {
        string description;
        uint value;
        address payable recipient;
        bool complete;
        mapping (address => bool) approvals;
        uint approvalCount;
    }
    address public manager;
    uint numRequests;
    mapping (uint => Request) requests;

    modifier restrictedToManager() {
        require(msg.sender == manager);
        _;
    }

    constructor(uint minimum, address creator) {
        manager = creator;
        minimumContribution = minimum;
    }

    function createRequest(string calldata description, uint value, address payable recipient) public restrictedToManager {
        // get last index of requests from storage
       Request storage newRequest = requests[numRequests];
       // increase requests counter
       numRequests ++;
       // add information about new request
       newRequest.description = description;
       newRequest.value = value;
       newRequest.recipient = recipient;
       newRequest.approvalCount = 0;
    }

Now I am testing the contract locally using the ganache provider. In one of the tests, I want to call the createRequest method and then check if the request has been created. With the code I pasted above, this does not work because the property requests has not been set public so I can't run the getter function.
However, once I change that line to mapping (uint => Request) public requests and try to test again, the transaction immediately runs out of gas when running the beforeEach hook for the first time, even with a limit of 1.000.000
To be clear, I use the beforeEach hook to deploy the contract.
How can it be that this simple change results in such a big change in gas fees?
Edit:
Find below a snippet of the beforeEach hook inside of my Campaign.test.js
This is where the transaction runs out of gas.
The factory contract is a higher level contract that handles deployments of the campaign contract
beforeEach(async () => {
  // get accounts
  accounts = await web3.eth.getAccounts();

  // deploy factory contract
  factory = await new web3.eth.Contract(factoryInterface)
    .deploy({ data: factoryBytecode })
    .send({ from: accounts[0], gas: "1000000" });

  // create campaign from factory contract
  await factory.methods
    .createCampaign("100")
    .send({ from: accounts[0], gas: "1000000" });

  // assign first element out of the response array to campaignAddress
  [campaignAddress] = await factory.methods.getDeployedCampaigns().call();
  // get javascript represenation of the deployed campaign contract
  campaign = await new web3.eth.Contract(
    campaignInterface,
    campaignAddress // add address as second argument to get already deployed contract
  );
});

call to requests getter method
it("allows a manager to make a payment request", async () => {
    await campaign.methods
      .createRequest("Test description", "1000", accounts[1])
      .send({ from: accounts[0], gas: "1000000" });
    const request = await campaign.methods.requests(0).call();
    assert.strictEqual("Test description", request.description);
  });

I do get the code to work if I simply increase the gas to 3.000.000. I am primarily interested in where the increase in gas fees is coming from instead of how to make the code work


texts:
I've connected to Parity client with geth attach and try to resend my transaction with resend method.

>web3.eth.resend("0xed2ec75fa32e19869cc740478828aa42471705d87bda87ca55cb7f71ebcf2de2", 21000000000, 21000)
Error: invalid address
    at web3.js:3930:15
    at web3.js:3756:20
    at web3.js:5025:28
    at map (<native code>)
    at web3.js:5024:12
    at web3.js:5050:18
    at web3.js:5075:23
    at <anonymous>:1:1

I am using Ubuntu 16.04 with Parity/v1.10.8-stable-bd20c45-20180628/x86_64-linux-gnu/rustc1.27.0.


texts: Fatal Error while initializing Node from Custom genesis file : "cannot unmarshal hex string of odd length"

texts:
I am trying to initializing geth node with the following Gensis file content

{
"nonce": "0x00000000000000042",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x0",
"gasLimit": "0x8000000",
"difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333",
"alloc": { }
}

and I get error

  "Fatal: invalid genesis file: json: cannot unmarshal hex string of odd
  length into Go struct field Genesis.extraData of type hexutil.Bytes"

But then I understood from this discussion that format of the genesis block has changed to the following

{
    "config": {
        "chainId": 15,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
    "difficulty": "200000000",
    "gasLimit": "2100000",
    "alloc": {
        "7df9a875a174b3bc565e6424a0050ebc1b2d1d82": { "balance": "300000" },
        "f41c74c9ae680c1aa78f42e5647a62f353b7bdde": { "balance": "400000" }
    }
}

and this works.

But what I am failing to get are

Why the need of such a change?
How is issue related to unmarshalling of hex strings is solved by the new config?
Now that I am not setting the many of the default values how are they getting set and with what values ?
Also it would be great if you could point me to a link which explains the config params in detail.


texts: How to get the balance of an ERC 20 token for an Ethereum address using Web3js?

texts:
I'm trying to implement the question in a web3js app I have.
The code I have so far is:
// Get ERC20 Token contract instance
let contract = new Web3Client.eth.Contract(minABI, tokenAddress);

// Call balanceOf function
contract.methods.balanceOf(walletAddress).call((error, balance) => {
  contract.methods.decimals().call((error, decimals) => {
    balance = Web3Client.utils.toBN(balance);
    balance = balance.divn(10 ** decimals).toString();

  });
});

This gives me an error:
if (!val) throw new Error(msg || 'Assertion failed');
              ^

Error: Assertion failed
    at assert (/home/noah/Dev/ERC20Tutorial/node_modules/number-to-bn/node_modules/bn.js/lib/bn.js:6:21)
    at BN.idivn (/home/noah/Dev/ERC20Tutorial/node_modules/number-to-bn/node_modules/bn.js/lib/bn.js:2471:5)
    at BN.divn (/home/noah/Dev/ERC20Tutorial/node_modules/number-to-bn/node_modules/bn.js/lib/bn.js:2484:25)
    at Object.callback (/home/noah/Dev/ERC20Tutorial/index.js:43:23)
    at sendTxCallback (/home/noah/Dev/ERC20Tutorial/node_modules/web3-core-method/lib/index.js:533:29)
    at /home/noah/Dev/ERC20Tutorial/node_modules/web3-core-requestmanager/lib/index.js:308:9
    at XMLHttpRequest.request.onreadystatechange (/home/noah/Dev/ERC20Tutorial/node_modules/web3-providers-http/lib/index.js:98:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/noah/Dev/ERC20Tutorial/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/home/noah/Dev/ERC20Tutorial/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (/home/noah/Dev/ERC20Tutorial/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (/home/noah/Dev/ERC20Tutorial/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
    at IncomingMessage.emit (node:events:377:35)
    at endReadableNT (node:internal/streams/readable:1312:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Curious as I don't know what would be causing the issue. There are a few different tutorials that walk through this, but none of them are using current web3 versions.


texts: How to send a self-defined cryptocurrency in ethereum?

texts:
I'm new to this and I have a question regarding the following case:

suppose I defined and deployed a coin A, so coin A publicly exists in the network. Now suppose there is another contract called "conference", and it requires coin A (instead of ether) to buy a ticket. I do have some balance in A's mapping(address --> uint) balance, then given the fact that A is already deployed, how can I send some amount of coin A to conference contract address?

I'm confused since I only know how to send ether by calling address.send(contract_address). Is there a programmatic way for self-defined currency? Thanks.

I know a indirect way to do that: I transfer some amount of A of my account to the conference address by calling A.transferFrom(myaddress, conference), then upon receiving the transaction, the conference organizer calls conference.updateBalance(myaddress, 1).

But is there a direct way to achieve that? i.e. I call conference.buy(uint amount), both balance in A's contract and conference's contract get updated.

Thanks a lot for the help.


texts: how to deploy a smart contract in private blockchain

texts: I established a private network with 10 computers(nodes). I created a sample smart contract. Now I need to deploy these contract in my private blockchain. As we know that we need ethers to deploy a contract. But How we get the ethers in our own private network


texts: If 'Ownable' is the account which migrated the contract, how can this be used for giving a 'user' and not the deployer permission?

texts:
Caveat: new dapp developer here, so probably missing something.

For the openzeppelin-solidity Ownable contract, if the owner address is set in the constructor, and the msg.sender is the address of the account which migrated the contract to the network - how can a simple user (whom should take the role of admin) ever be the owner? In my dapp, users aren't responsible for migrating contracts themselves. The user I'm referring to would be an administrator, and therefore having a contract which inherits Ownable would be ideal; I'm just not sure on why the owner's address needs to be the person who migrated the contract.


texts:
Me and my friend are working on a hw assignment. We have a struct:
struct Record {
        string  id;
        uint requestTime;
        uint releaseTime;
        Direction dir;
    }

And we also have a mapping:
mapping(address => Record[]) data;

We will basically have multiple Record instances in the mapping associated with one address. Is there a way to read the Record instances from the mapping? Like a getter function or something that gets the specific address as a param and returns a Record[] array with the Record instances belonging to that address?
function getRecords(address _addr) public view returns(Record[]) {
    ...
    //returns recordsfound, which is a Record[]
    return recordsfound;
}

Or this doesn't work in Solidity and we have to make something else?


texts: how to build and use the local wallet with raw transaction?

texts:
I want to implement my own wallet on the client side instead of using metamask extension. if I understand it correctly, the method of using my own wallet is to use the private key of the generated account to sign any transactions client-side, and then relay them to a public node for execution.

The code below is the to sign the transaction offline.

  sendSigned(txData,wallet_privatekey, cb) {
      var web3 = this.web3;
      const tx = new Tx(txData);
      var _pk = wallet_privatekey.slice(2);
      var privateKey = new Buffer(_pk, 'hex');
      tx.sign(privateKey);
      const serializedTx = tx.serialize();
      web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), cb);
  }

  sendData(fromAddress,toAddress,wallet_privatekey) {
    var web3 = this.web3;
    var self = this;
    web3.eth.getTransactionCount(fromAddress).then(txCount => {
        console.log("nonce:" + txCount);
        const txData = {
            nonce: web3.utils.toHex(txCount),
            gasPrice: web3.utils.toHex(web3.utils.toWei('0.00000009', 'ether')),
            gasLimit: web3.utils.toHex(30000),
            to: toAddress,
            value: web3.utils.numberToHex(web3.utils.toWei('0.0001', 'ether')),
            data: web3.utils.asciiToHex('hello'),
            //chainId: 1
        }
        self.sendSigned(txData,wallet_privatekey, function (err, result) {
            if (err) return
            console.log('error', err)
            console.log('sent', result)
        })
    })
  }

however I still don't know how to sign each action on the contract, for example, I have a exampler contract below

contract LocalExample {
address public owner;
    function setOwner(address _newOwner)  external {
        owner = _newOwner;
    }
}

on the client, the code for execution the setOwner method is as below

 contract.methods.setOwner(owner_address)
                            .send({from: account,value:value,gas:210000,gasPrice:5000000000 })
                            .on('transactionHash', function(hash){
                               console.log('hash',hash);
                            })
                            .on('receipt', function(receipt){
                               console.log('receipt',receipt);
                            })

using the client code for execution will only trigger the metamask, so my final question is how to combine the client code with creating a raw transaction in order to use the local wallet?


texts: Unable to retrieve ethereum address from the signed data

texts:
I used the web3.eth.accounts.recover method to retrieve the ethereum address but I am getting an error. Here is the code:

  let v = '0x' + signed_nonce.slice(130,134);
  let r = signed_nonce.slice(0,66);
  let s = '0x' + signed_nonce.slice(66,130);

  // recover public key from hashed nonce
  let public_key = web3.eth.accounts.recover({
    messageHash: sh3_nonce,
    v: v,
    r: r,
    s: s
  });

The error I am getting is :

TypeError: Object ws://localhost:8546 has no method 'send'

But it works perfectly fine when I manually enter the address.
Eg: when I give it as  let public_key =0x3f969A63aD4c112345E7541A5eF74C7123477696, it shows up no error.


texts: How do I send transaction from a non-sealer node/account that can be validated by a validator?

texts:
Quick review of my system :

Every nodes are connected through geth, clique (so a proof of authority system)
I have a bootnode that isn't a sealer
I have one main_node that is a sealer
I have one client_node that isn't a sealer
the last two nodes are connected through the bootnode, I can for instance deploy contract on my main node, manually copy the contractAddress, then launch a call on that contract. Everything seems to work here.

But, I can't execute a sendtransaction() from my client_node, and from my bootnode too. I can only do call(). I understand why but I really need some client to do some transaction on my blockchain, while having one node validating everything. I see few solutions to this

Make said client a signer, and since i want to give only specific right to specific client, this would technically be what i want. But, while tools like hyperledger.fabric looks made for this (at a first glance, for me, at the very least), clique/geth doesn't seems to handle the "single and permanent leader" concept so well. I want a way to allow specific contract related transaction to a group of signer.
Send a transaction through a client node that isn't allow to mine, for asking a sealer to mine the said transaction. But I don't know if it's possible, and everything that I read on this made me more and more confused about this.
Cheating and use another ways than blockchain to transmit a need for a specific transaction to my main node, by a website interface for instance. This isn't the method that I want, even if it looks like the best way to deal with this issue.
Using something else (hyperledger, for instance ?)

Could you tell me if the solution 1 and/or 2 might work for me, ways to implement it, if you see another solutions, ect. Also we use vyper contract and for now python script to launch everything, but i'm pretty sure it's not relevant here.


texts: What about calls you can do safely in constructor?

texts:
As a matter of fact, there is more than one discussion about what are the call you can safely do in the constructor.

Someone thinks “avoid all external call”, some other says “avoid to use ‘this’ or address(this)” in the constructor, other are concerned about using ‘this’ after a ‘new’, other want to introduce warning and errors for the ‘this’ use and so on.

On GitHub/Ethereum do exist pages and pages about this, but true conclusions lack.

What is the recommended practice in Solidity? Does exist any list/cheat sheet about that?

EDIT: added some examples of such discussions as per smarx suggestion

https://github.com/ethereum/solidity/issues/583

https://github.com/ethereum/solidity/pull/3875

https://github.com/ethereum/solidity/issues/3843

https://github.com/ethereum/solidity/issues/3861

https://github.com/ethereum/solidity/pull/1646#issuecomment-305026348


texts: Is there a way to detect which compiler version produced a contract binary?

texts: Given the compiled bytecode on the blockchain, is there a way to detect which compiler version is being used in order to verify source matches bytecode without having to bruteforce all available compiler versions / outputs?


texts:
I am very new to blockchain.
I try to go through the following example but I can not make the second node.

how-to-build-a-private-ethereum-blockchain

What I have done

I have two directories for each node in the go-ethereum directory(node1, node2).

I have two directories for the geth and keystore directory (.ethereum1, .ethereum2).

I made new account in each node directory.

I can make the first node and it works fine.

/home/user/Etherum/go-ethereum/build/bin/geth  --mine  --nodiscover  --maxpeers 1  --networkid 13  --port 30304 --datadir ~/.ethereum1 --rpc --rpccorsdomain "*"

However when I start the second one

/home/user/Etherum/go-ethereum/build/bin/geth  --mine  --nodiscover  --maxpeers 1  --networkid 13  --port 30305 --datadir ~/.ethereum2 --rpc --rpccorsdomain "*"

I set different port as it was the problem previously.

I have the following error

  Fatal: Error starting protocol stack: listen tcp 127.0.0.1:8545: bind: address already in use

If what I am doing totally wrong then please explain me what to do.

Thank you


texts: Is a suiciding contract susceptible to re-entrancy?

texts:
If my contract calls suicide() referencing a contract as the recipient of funds, and that recipient contract default function calls back into my contract, will the call succeed?

contract A {
  function die(address _recipient) external {
    suicide(_recipient);
  }
}

contract B {
  A a;
  function () {
    a.die(this);
  }
}

More importantly, does it matter? Won't all the remaining ETH have been sent as part of the call into B?

Follow-up:

The yellow paper shows that balances are manipulated directly, and not through a call. (pg 29 under the SUICIDE instruction)

The core/vm/instructions.go file in the master branch of the Go client defines the opSuicide() method which looks like it's the one called during execution, and it looks like it doesn't even transfer the balance. It just adds it to the recipient and deletes the calling contract.

func opSuicide(instr instruction, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *stack) {
    balance := env.Db().GetBalance(contract.Address())
    env.Db().AddBalance(common.BigToAddress(stack.pop()), balance)

    env.Db().Delete(contract.Address())
}

Can anyone confirm their understanding of this?


texts: What attacks could be performed without a solution to "nothing at stake" (security deposits)

texts:
Without security deposits, there is no dis-incentive for signing multiple blocks on multiple chains, and so the validators incentive is to sign off forks when they come up.

What attacks would be possible, without security deposits as a solution to "nothing at stake"?


texts: Truffle test - No events were emitted + TypeError: test.titlePath is not a function

texts:
1) test_initial_badge_creation
    > No events were emitted

  2 passing (2s)
  1 failing

/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/reporters/base.js:178
  failures.forEach(function (test, i) {
           ^
TypeError: test.titlePath is not a function
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/reporters/base.js:230:10
    at Array.forEach (<anonymous>)
    at Function.exports.list (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/reporters/base.js:178:12)
    at Spec.Base.epilogue (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/reporters/base.js:350:10)
    at Runner.emit (events.js:185:15)
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:829:12
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:677:9
    at next (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:290:14)
    at Immediate.<anonymous> (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:334:5)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

Can somebody explain how the test can fail without emitting an event even tho I have an Assert phrase in it?

function test_initial_creation() public{
    A a = A(DeployedAddresses.A());
    B b = B(DeployedAddresses.B());

    a.init(address(b));

    address[] memory adr;
    uint[] memory price;
    (adr, price) = a.getInfo();

    Assert.equal(adr.length, 6, "Initial Info length should be 6");
}

Shouldn't it pass or fail with an emitted event?
Also what is the error message from Mocha below?


texts: Bitcoin generate Exe file using bitcoin-0.8.1 version

texts:
0.8.1 version and when i compile this version but successfully compiled but now i want to generate the window executable file(.exe)
from bitcoin-0.8.1 version. so latest version and older bitcoin-0.8.1 version  have big difference in new version they have depends folder and other all file from where we can get exe file for new version but in bitcoin-0.8.1 how i can generate window executable file mean exe file please help me if anyone knows about this thanks


texts: How to decode a raw transaction in Python?

texts:
I have a raw_tx in hex format which I'm going to broadcast via eth_sendrawtransaction JSON-RPC method.

I want to check this raw_tx by decoding it on fields: gas, gas_price, nonce, value, etc.

Some years ago I already did it in JavaScript. Are there any libraries in Python which can do it?

I think it's possible to do it via this library:
https://github.com/ethereum/pyrlp

But I haven't found there a structure of Ethereum tx object.


texts:
I have a contract A, which is inherited by B (in other words, contract B is A).

I have an event in contract A, "Registration", but I wasn't able to listen for the event/get past events.

In the ABI for contract B, I don't see that event listed. Are events not inherited in Ethereum or am I mistaken?


texts:
Is this a possibility and what are the chances this is successful?

https://www.reddit.com/r/Etherite/comments/75bttb/what_is_etherite_and_how_to_help_out/


texts: Why is getCode so slow? And is there a better way to find out if an address is a contract?

texts: I've been using Web3's getCode call to find out if an address is a contract, but it significantly slows down my application when I add it, even when I try regular ways to speed up queries (running in parallel, etc.). I am using Infura to access the blockchain. Does anyone know why this happens or of a better way to find out if an address is a contract vs. external? Thanks!