texts: i want to make the etherum wallet using web3.js

texts:
i synced all etherum node in my localhost and i am connecting my node through this command

geth --rpc --rpcaddr "127.0.0.1" --rpcport "8545" \ --rpc --rpccorsdomain "http://127.0.0.1:8545" console

and then i am attaching thought this command from node.js cmd

geth attach http://127.0.0.1:8545

then i download web3.js and make one html page for testing so before i create account through (geth account new ) from node.js cmd and when and after that i am using some script for checking my create account that is i create thought node.js cmd using (geth account new ) its show perfectly and now i want to create new etherum account using

var Accounts = require('web3-eth-accounts');

// Passing in the eth or web3 package is necessary to allow retrieving chainId, gasPrice and nonce automatically
// for accounts.signTransaction().
var accounts = new Accounts('ws://localhost:8546');

so its showing me error that is

  web3-eth-accounts is not found

but you give me solution for this using this command(npm install web3-eth-accounts ) so its successfully install but when i run this (npm run-script build-all) so its not working my my node.js cmd and tell me where i had to run this command in project ? ..

and i am aslo facing this issue

npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

audited 118883 packages in 29.686s
found 1766 vulnerabilities (1 low, 1765 moderate)
  run `npm audit fix` to fix them, or `npm audit` for details


texts: Is there a way to perform a rollback of transactions in a contract that happened many days ago?

texts: For the DAO, the only way to rollback was to perform a hard fork.  Has there been any attempts to program code, so that if enough token holders agree, a contract can be rolled back after N+ days, without needing to resort to a hard fork of the entire network.  I'm trying to conceptually think about idiosyncratic solution to rollbacks for specific contracts.


texts: Is it possible to verify Ethash PoW in a contract?

texts:
Reading on EtHash, I was thinking if it is possible to verify the current Ethereum Proof Of Work by a smart contract. There is an instruction SHA3, which computes 256-bit hash, but EtHash uses 512-bit hash. Was this discrepancy intentional or just an oversight? Is it possible to compute one from another somehow?

I know that verifying PoW in the contract might be expensive, but it could be used just as a response to a challenge.


texts: Can I use other tokens in loom network (sidechains)? How does loom network handles it?

texts:
How to receive other tokens in the smart contract deployed in loom and keep it in escrow?, this is the code.

    pragma solidity ^0.5.0;

    //import ERC20 functionality ...

    contract  Example {

        ERC20   public token;

        //@param _token the address of the DAI smart contract
        constructor(ERC20 _token) public {
            token = ERC20(_token);
        }

        function () external payable {}

        function getBalance() public view returns (uint256) {
            return token.balanceOf(address(this));
        }

        function withdraw() public {
            token.transfer(msg.sender, getBalance());
        }
    }

Logic in Ethereum is one can keep the money in the smart contract address, and release it when conditions are met.
Can I use this code directly in the loom network, or there needs to be any configuration done in the transfer gateway? How will the smart contract in loom network handle it if the transfer gateway is not involved.
https://loomx.io/developers/en/extdev-transfer-gateway.html


texts: Geth Console - Sleep after mining a block?

texts:
I am running a local testnet with a low mining difficulty to test my contracts, and I am conscious that when I start another mining geth instance the total computation will hog my CPU.

My question is - is there a way of making the geth miner sleep for a specified period of time before mining the next block?

I could just have one node mining transactions, but I would like to emulate the real network more closely.

I am sure there are other solutions to testnet mining that I am not aware of, and they are also welcomed.


texts: Is it possible to create a UX where you can just press a button and get your Metamask wallet refilled from a faucet ( for example for rinkeby testnet). Currently the process is very cumbersome where you have to copy wallet address, then paste in faucet window, then do some social auth and then your wallet gets funded. Any suggestions in how to make this UX better?


texts: How msg.sender address gets generated in smartcontract?

texts:
msg.sender (address): the sender of the message (current call).
Considering a scenario where a user uses a smart contract and try to perform a transaction. For that particular user msg.sender is the address of that user.
Does this address ever change for that specific user?
On what basis address is given to the caller? How its generated?


texts:
I don't understand how the following test can pass. I tried it in my application and it fails.

The entry point is the description 'when called by the owner'.

In this function two test cases are run. Before each test case the token with tokenId is transferred to the address stored in this.to. After transferring the token approval is deleted.

The test case transfers the ownership of the given token ID to the given address because it tests the new owner of the contract.

The second test 'clears the approval for the token ID'will alway fail because the transferFunction in the beforeEach function is called again but the token doesn't belong to owneranymore.

I'm wondering if the test framework is supposed to behave differently and should delete the state before running a test case. This is not happening with my setup (ganache-cli@6.1.0, Truffle v4.1.11 (core: 4.1.11, Solidity v0.4.24 (solc-js), Mocha 2.5.3 )

beforeEach(async function () {
  this.to = accounts[1];
  await this.token.approve(approved, tokenId, { from: owner });
  await this.token.setApprovalForAll(operator, true, { from: owner });
});

const transferWasSuccessful = function ({ owner, tokenId, approved }) {
  it('transfers the ownership of the given token ID to the given address', async function () {
    const newOwner = await this.token.ownerOf(tokenId);
    newOwner.should.be.equal(this.to);
  });

  it('clears the approval for the token ID', async function () {
    const approvedAccount = await this.token.getApproved(tokenId);
    approvedAccount.should.be.equal(ZERO_ADDRESS);
  });
...
}

const shouldTransferTokensByUsers = function (transferFunction) {
  describe('when called by the owner', function () {
    beforeEach(async function () {
      ({ logs } = await transferFunction.call(this, owner, this.to, tokenId, { from: owner }));
    });
    transferWasSuccessful({ owner, tokenId, approved });
  });


texts: Why contract's function that is deploy inside Solidity browser does not deployed inside geth?

texts:
I have my private Ethereum Network.

Inside Solidity Browser:

From Web3 Provider I have connected to my local ethereum node.
I have pressed create button and successfully deployed my contract.
Now I could call any function inside my contract and all deployed without having any problem.

As an example: I have deployed insertfront(string val) transaction inside Solidity Browser (To get mined takes around a minute). Gas costs is 203893.

Inside Geth:

Connect into private ethereum network.
Obtain address and abi (located inside the interface box) from the Solidity Browser that will point the deployed contract.

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

mycontract
{
...
  insertfront: function(),
  allEvents: function(),
  construct: function(),
  delete_: function(),
  delete_items: function(),
  deleteback: function(),
  deletefront: function(),
  get: function(),
  get_: function(),
  get_map: function(),
...
}

mycontract.deletefront( {from: eth.accounts[0]} ) //This works inside geth and function does what it has to do. Transaction mines and deploys. deletefront() function's gas usage is 41920.
But when I call insertfront(string val) function inside geth (please not that transaction has costed 203893 gas inside Solidity Browser), it never deploys or mines in my blockchain (I have waited hours but no help).

> mycontract.insertfront("some_string", {from: eth.accounts[0]} )
"0x7048278dcdb02c02894082af541c73ad6a8e0e37cf1ab90ac914c58cc2d2f983"

//But it has no affect and did not done the what function has to do.

[Q] Why function that is deploy inside Solidity browser does not deployed inside geth? Could it be because usage of high gas amount for a function?

Thank you for your valuable time and help.


texts: Cannot mine at synced block with Ethereum Wallet

texts:
I have trouble with mining with Ethereum wallet.

It has own geth, and I have blockchain synchronized. Ethereum wallet is running, same as its geth.

However, ethminer is throwing

  "JSON-RPC problem. Probably couldn't connect. Retrying in 1..."

which, according to this topic ( https://www.cryptocompare.com/mining/guides/how-to-mine-ethereum/ ) means, that blockchain is actually not synchronized.

Also, I have my MyEtherWallet connected to Ethereum wallet via its json, if it has some role in this issue.

So please, any tips, how to get miner connected?

Thanks :)


texts: Correct way to build an automatic refunding system for auctions

texts:
I want to build an auctions contract and I'm very aware of the push-pull pattern for auctions or sending Ether but beyond that I wanted to explore if there was a way where I could send back the money, or whatever is being sent to the user, automatically. What I'm trying to solve with this is that if I want to run multiple auctions at a time and the same user bids on all of them it can be very tedious for them to claim back all their bids manually, I've been trying to study what OpenSea does but I've not had much success there.

I wanted to use a token (DAI or WEI) but I'm not sure if they are subject to the same risks as sending Eth automatically through a loop or something.

So, what are my options here or what's a popular approach these pages that run auctions take for users to make bids and whatnot?


texts: When calling ERC-20 token transfer() method nothing happens

texts:
I'm currently using version 1.2.9 and Using Infura Rinkeby as Provider. So basically I'm building a node application with Inbuilt wallet. Now I have successfully Created an Account and Used that account to Send ETH transactions to other wallets by Sign Transactions and Send Transactions. Now When I have to send Contract Methods in a transaction my code thinks im sending ETH to that address my code is:
var contractAddress = account.asset[req.body.assetType].tokenAddress; var user_addressTo = req.body.toAccount;

var amountSent = req.body.valusent; const myContract = new web3.eth.Contract(ABI,contractAddress);

const result =   {
from: account.address,
to:user_addressTo,
value:0x00,
gasPrice: web3.utils.toHex(web3.utils.toWei(gasPrice, 'gwei')),
gas:req.body.gasLimit,
data:myContract.methods.transfer(user_addressTo,amountSent).encodeABI()
};

var signPromise  =  await web3.eth.accounts.signTransaction(result,key);
var z = await web3.eth.sendSignedTransaction(signPromise.rawTransaction);

I have checked multiple times the values im sending In. Each Value works just fine Now the Response I get from Blockchain is

blockNumber: 7645527,
contractAddress: null,
cumulativeGasUsed: 494263,
from: '0xe6f2332b8758148de0e7739177544d28a4225807',
gasUsed: 21620,
logs: [],
logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x3dea86e3170ab1e93ff033cee4ae07bb19c75ab7',
transactionHash: '0xca08aa4560de4bae21bceaa36ed2b8c23f218ca05cf7d9adad1845ac8b817dcc',
transactionIndex: 2

I have followed a lot of tutorials and answers from different platforms but each gives out this result. Can you guys help me?


texts: ABI artifacts corrupted, manually edit ABI?

texts:
Is it possible to manually add functions to the ABI, specifically the getProduct and addProductToStore functions? Does it make a difference?
Have already tried deleting build + recompiling + remigrating, same issue. Believe it to be an problem with Truffle's build process corrupting the artifacts?

Similar to this issue: https://github.com/trufflesuite/truffle/issues/685

Remix :

[
    {
        "constant": true,
        "inputs": [],
        "name": "productIndex",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "name": "_productId",
                "type": "uint256"
            }
        ],
        "name": "getProduct",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "uint256"
            },
            {
                "name": "",
                "type": "uint256"
            },
            {
                "name": "",
                "type": "uint256"
            },
            {
                "name": "",
                "type": "uint8"
            },
            {
                "name": "",
                "type": "uint8"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "_name",
                "type": "string"
            },
            {
                "name": "_category",
                "type": "string"
            },
            {
                "name": "_imageLink",
                "type": "string"
            },
            {
                "name": "_descLink",
                "type": "string"
            },
            {
                "name": "_auctionStartTime",
                "type": "uint256"
            },
            {
                "name": "_auctionEndTime",
                "type": "uint256"
            },
            {
                "name": "_startPrice",
                "type": "uint256"
            },
            {
                "name": "_productCondition",
                "type": "uint256"
            }
        ],
        "name": "addProductToStore",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    }
]

Local Json file:

"abi": [
    {
      "constant": true,
      "inputs": [],
      "name": "productIndex",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "constructor"
    }
  ]


texts: Can I Specify gas fees in the smart contract?

texts:
Deploying my contract on rinkeby cost ~12 USD in gas fees (using truffle cli). Is it possible for me to specify gas fees/set a limit in the smart contract so it costs me 0.5 USD, but takes longer to deploy ?
Thank you.


texts: CORS issue with infura.io on safari and mobile browsers

texts:
Connecting to infura.io is working fine when using chrome on desktop, however when using safari I get CORS issues. Also the mobile versions of the page don't even load on the device. The following messages appear in the console.

Failed to load resource: Origin http://website.com is not allowed by Access-Control-Allow-Origin.
Fetch API cannot load https://ropsten.infura.io/[ID]/. Origin http://website.com is not allowed by Access-Control-Allow-Origin.

I am using Amazon s3 so I tried to change the CORS configuration settings to something like this, but still no effect.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://*</AllowedOrigin>
    <AllowedOrigin>https://*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
    <AllowedHeader>x-requested-with</AllowedHeader>
    <AllowedHeader>origin</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Is this a common issue with infura.io? Is there anything else that I am missing?


texts: How is The Graph a decentralised solution?

texts:
I understand that querying for data on Ethereum is a pain in the neck and that The Graph indexes events so that developers can more easily get their most precious blockchain data.

However, I'm not sure I follow why The Graph can be described as decentralised (as they claim). It seems they abstract the process of retrieving data stored on a server by putting GraphQL in between.

Could someone explain?


texts:
I'm looking for a complete list of Remix IDE shortcuts. (Little things make a big difference, and I'm a big fan of efficiency). Through trial and error, here's what I found so far:

Opt+Up/Down: Move line up/down
CMD+D: Delete line
CTR+OPT+Up/Down: Multicursor (super useful)

I would love to be able to CMD+D to highlight word like in Sublime. I've tried searching for Remix IDE shortcuts, searched the doc, but found nothing...
Anybody have their own list or know of a source? Thanks!


texts: Can someone help me. I was looking to see whats taking so long from coinbase to my wallet and I found this on redit. So how do i track my transaction from my wallet from coinbase to my other wallet? Thank you


texts:
I've seen that geth can be used to create a wallet address by doing

geth account new

Where is the wallet stored?

How can I backup this wallet in case I lose my computer?

What is the difference between geth and mist?

Where does mist store my wallet and how can I prevent myself from losing it as well?

Can I make transactions with any of them?


texts:
Is it possible for a smart contract to autonomously execute (with no external interaction) when a certain condition is met? Say, when a certain time arrives.

My thought is that smart contracts are only executed when interacted with by an external account. Am I correct?


texts:
Can someone explain me the Dogethereum project?

I mean, is it a token managed by a smart contract (through a bridge) or is it a full independent blockchain whose code is based on that of Ethereum, so that it is a platform for the developing of its own decentralized apps with dogethereum as currency?


texts: Why do Solidity Browser non-constant functions return values?

texts:
When calling a state mutating function on the chain, the TX receipt object is returned.  In Solidity Browser, under the Javascript VM, a return value is returned if one is set.

Why does the Javascript VM behave in this confusing way?

For example, the following contract contains a state mutation function which returns a value.

contract foo {

    uint public bar;

    function set(uint newbar) public returns (bool)
    {
        bar = newbar;
        return true;
    }
}

In the Javascript VM, the value is shown as returned...

This is contrary to the behaviour of an on chain contract which returns the TX recipt.  IOW returns have no purpose in a state mutating function (or am I missing something really fundamental?)

The Javascript VM's return behaviour can lead to a false sense of functionality by which an author (like me, who should have known better) then writes contracts depending upon such return values but which have absoutly no functionality on chain...

Another example that works in VM but breaks on chain is when trying to interact with a 'new' contract...

contract foo {
    uint public number = 42;
    function set(uint num)
    {
        number = num;
    }
}

contract fooFactory {
    foo public kungFoo;
    function newFoo()
    {
        kungFoo = new foo();
        kungFoo.set(1); // This call will throw on chain yet works in VM
    }
}


texts: How to get the balance of a contract using web3.js?

texts:
I have deployed a contract as follows and determined its balance to be 5000 wei (value: 5000):

const thisContract = new web3.eth.Contract(abi);
thisContract.deploy({
    data: bytecode,
    arguments: [ "0x84f0c8fC2F6bc8394EB77BaAAe89cB6e12C048C2", 86400]
}).send({
    from: "0x3455D7167A2EE2d660EE85F8e90C6b3B1cCB7163",
    gas: 5000000 ,
    gasPrice: '3000000000',
    value: 5000 // here I have determined the balance.
}, function(error, transactionHash) {
    console.log(error);
    console.log(transactionHash);
    console.log('function exec');
}).then(function(newContractInstance) {
    console.log('Contract Instance:' + newContractInstance.options.address);
});

I have deployed this contract on Tobalaba blockchain (its github is here.)

The balance of the address by which I developed this contract is 20000000000000000000 wei as follows :

> web3.eth.getBalance('0x3455D7167A2EE2d660EE85F8e90C6b3B1cCB7163').then(console.log)
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> 20000000000000000000

However, when I get the balance of the contract, it's 0 as follows:

> web3.eth.getBalance('0xd227398f81bad20882b46ccdffc71058025df341').then(console.log)
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> 0

And here is the information of deployment of this contract:

https://tobalaba.etherscan.com/address/0xd227398f81bad20882b46ccdffc71058025df341

Acoording to which the contract address is 0xD227398f81bAD20882B46ccdFfC71058025df341

Is something wrong?

IMPORTANT NOTE: I have developed this contract: https://programtheblockchain.com/posts/2018/02/23/writing-a-simple-payment-channel/

Meanwhile, when I get the contract address it returns null!

> thisContract.options.address
null

Whereas, regarding to this information (https://tobalaba.etherscan.com/tx/0xb9834bd2ebbbb930208dbb17462169441c6b63542a01a43e3992ecf803cb0734) it have to be deployed, isn't it ? (Please see the screen shot bellow)


texts: Any decentralized exchanger to convert between btc and eth？

texts: Any way to convert on different chains？That means we can convert between btc and eth on different chain.


texts: Did I risk my Geth account using the following websites?

texts:
At first I didn't know how to check for account balance using the Geth console, so I put my account address to the following websites:

ethermine.org, etherchain.org, etherscan.io

Did I do a risky thing by giving my account address to them? Or to someone else in general?  (And I thus should create a new account and transfer the Ether there?)


texts:
Is there anything that is equivalent of Hyperledger Fabric's Membership Service Provider in Ethereum?

  The power of an MSP goes beyond simply listing who is a network participant or member of a channel. An MSP can identify specific roles an actor might play either within the scope of the organization the MSP represents (e.g., admins, or as members of a sub-organization group), and sets the basis for defining access privileges in the context of a network and channel (e.g., channel admins, readers, writers).

EDIT: My question is wrt a private Ethereum blockchain, not the public Ethereum network


texts: Contract can't be mined in ropsten network

texts:
I have a node running from geth --testnet --rpc --rpcapi "eth,web3,personal" --rpcport=8545 --rpccorsdomain "*" .

The contract is

pragma solidity ^0.4.15;
contract SimpleMultiSig {

  uint public nonce;                // (only) mutable state
  uint public threshold;            // immutable state
  mapping (address => bool) isOwner; // immutable state
  address[] public ownersArr;        // immutable state

  function SimpleMultiSig(uint threshold_, address[] owners_) {
    require(owners_.length <= 10 && threshold_ <= owners_.length && threshold_ != 0);

    address lastAdd = address(0);
    for (uint i=0; i<owners_.length; i++) {
      require(owners_[i] > lastAdd);
      isOwner[owners_[i]] = true;
      lastAdd = owners_[i];
    }
    ownersArr = owners_;
    threshold = threshold_;
  }

  // Note that address recovered from signatures must be strictly increasing
  function execute(uint8[] sigV, bytes32[] sigR, bytes32[] sigS, address destination, uint value, bytes data) {
    require(sigR.length == threshold);
    require(sigR.length == sigS.length && sigR.length == sigV.length);

    // Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
    bytes32 txHash = keccak256(byte(0x19), byte(0), this, destination, value, data, nonce);

    address lastAdd = address(0); // cannot have address(0) as an owner
    for (uint i = 0; i < threshold; i++) {
        address recovered = ecrecover(txHash, sigV[i], sigR[i], sigS[i]);
        require(recovered > lastAdd && isOwner[recovered]);
        lastAdd = recovered;
    }

    // If we make it here all signatures are accounted for
    nonce = nonce + 1;
    require(destination.call.value(value)(data));
  }

  function () payable {}
}

Deploy code is

const fs = require("fs");
const Web3 = require('web3');
const solc = require('solc')

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

let account = web3.personal.unlockAccount(web3.eth.accounts[0], 'password');
let source = fs.readFileSync('SimpleMultiSig.sol', 'utf8');
let compiledContract = solc.compile(source, 1);
let abi = compiledContract.contracts[':SimpleMultiSig'].interface;
console.log('Abi: ', abi);

let bytecode = compiledContract.contracts[':SimpleMultiSig'].bytecode;
let gasEstimate = web3.eth.estimateGas({data: '0x'+bytecode});
let contract = web3.eth.contract(JSON.parse(abi));
console.log('gasEstimate', gasEstimate)

const addresses = [
  "0xa90a595e286a992b575b9f2858a6725bc176c3f6",
  "0x1a2eec7053a246c6ed8a75cf0f47fbed2bd7b211",
  "0x03852aadab1794dbd472ae9ac772e79801d3bc3b",
  "0x2349e11f56413ac91cc05a46341e4ea7992bedd3"
]
contract.new(2, addresses,  {from:web3.eth.accounts[0], data:'0x'+bytecode, value:0, gas:gasEstimate}, (err, myContract) => {
  if(!err) {
     if(!myContract.address) {
         console.log("Hash: ", myContract.transactionHash);
     } else {
         console.log("Address: ", myContract.address);
     }
  }
  else {
    console.log(err);
  }
});

Here is the strange thing:

When I run node deploy.js , it throw an error 'Error: exceeds block gas limit'. So I try to subtract the gasEstimate to gasEstimate-5000, then run deploy.js again, but the new error is Error: The contract code couldn't be stored, please check your gas amount. The transaction id is 0x4cb91d82c110a6bd198aa97691ae9844938a7dc7c8629468b39b704a688acbc1. You can check it out on etherscan.io

Is there something wrong with my contract or deploy code?


texts: How to convert signed integer to string?

texts:
I want to convert a signed integer to string.

Is the only way to use uint2str() and then use a string library function, e.g., strings, concat() to concat the sign “-“?. Or is there more efficient way?


texts: How my node is sync with highest block number of block-chain in which block number transaction have done of some ether?

texts:
I am new to Ethereum block-chain.One question in my mind. I connect geth node to test network with "--fast and --cache=2048" parameters.So my node is sync is after 8 hours.And I successfully deploy smart contract on test network(rinkeby). But one question in my mind.

How does my node sync with the highest block number??
What is the format the time is displayed when I request for the sync status in Geth??

It might be a silly question but here i want to understand this concept more deeply.

Please help to clear my above query.

Thanks


texts:
While going through solidity documentation I came across a term 'the owning contract' which i didnt understand.

  A contract in the sense of Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. The line uint storedData; declares a state variable called storedData of type uint (unsigned integer of 256 bits). You can think of it as a single slot in a database that can be queried and altered by calling functions of the code that manages the database. In the case of Ethereum, this is always the owning contract. And in this case, the functions set and get can be used to modify or retrieve the value of the variable.


texts: Could not deploy contract through sendTransaction

texts:
I am trying to deploy contract (available at Etherscan.io ). I proceed following steps:
copy its contract creation code and save them in crCode variable. Then i tried to to run following code;

 async function deployWithCreationCode(){

    var myTrx = await web3.eth.sendTransaction({
      from: account1,
      data: crCode
  });
  console.log(myTrx)
}

Here is my output.

UnhandledPromiseRejectionWarning: Error: Returned error: base fee exceeds gas limit

How to resolve it ?


texts: Is there a comparison of Ethereum smart contracts to other platforms that also have smart contracts?

texts: Doing some research in the smart contracts arena. But is there an in depth comparisons with the pros/cons of each implementation of smart contracts in other blockchains as compared to Ethereum smart contracts? What are the strength and weaknesses of each?


texts: How to pass numbers greater than 9007199254740991 to contracts?

texts:
When I try to call function check() with a number greater than 9007199254740991 I get an error:

  Error encoding arguments: Error: Assertion failed

contract C {
     function rateCheck(uint rate){
          if(rate % 10 finney != 0 || rate == 0){
             throw;
          }
     }
}

Question:
What's the best workaround?


texts: How to deploy kyber network proxy locally and test with truffle?

texts:
I am trying to deploy a proxy from Kyber Network for local development. So far I have pulled down the workshop repo and I have successfully deployed all the contracts successfully. I have the following contract:
import "./Investor.sol";
import "./IKyberNetworkProxy.sol";

contract Trader is Investor {

    uint256 public platformFeeBps;

    constructor(
        IKyberNetworkProxy _kyberProxy,
        uint256  _platformFeeBps
    ) public
    {
        kyberProxy = _kyberProxy;
        platformFeeBps = _platformFeeBps;
    }

    function getConversionRates(
        IERC20 srcToken,
        IERC20 destToken,
        uint256 srcQty
    ) public
      view
      returns (uint256)
    {
      return kyberProxy.getExpectedRateAfterFee(srcToken, destToken, srcQty, platformFeeBps, '');
    }

}

And it is being deployed in this migration:

const Trader = artifacts.require("Trader");
const NetworkProxy = artifacts.require('IKyberNetworkProxy');
const PLATFORM_FEE = 25;
module.exports = async function(deployer, network)  {

  const kyberNetWorkProxyAddress = network == 'ropsten' ? '0x818E6FECD516Ecc3849DAf6845e3EC868087B755' : '0xf7b8C85953aF2524CcEC98066FCebAF8db27De02';

  const proxy = await NetworkProxy.at(kyberNetWorkProxyAddress);
  deployer.deploy(Trader, proxy, PLATFORM_FEE);
};

Running
truffle migrate --network development
will execute successfully but the trouble seems to be when I am running truffle test tests/Trader.js
This is my Trader test file:

/* libraries used */

const truffleAssert = require('truffle-assertions');
const vals = require('./lib/testValuesCommon.js');

/* Contracts in this test */

const Trader = artifacts.require("../contracts/Trader.sol");
const KyberProxy = artifacts.require("../contracts/IkyberNetworkProxy.sol");

/* Useful aliases */

const toBN = web3.utils.toBN;

contract("Trader", (accounts) => {
  const TRADER_ID = 1;

  const OVERFLOW_NUMBER = toBN(2, 10).pow(toBN(256, 10)).sub(toBN(1, 10));

  const TraderStatus = {OPEN: 0,  PAUSED: 1, CLOSED: 2};

  const oneEth = web3.utils.toWei('1', 'ether');

  const ETH_ADDRESS = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
  const KNC_ADDRESS = '0xdd974d5c2e2928dea5f71b9825b8b646686bd200';
  const WBTC_ADDRESS = '0xdd974d5c2e2928dea5f71b9825b8b646686bd200';

  const PLATFORM_FEE = 25;

  const owner = accounts[0];
  const trader = accounts[1];
  const investorA = accounts[2];
  const investorB = accounts[3];

  let instance;
  let proxy;

  before(async () => {
    proxy = await KyberProxy.at('0xf7b8C85953aF2524CcEC98066FCebAF8db27De02');
    instance = await Trader.new(proxy, PLATFORM_FEE);
  });

  describe('#getConversionRates()', () => {

    it('should allow the contract owner to add a trader and increment the totalTraders',
       async () => {

        const conversion = await proxy.getConversionRates(ETH_ADDRESS, KNC_ADDRESS, oneEth, PLATFORM_FEE, '', { from: owner });
        console.log(conversion);
       });
  });
});

Running the tests will throw this error: (the object in value being the ABI for IKyberNetwrokProxy.sol)
Contract: Trader
       "before each" hook: before test in "Contract: Trader":
     Uncaught RuntimeError: abort(Error: while migrating Trader: invalid address (arg="_kyberProxy", coderType="address", value="[object Object]")). Build with -s ASSERTIONS=1 for more info.

I think my lack of understanding on proxy addresses and how they are used is causing my struggle but if anyone could shed some light on this I would very much appreciate it.
THanks,
J


texts: How to recognize failed transaction in a block?

texts:
I am trying to decode transactions from a block, and I noticed that failed transactions are included in a block.
Is there any specific information within failed transaction data or within block that contains this failed transaction, that can tell me that this transaction is failed?
Or maybe that information is stored in one of next blocks?


texts: Assembly operations throw warnings during compiling

texts:
Leveraging the following common string utility has been quite helpful, but would like to get rid of a warning:

function stringToBytes32(string memory source) returns (bytes32 result) {
      assembly {
          result := mload(add(source, 32))
      }
      return result;
  }

 But upon updating the compiler to 0.4.11, I see warnings during compilation, indicating the variable, "source"

Unused local variable

Anu suggestions on whether this is due to a compiler update, or the usage of 'memory' keyword?


texts: Parsing String to Integer for very large numbers

texts:
I've been trying to find a way to pass integer as string using a few of the function provided by the community but , while it works for " small " numbers it doesn't for larger ones.

Does anybody knows why and what is the limit here ?

contract Test {

    function stringToUint(string s) constant returns (uint) {
    bytes memory b = bytes(s);
    uint result = 0;
    for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
        if (b[i] >= 48 && b[i] <= 57) {
            result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -.
        }
    }
    return result; // this was missing
    }

        // parseInt
    function parseInt(string _a)  returns (uint) {
        return parseInt(_a, 0);
    }

    // parseInt(parseFloat*10^_b)
    function parseInt(string _a, uint _b) internal returns (uint) {
        bytes memory bresult = bytes(_a);
        uint mint = 0;
        bool decimals = false;
        for (uint i=0; i<bresult.length; i++){
            if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
                if (decimals){
                   if (_b == 0) break;
                    else _b--;
                }
                mint *= 10;
                mint += uint(bresult[i]) - 48;
            } else if (bresult[i] == 46) decimals = true;
        }
        if (_b > 0) mint *= 10**_b;
        return mint;
    }

}

The first function stringToUint is from this SO ( How to convert string to int )
And the second one is from the OraclizeitAPI contract.

Both don't behave as i expect for this param :

"10000000000000000000000000000000000000000000000000000000000000000000000000000000001"

Will return :

79381376136047024986163664703589883750854290615248988403587492614211165487105

When i'm expecting

10000000000000000000000000000000000000000000000000000000000000000000000000000000001


texts: How does Parity pendingTransactionsStats works?

texts:
I am trying to develop little method to track status of my pending transactions by given address together with propagation info. But I am bit confused about pendingTransactionsStats behavior as it changes each time i check.

My code first check for pendingTransactions of my address then checks pendingTransactionsStats for hashes that retrieved from pendingTransactions.

var myAddr =  "0x2c5253b9055cfd3ac7a2d352934fb5c45f667367";
api.parity.pendingTransactions()
  .then((pendingTransactions)=>{

    // filter my transaction by my address
    let pendingQueue = _.filter(pendingTransactions, (a) =>  {return a.from.toLowerCase() == myAddr});
    if(pendingQueue.length > 0) {

      // get stats of my pending transactions
      api.parity.pendingTransactionsStats().then((pendingTransactionsStats)=>{
        for (var i = 0, l = pendingQueue.length; i < l; i++) {
          let pendingHash = pendingQueue[i].hash;
          console.log("pendingHash : " , pendingQueue[i].hash);
          console.log(pendingTransactionsStats[pendingHash]);
        }

      });
    } else {
      console.log("no pending transactions");
    }
  });

pendingTransactionsStats gives different propogation info each time i check. Sometimes doesnt even return anything. Is it expected behaviour? If yes, what should i understand from this. My aim is to be sure that my pending transaction is propagated to network. So i can be sure that reason of pending is not about network but only gasPrice.

My code outputs with few seconds inbetween :

pendingHash :  0x551e1af7c403c7fc847ecc2c4b8174e0853931f07fbc0eefd267a68fd87604e3
{ firstSeen: 3609956,
  propagatedTo:
   { '0xd1da0fa61e0f1b69918ad330e59a12eddd1450256dd6837764c1d587b1adb5cf8ef661c043588f61ec0603e73fc641f5855ef486990ce13021d019e7a3c15de7': 1 } }

After few seconds no stats found:

pendingHash :  0x551e1af7c403c7fc847ecc2c4b8174e0853931f07fbc0eefd267a68fd87604e3
undefined

Then some more seconds and there two nodes :

{ firstSeen: 3609957,
  propagatedTo:
   { '0x3b1dcc486de0b4b0cd2783b5fd770e183b0f063cd045b775e330aa8a3059ebff3d65131fa6f51761bef1152c54cfd9dd83b71aed38e9c1aaeb5660c8b73d5daa': 1,
     '0xf2170f44de933a592b6bac04f4926a81b7eae662abf888719e55a6556dd3dfbfa9ca36f314bc079d0ae2932fde27adee634363170d0316eb5a28e9baacca1868': 1 } }

One more question; what do those numbers indicate with peer Ids?


texts:
Is it possible to make a function only callable by owner but restricted to view?
I tried something like that.

function getUserTokenBalance(address user) public view onlyAdmin returns (uint256) {
    return balance[user];
}

Calling this method from web3 like:

contract.methods
 .getUserTokenBalance('0x06bf3b021f10712655a8786f2bFfF11ddE0ea21B')
 .call({ from: account.address })
 .then((data) => {
   console.log('balance: ', data);
 })
.catch((err) => {
  console.log('error', err);
});

returns some weird long number as string 3963877391197344453575983046348115674221700746820753546331534351508065746944

I guess it's not working because I have to send a transaction so the smart contract can verify me as the owner. However, what I want to achieve is to query some state in the smart contract without paying any fees.


texts: Warnings ICO contracts : set a now time or a future date-time

texts:
Time issue in Solidity ICO contract. Should I set time in future, 17.05.2018.10.00? and not use 'now' as I read it will not work.
Warning below.
use of "now": "now" does not mean current time. Now is an alias for block.timestamp.

Do I need to change gas, how much for a ICO contract?
Warning below.
Fallback function of contract nameToken requires too much gas (infinite). If the fallback function requires more than 2300 gas, the contract cannot receive Ether.
Warning how to make changes so the ICO contract will work.

Gas requirement of function nameToken.approveAndCall(address,uint256,bytes) high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)

Does this mean my token take can not be the same as contract name? why not?!
nameToken.balanceOf(address) : Variables have very similar names balances and balance. Note: Modifiers are currently not considered by this static analysis.

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


texts: What is the difference between testRPC and geth?

texts:
I wonder what is the difference between testRPC and geth (on private network) because, they both can create:

blockchains
nodes
accounts

The "only" difference I see, is that the testRPC has almost unlimited Ether, which makes the mining process unnecessary.

Maybe is there a link between geth and the testRPC? I mean applying some functions implented in geth could be applied on a testRPC network?

Thanks in advance,


texts: Frontend for OpenZeppelin ERC20 token and Crowdsale

texts: does anyone know if there are any resources online for a front-end app.js for a simple ERC20 token for a crowdsale? I am looking to build out a front end that will allow log-in with Metamask and buy function from a webpage.


texts: How is the Mining Difficulty calculated on Ethereum?

texts:
Having read various pieces of documentation, it's still not completely clear to me what dictates the difficulty rise, and how Ethereum difficulty levels differ to Bitcoin.

In the past week difficulty has jumped from around 11 to over 17, whilst GH/s has fluctuated between 800.00 - 1400.00 but with no clear correlation between the two.

Has the "difficulty bomb" now been introduced? And if yes, is there any way for approximating or calculating how much difficulty will likely rise by in the next 6-12 months?

Related: If Serenity / PoS is unlikely to be introduced until early next year, has there been any suggestion from the dev team that the effects of this "difficulty bomb" will be reduced in either the homestead or metropolis releases?


texts: Do I have to worry about signing transaction?

texts:
I'm using truffle & ganache to test a simple voting app.
Do I have to worry about security and transaction signing or is it managed for me ?


texts: Difference between "decoded input" and "input" in Remix?

texts:
What is the difference between "decoded input" and "input" in the remix output? If these functions were to be called in an actual blockchain, would the "decoded input" be saved in a block, and thus visible to all? For example, in the attached figure, are the 0x01 and 0x04 values saved in a transaction. 'submitRange' is a public function. For context, I am wanting to keep this information private.

Thank you in advance!


texts: How can I make new account by JSON-RPC of Go

texts:
I'd like to make new account by JSON-RPC.I've checked the wiki of Ethereum, however I could not find out how to do that.

I've found call existed accounts, but it isn't what I want.
eth_accounts

Could you tell me how to do this?


texts: eth_sendTransaction gas required exceeds allowance

texts:
$result = $client->callMethod('eth_sendTransaction', [array(
                    "from" => $address->address,
                    "to" => "0xac52822dde76b9c4cd701d5f4402acedb2a86cc1",
                    "value" => "0x" . strval(dechex($amount)),
                    "gasPrice" => "0x" . strval(dechex($gasPrice))
                )]);

Hi, when I call the function above I get this result:

{ ["jsonrpc"]=> string(3) "2.0" ["id"]=> int(1) ["error"]=> array(2) { ["code"]=> int(-32000) ["message"]=> string(70) "gas required exceeds allowance (9958635) or always failing transaction" } }

Could you please help me what is wrong? I've tried to increase gasLimit, but got the same result. Also I'm running geth light node if it helps.

Thanks for your help.


texts: Store encrypted data on-chain VS on cloud

texts: So, I am currently doing research for a project and an interesting question was born. If I have data that I want to store encrypted, why to choose blockchain instead of a cloud provider? Since the data is encrypted, wherever I decide to store it, it should be the same in term of privacy and security, right? Because, even in the case of the cloud provider, nobody can decrypt my data except for me. Any ideas?


texts: I tried to create an account by using ethereumj client, It said it created it but I could not see the keystore file. Can ethereumj generate the keystore file just like go client?


texts:
I'm firing up a test network like so:

geth --networkid=43766 --datadir ~/.ethereum/authchaintestnet/ --unlock b40474571297fd05ac82fd2994f45c977f3ca77a --password ~/.ethereum/authchaintestnet/passwordfile --mine --rpcaddr 127.0.0.1 --rpcapi eth,net,web3,personal --verbosity=4 --nodiscover

... but Geth keeps trying to connect to a bunch of peers that have nothing to do with my network. Why is Geth ignoring the nodiscover flag?


texts: Miner crashes at Invalid header on mined block

texts:
Please Help !
I have a geth client running a private chain, everytime I do miner.start() it starts processing any previously committed transactions then it prints the following then crashes completely. It doesn't process any more transaction when I send/receive any ether.

INFO [04-05|17:10:44]  mined potential block                  number=23 hash=077500…801662
INFO [04-05|17:10:44] Commit new mining work                   number=24 txs=0 uncles=0 elapsed=140.185µs
INFO [04-05|17:10:45] Successfully sealed new block            number=24 hash=b7d1ba…11081e
INFO [04-05|17:10:45]  block reached canonical chain          number=19 hash=c42dc1…94d958
INFO [04-05|17:10:45]  mined potential block                  number=24 hash=b7d1ba…11081e
INFO [04-05|17:10:45] Commit new mining work                   number=25 txs=0 uncles=0 elapsed=132.192µs
INFO [04-05|17:10:46] Successfully sealed new block            number=25 hash=be9ac2…c5861c
INFO [04-05|17:10:46]  block reached canonical chain          number=20 hash=7e9132…28bf08
INFO [04-05|17:10:46]  mined potential block                  number=25 hash=be9ac2…c5861c
INFO [04-05|17:10:46] Commit new mining work                   number=26 txs=0 uncles=0 elapsed=164.022µs
INFO [04-05|17:10:47] Successfully sealed new block            number=26 hash=e6b517…6e284e
INFO [04-05|17:10:47]  block reached canonical chain          number=21 hash=4e3a79…0164b9
INFO [04-05|17:10:47]  mined potential block                  number=26 hash=e6b517…6e284e
INFO [04-05|17:10:47] Commit new mining work                   number=27 txs=0 uncles=0 elapsed=158.024µs
INFO [04-05|17:10:47] Successfully sealed new block            number=27 hash=0254f9…5abbf9
ERROR[04-05|17:10:47] Invalid header on mined block            err="block in the future"

I'm running the following version of GETH

Geth
Version: 1.6.0-unstable
Git Commit: cc303017c3f145441e583b5bb10ee3070b44cc50
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.8
OS: linux


texts: Contract not disbursing MetaCoin to parent account

texts:
I've combined MetaCoin and created an Ownable contract to allow for my Relay contract have access to MetaCoin methods and variables. Everything is successfully deployed using truffle. My assumption is that Relay (thereby the default account in web3.eth.accounts) should have access to methods and variables from MetaCoin. Below is the contract:

pragma solidity ^0.4.4;
import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract Ownable {
  address public owner;

  function Ownable() {
    owner = msg.sender;
  }

   modifier onlyOwner() {
    if (msg.sender != owner) {
      throw;
    }
    _;
  }

  function transferOwnership(address newOwner) onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
    }
  }

}

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

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

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

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

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

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

contract Relay is MetaCoin {
address public owner;
uint public count;
address[] oracles;
uint public fee;

  function Relay() {
    owner = msg.sender;
    count = 0;
    fee = 10;
  }

  function fundRelay() payable returns (bool) {
    if (owner != msg.sender) throw;

  }

function approveExternalTransaction() {
  count++;
  if (count == 3) {
    releaseFunds();
  }
}
  function releaseFunds () {

      sendCoin(owner, fee);

  }
}

I am acting as a manual oracle and I call approveExternalTransaction() 3 times, on the third time sendCoin() should be called. It currently is not being called. sendCoin() is not called when I manually call the method either.

I'm running this all successfully using truffle and I expect the pre-funded contract to release the funds to the owner (account 0 in web3.eth.accounts), but nothing is happening.

One hint is that when I call Relay.at(relay).balance() I get the error Relay.at(...).balance is not a function. Does being Ownable not inherit the balance variable declarations as well? Or is this an issue with either truffle or the way I've constructed my contracts?

Thank you for any help.

UPDATE -- Found this guide https://dappsforbeginners.wordpress.com/tutorials/interactions-between-contracts/

Changed these functions -

function approveExternalTransaction(address coinContractAddress) {
    count++;
    if (count == 3) {
      releaseFunds(coinContractAddress);
    }
  }

  function sendCoin(address coinContractAddress, address receiver, uint amount) {
        MetaCoin m = MetaCoin(coinContractAddress);
      if(m.getBalance(msg.sender) >= amount) {
        balances[msg.sender] += amount;
        balances[owner] -= amount;
      m.sendCoin(owner, fee);
    }
  }

function releaseFunds (address coinContractAddress) {
    sendCoin(coinContractAddress, owner, fee);
 }

}

The issue now is when I set address = MetaCoin.deployed().then(function(instance) { return instance.address; }) and then call Relay.at(relay).approveExternalTransaction(address) I am getting the following error:

BigNumber Error: new BigNumber() not a number: [object Object]

Any idea why this might be happening?


texts: Transfer money between accounts in solidity

texts:
I am writing a contract where I want to transfer money (present in the contract owners account and not the contract) to an account address passed to a function in the contract.

for some reason this code won't work

function payBill(uint value, address account) payable public {
account.transfer(value);
transactionCount += 1;
transactionAmount += value;

}


texts:
Does anyone know if is there any open source code mobile wallet (Android or IOS) that i can use to store and transfer my custom ERC20 token.

I would like to be able to modify it in order to allow it to store only my custom token, i mean, lets say i create xyzToken (ERC20) so i would like to have XYZapp, where i can handle my balance and transfer the token to other users.


texts: Does Gas Price Affect TX minng priority [ROPSTEN]

texts: Since ether, on the ropsten network, virtually isn't worth anything does the gas price for transactions affect the priority in which they're mined? I'm asking because web3.eth.getGasPrice() (on the ropsten network) seems to always returns a fixed price of 1 GWEI. Also when testing with different gas prices i can't say I've noticed a differences that i, undoubtedly, can say were caused by the gas price.


texts: How much memory do I need to mine any blocks on my lockal network?

texts:
I have linux box with 5Gb of memory:

osboxes@osboxes ~/node1 $ free
              total        used        free      shared  buff/cache   available
Mem:        5176876      158360     3536464      226748     1482052     4751712

This is my genesis.json:

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

This is how I initialize it:

geth --datadir . init genesis.json

And i open console

geth --datadir . console

Then I start miner and get this crash:

ERROR[07-10|15:56:35] Failed to generate mapped ethash dataset epoch=1 err="cannot allocate memory"
runtime: out of memory: cannot allocate 2164260864-byte block (128057344 in use)
fatal error: out of memory

How much memory would be enough?


texts: What is auxdata in the asm output from solc?

texts:
I am using -

solc --asm smartcontractname.sol

I get at the end of the asm auxdata. I am trying to check different modules to see what is inherited. Does anyone know how auxdata is computed? Here is an example -

  auxdata:
  0xa165627a7a72305820b41b74dd955b6016ed7df922d97394e291c6cebecd0289470726ff64204a7a790029

I assume this is a hash of the asm or something like that. My purpose is to determine what code specifically is passed into modules.


texts: I have the stupidest question. I have the source code of a smart-contract written in solidity. In Remix, it compiles normally, in the BSC test network, transactions pass. And actually, what to do next? Where to upload the source code so that the smart contract already appears in the BSC network?


texts: Infura Web Sockets doesn't work on Infura

texts:
I have a problem with connecting via Websockets to Infura. I am listening on some events from my smart contract, so when some event is dispatched by calling some method from smart contract, I should catch that event and do some stuff inside callback. Actually this seems to work locally(localhost), so I am connecting to Infura via Websockets without problem and everything works fine.

The problem occurs when a backend is deployed on aws instance. So the WebSocket connection to that AWS instance cannot be done and the most strangest thing is that I don't get any errors. Here is the code:

const web3Socket = new Web3(new Web3.providers.WebsocketProvider("wss://ropsten.infura.io/ws"));
...
...
...
let instance = await new web3Socket.eth.Contract(contractAbi, address);
 instance.events.transactionEvent({
        fromBlock: "latest"
    }, (error, event) => { console.log(event); })
        .on('data', async (event) => {
            // do some stuff
        })
        .on('changed', function(event){
            console.log('CHANGED');
            console.log(event);
            // remove event from local database
        })
        .on('error', console.error);
...
...
...

So actually .on('error', console.error); is not throwing any error for example connection lost or connection refused. Any tips/suggestions on what to try next or what can cause the issue?


texts: How can one apply and work for the Ethereum Foundation?

texts: I would like to know how one can apply and work for the Ethereum Foundation as a software developer. I tried to look online but could not find the answer.


texts: Cannot restore Electrum wallet from seedphrase

texts:
Please be gentle as I'm new here (and n00b in blockchain world).
I created an Ethereum wallet a few years ago and was under the impression that I would be able to restore my wallet on a new PC using only my passphrase.
I've downloaded Electrum now and selected "I already have a seed passphrase" and seemingly "restored my wallet". However I cannot see my ethers in any of the addresses in the wallet.
Am I misinterpreting some of the concepts? Am I missing some important step?
Any guidance would be more than kindly appreciated!


texts:
How can I have a local copy of the binance chain for use in ganache like to use BNB as default coin instead ETH?
I see here Ganache -f how can I fork the whole chain? that I must provide -f parameter but I don't know exactly how.
By the way... I need a CLI flavor because I'm using Ubuntu server.


texts: How to concatenate uint to address in solidity?

texts: I would like to concatenate an Ethereum address to an uint in Solidity. How can I do that?


texts: Minimal working example of ethereum dapp

texts:
There are examples about how to develep dapp based on ethereum. They work.

However, they are not minimal, in the sense that readers need to learned things that may be left without. For example, in the follow URL, a framework like truffle is used. I think that people may develop a dapp without using truffle or other frameworks. Also, the problem on this URL is about wrestling. However, seems to be also unnecessary, maybe other more simpler problems can be solved (For example, could adding two numbers be developed on a dapp?).

https://hackernoon.com/ethereum-development-walkthrough-part-1-smart-contracts-b3979e6e573e

The following example is not "working", as it requires the user understand it before it can be used. It should just work without the learning have to understand what the code means. It is better that all the code should be in a github repo and the instructions for running the code.

https://programtheblockchain.com/posts/2017/12/13/building-decentralized-apps-with-ethereum-and-javascript/

Does anybody have any minimal working example of ethereum dapp?

I'd like the example be to run the dapp on an test network hosted by ganache to avoid having to purchase ETHs.


texts:
Realise this is a long shot but giving it a go anyway: I had a situation quite recently where my wallet security was compromised and I suddenly had to move all of my crypto out of it quite quickly. In my haste I confused a contract address for my personal wallets address when sending a token across. I realise that these are 99.999% lost forever, but as I understand it from reading similar posts here, there may be the possibility that a function has been written into the contracts code to allow the transfer of tokens.
This is the contract where the tokens are stuck https://etherscan.io/address/0x9f599410d207f3d2828a8712e5e543ac2e040382
Please could anyone here have a look at the code to see whether such a function exists?
Much appreciate any help


texts: Hashrate of R9 280X is extremely low. Why?

texts:
I have an ASUS R9 280X graphics card running with Windows 10, 16 GB of RAM and an Intel i7 6700 processor.

Why is my hashrate at 7.5 Mh/s?

I did expect a hashrate of arround 20 Mh/s. Will the installation of ethOS rise my hashrate? Or should I install another driver?

Thank you for your answers!


texts:
I know this issue was discussed before several times, but I cant get the solution to my problem from any of the answers,

My contract got deployed fine before adding the following function,

function setApproval(address addr, bool approved)payable returns(string, uint, uint) {

       //some logical operations and assignments

    }

as soon as I add the function and try to deploy the contract,
I got this error

  Error encountered, bailing. Network state unknown. Review successful
  transactions manually. Error: The contract code couldn't be stored,
  please check your gas amount.

test rpc server shows following logs

  Transaction:
  0xd5791ac0c6059cbd43e00a7fabe566ada3f0572966f12ff25da6e04215840f39
  Contract created: 0x9062592c5dd06340401c1e750ddb025defabf5be Gas
  usage: 4712388 Block Number: 16 Block Time: Sat Jul 22 2017 03:30:30
  GMT+0530 (India Standard Time) Runtime Error: out of gas

again after removing this function contract deployed without errors

what is wrong with this function?

My contract code is around 250 lines, is there any limit on contract code size??

Thanks in advance


texts: How to transfer tokens between smart contracts?

texts:
I am trying to understand exactly how can I transfer ERC20 tokens between contracts.

In my case, these contracts are basically the same and they are different versions of the same contract. To put it in a scenario: let's imagine I have released a smart new token based on ERC20 and used it in an ICO. Then I found a bug in my contract that I solved in the dev environment.

The question is: How do I transfer the data stored in the first contract (deployed) to the second one (after deployment of the dev contract), when it comes to the tokens and the balances?


texts: Getting this message in mist: Couldn't estimate gas, resorting to default parameters. Transaction is likely cheaper than the estimate

texts:
What is this error message in red:

Couldn't estimate gas, resorting to default parameters.
Transaction is likely cheaper than the estimate

I have written a smart contract:

pragma solidity ^0.4.0;

contract MyFirstContract {
    uint256 counter =0;

    function increase() public {
        counter++;
    }

    function  decrease() public{
        counter--;
    }

    function getCounter() public constant  returns (uint256) {
        return counter;
    }
}

At the time of contact creation, it has estimated 77,829 gas and I set the maximum gas to 877,829.

When I execute a function on the contract, why do I get this error message in red?

Kindly guide me as I am a beginner in Ethereum.


texts: Do storage MPT branch nodes contain values?

texts:
when reading through the specs of Merkle-Patricia-Trees, I was wondering if branch nodes of storage tries ever contain values?
It is my understanding, that the last array element of a branch node contains a value in case the trie was fully traversed for a given key. This occurs when we happen to have keys of different length, I guess? For the storage trie, keys are first hashed to mitigate DoS attacks building long paths, so we always have fixed length keys.
Is my assumption correct that values in the storage trie are always stored in leaf nodes, because the key is of fixed length?


texts: Building Ethereum application with in-process client

texts:
Most applications connect to an Ethereum Node through RPC, using a library like Web3.js and Nethereum. That introduces a need to deploy a full node side-by-side with the application, be it on the server or the user's machine, and communicate through sockets through loop-back adaptor.

This practice seems surprising to me - obvious alternative is to package a client as part of my server application, and have them run in-process. Do Ethernet clients have an API to be used as a library and is considered appropriate and "good design"? I mean either running them as part of back-end or in full-fat desktop client.


texts: Any way to convert the characters that make up bytes into a string?

texts: For example if I have a bytes4 variable that is "0xabcd1122" is there any way to turn this into a string with a value of "abcd1122"? I am asking because I want to assign a unique identifier to a token symbol but when I convert bytes to a string the result does not fit utf-8 encoding making the output garbled. If converting the characters that make up the bytes variable into a string doesn't work, does anybody have any idea to generate a unique identifier as a string?


texts: Get a list of tokens inside an ethereum wallet address

texts: is there a way(mostly a api) to get all the tokens currently being held by a wallet address?(Their contract addresses)


texts: Geth.framework for iOS - failed to set up geth instance

texts:
I tried to use the Geth.framework in iOS to set up geth instance with RPC enabled. I followed the instruction posted on Ethereum github
https://github.com/ethereum/go-ethereum/wiki/Mobile%3A-Introduction, and Peter's (@karalabe) talk titled "Import Geth: Ethereum from Go and beyond".

But I received this compile error in geth instance setup
DispatchQueue.global(qos: .background).async {
     Geth.run("--ipcdisable --fast --rpc --rpccorsdomain *")
}
The error is: Module Geth has no member named run

The Geth version is the latest version 1.8.2

Any ideas what went wrong? thanks.


texts: How (or where) to see errors when something goes wrong using truffle exec ?

texts: I want to know how ( or where if logged somewhere) to find errors when running truffle exec . And this because i ran truffle command  and a dependency was missing (i forget a require) and i didn't see any errors.


texts: Do I need to include erc20 standared function in all smart contract?

texts: erc20 token standard functions are only important for creating new tokens, or for all, suppose a smart contract is only intended to transfer token, should it contain those standard erc20 functions or that is useless there ?


texts: Trouble loading parity wallet from mnemonic phrase

texts: When attempting to restore my parity wallet using the mnemonic phrase, a wallet that is different from the wallet i want to access is loaded. I can view my account and its balance of etherscan, but parity wont load it through the phrase. Can any one suggest anythign to help?


texts: Is there a data structure that contains all the JSON RPC endpoints? Not the wiki, but a JSON or SQL file that I can use to programatically iterate over all the endpoints to generate code.


texts: How truffle selects the address with which it deploys a smart contract with and where does it gets it's private keys?

texts:
I am reading truffle tutorials for deployment smart contract to gauche, I've never deployed any smart contract to real network.
Now when migrate (deploy) a smart contract I get these info:

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

   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x2d01568d6461be2557bb7b58c30fb0288e183ce090503a374caa635d1415b82e
   > Blocks: 0            Seconds: 0
   > contract address:    0xeCE6C3Df643eeaBeF14FB22Ec59025b3614337bb
   > account:             0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
   > balance:             99.98776428
   > gas used:            284844
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00569688 ETH

   Deploying 'Coin'
   ----------------
   > transaction hash:    0x7cf73aac0c7bc19cae31b170ab3987a51a7642029862abe62f03fe712a1d0437
   > Blocks: 0            Seconds: 0
   > contract address:    0x2FE15cC795B06e0369fBA40BE1E6004344f87818
   > account:             0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
   > balance:             99.97940696
   > gas used:            417866
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00835732 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.0140542 ETH

Summary
=======
> Total deployments:   2
> Final cost:          0.0140542 ETH

From the screenshot below it can be seen that the smart contract is deployed with the address 0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
how does truffle chooses this address, where it gets it's private key, and how to change this address if desired ?


texts: This contract does not implement all functions and thus cannot be created? I am very new to solidty . Any help highly appreciated

texts:
pragma solidity ^0.4.0;
contract contracta{
    uint mapsize=10;
    struct request_task{
    uint task_id;
    string ip_address;
    uint flag ;// submited, 1, excuteding, 2, finished, 3, failed
    uint task_submit_time; // 08:12:01 06/18/2018
    uint task_deadline; //  09:12:01 06/18/2018
    uint  provided_price; // maximum price: $10 per hour
    uint bandwidth; // minimum: 100.00 KBP
    }
    request_task[] private request;
    uint internal countera;
    function contracta() internal{
        add(1,"172.168.3.3",1,10,30,5,200);
        add(1,"172.168.3.3",1,10,30,5,200);

    }
    function add(uint _task_id,string _ip_address,uint _flag,uint _task_submit_time,uint _task_deadline,uint  _provided_price,uint _bandwidth) internal{
        request.push(request_task(_task_id,_ip_address,_flag, _task_submit_time,_task_deadline,_provided_price,_bandwidth));
    }
    function get()constant returns(uint){
        return request[1].task_submit_time;
    }

}


texts: Is there any project to calculate different hashes like md5, sha1 etc. in solidity?

texts:
I'm looking for solditiy-code to generate hashes of different hash-algorithms

MD5
SHA1
SHA512

and more. Is there any project which implemented hash-algorithms in solidity?

Is there someone out there who also needs this?


texts:
I have a problem when deploying smart contracts on remix.
When I click create, I can see that transactions are passing through, from the blockchain explorer. I clicked multiple times, and this is the result.

However, I am getting the below 'error' and the contract does not seem to be deploying. I have tried different contracts and changing browser, to no avail.

I am connecting to my node via web3 provider. I can see my wallets

I am adding a sample smart contract:

  contract test{

    int _multiplier;

    function test (int multiplier){
        _multiplier = multiplier;
    }

    function multiply (int val) returns (int d){
        return val * _multiplier;
    }

}

When deploying the smart contract, i can see it in geth.

then i get the error mentioned above in remix.


texts: Ethereum crowdsale example - Stuck tokens (how to save)

texts:
I deployed a crowdsale contract using the source from ethereum.org and loaded it with some tokens.  It works as expected, except that it has no code to return the unsold tokens to the beneficiary.

Is there any way to save these tokens?

Here is the contract source

pragma solidity ^0.4.16;

interface token {
    function transfer(address receiver, uint amount);
}

contract Crowdsale {
    address public beneficiary;
    uint public fundingGoal;
    uint public amountRaised;
    uint public deadline;
    uint public price;
    token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool fundingGoalReached = false;
    bool crowdsaleClosed = false;

    event GoalReached(address recipient, uint totalAmountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);

    /**
     * Constrctor function
     *
     * Setup the owner
     */
    function Crowdsale(
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        address addressOfTokenUsedAsReward
    ) {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken * 1 ether;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

    /**
     * Fallback function
     *
     * The function without name is the default function that is called whenever anyone sends funds to a contract
     */
    function () payable {
        require(!crowdsaleClosed);
        uint amount = msg.value;
        balanceOf[msg.sender] += amount;
        amountRaised += amount;
        tokenReward.transfer(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    modifier afterDeadline() { if (now >= deadline) _; }

    /**
     * Check if goal was reached
     *
     * Checks if the goal or time limit has been reached and ends the campaign
     */
    function checkGoalReached() afterDeadline {
        if (amountRaised >= fundingGoal){
            fundingGoalReached = true;
            GoalReached(beneficiary, amountRaised);
        }
        crowdsaleClosed = true;
    }

    /**
     * Withdraw the funds
     *
     * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
     * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
     * the amount they contributed.
     */
    function safeWithdrawal() afterDeadline {
        if (!fundingGoalReached) {
            uint amount = balanceOf[msg.sender];
            balanceOf[msg.sender] = 0;
            if (amount > 0) {
                if (msg.sender.send(amount)) {
                    FundTransfer(msg.sender, amount, false);
                } else {
                    balanceOf[msg.sender] = amount;
                }
            }
        }

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


texts: Where can I get list of tokens that allow direct conversion to ether and not just from token to token?

texts:
Most tokens simply utilize the ERC20 functions transferfrom/transferto which just use some balances to add from one user to another - but what are the ones who allow you to:

buy token
cashout to ether such as: withdraw (msg.sender.transfer (tokensbought);)

Can something like this be done with WETH somehow? (wrapped ether).

I am just looking for a way to get around pricey/scammy exchanges where withdrawal will cost money...not to mention lack of liquidity. Thanx


texts:
I have a trouble with comparing timestamp parameter(in test) and now in smart contract.

Here is my smart contract:

function create(uint created_at) public {
    require(now > created_at, "The created_at should be less than now .");
}

And test function:

it("...should store the created_at", async () => {
    const storageInstance = await Storage.deployed();
    let created_at = new Date().getTime();//create utc now timestamp
    await storageInstance.create(created_at);
 }

The test doesn't pass. Error:

  The created_at should be less than now .


texts: how does a smart pool identifies the valid block in ethereum

texts:
I have been reading this paper https://eprint.iacr.org/2017/019.pdf.

To my understanding, the miners send the shares in batches and later the smart pool verifies the shares with sampling with augmented merkel trees.
after the shares are verified, the shares are placed in verclaim sets.

Now what do i don't get is the smart pool needs to identify the valid block from  the shares and broadcast to the network. How does the smart pool find the valid block?? moreover doesnot the smartpool only have the augmented merkel root instead of whole the shares from all the miners??


texts: geth console mining - how to find when a contract is mined

texts:
I created a private blockchain console with an unlocked account.

I have a simple contract, simpleContract.sol

pragma solidity ^0.4.0;

contract SimpleStorage {
  uint storedData;

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

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

It was made into a js file using

echo "var simpleOutput=`solc --optimize --combined-json abi,bin,interface simpleContract.sol`" > simpleStorage.js

I load my contract in the console using

loadScript("simpleStorage.js")
var simpleStorageContract = eth.contract(JSON.parse(simpleOutput.contracts["simpleContract.sol:SimpleStorage"].abi));
var simpleStorage = simpleStorageContract.new(   {     from: eth.accounts[0],      data: "0x" + simpleOutput.contracts["simpleContract.sol:SimpleStorage"].bin,      gas: '47000'   },  function (e, contract) { if(!e) {    if(!contract.address) {      console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");    } else {      console.log("Contract mined! Address: " + contract.address);      console.log(contract);    }  }})

I see

  Contract transaction send: TransactionHash:
  0x0f01f04f0e266cdca62479413bf17d65d38ef0b497dcbe9e9232451c994892a0
  waiting to be mined...

When I start the miner with

miner.setEtherbase(eth.accounts[0])
miner.start(4)

It prints

  INFO [07-01|18:22:03] Updated mining threads    threads=4

  INFO [07-01|18:22:03] Transaction pool price threshold updated
  price=18000000000

  INFO [07-01|18:22:03] Starting mining operation

  INFO [07-01|18:22:03] Commit new mining work         number=3062 txs=0 uncles=0 elapsed=309.753µs

  INFO [07-01|18:22:06] Successfully sealed new block            number=1 hash=a73c27…d68bae

  INFO [07-01|18:22:06]  mined potential block                  number=2 hash=a73c27…d68bae

  INFO [07-01|18:22:06] Commit new mining work                   number=3 txs=0 uncles=0 elapsed=126.412µs

  INFO [07-01|18:22:08] Successfully sealed new block            number=4 hash=577497…34db4e

How can I find when my contract will be mined? I was under the impression that I could find the block number using

eth.getTransaction

Any solutions?


texts:
could anyone tell me about Ethereum's decision making. I am new about that.

for example

how the roadmap decided or who decide it
how make decision of softfork or hardfork
how appropriate code is committed and merged and who does it
is there any admin of nodes(like masternode)
how can we join as a core member who can be on Core Devs Meeting
is there any voting to ask to node for developing

I am currently researching about governance in crypto industry
thanks,


texts: fail transaction and prevent storing it on the chain

texts:
both require and assert generate an exception and mark the transaction as failed.

Is there a way to make the transaction not register on the network and hence not incur any cost?


texts: Ethereum is not transferred on Ropsten network

texts:
Here's my code for signing nd sending a transaction on Ropsten testnet which is working properly. However, the value that is set to '1' eth is not transferred to the target address.
var Tx = require('ethereumjs-tx').Transaction

const Web3 = require ('web3')
const web3 = new Web3('MY URL including the key')

//Public keys for two accounts
const account1 = '0x8dAd70D461d01C2945A0a1b358eDF21544E03d07'
const account2 = '0x2bA9D4119A2F5c80812d273F3720347dd529FD0A'

const prKey1 = Buffer.from(process.env.PR_KEY1.substring(2,66), 'hex')
const prKey2 = Buffer.from(process.env.PR_KEY2.substring(2,66), 'hex')

// *********************Transfer from account 1 to account 2 *******************
web3.eth.getTransactionCount(account1, (err, txCount) => {
// Build the transaction
    const txObject = {
    nonce: web3.utils.toHex(txCount),
    to: account2,
    Value: web3.utils.toHex(web3.utils.toWei('1', 'ether')),
    gasLimit: web3.utils.toHex(21000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('100' , 'gwei'))

    }

// Sign the transaction - choose ropsten as the network
    const tx = new Tx(txObject, {chain: 'ropsten'})
    tx.sign(prKey1)

    const serializedTransaction = tx.serialize()
    const raw = '0x' + serializedTransaction.toString('hex')

// Broadcast the transaction
    web3.eth.sendSignedTransaction(raw, (err, txHash) => {
        console.log('txHash:', txHash)
  })
})


texts: How can I wait if it's not possible in smart contracts?

texts:
From my understanding, waiting in a solidity smart contract would create a total disaster for the whole Ethereum's blockchain.

I can see in some circumstances that solidity offers block.timestamp and keywords such as "now + 1 day".

My specific scenario is the following:

A smart contract sends an ERC20 Token from 3 different addresses. However,
those tokens shall not be sent at the same time, but eventually wait between
1 minutes and 1 hour between each transaction.

Is that achievable using smart contracts?


texts: How can i refund 0.017eth from fail confirmed transaction (ropsten)

texts:
https://ropsten.etherscan.io/address/0xf0cc02d3fc8f53ecf90690757fafef646431996a
this example with out of gas. Create new transaction with nonce 5 not work, because tx is confirmed.
How can i return 0.017 eth from fail transaction


texts: Call a payable contract's function from another contract via an interface

texts:
I have two contracts, they are connected via an interface.

When user calls contract1 function, it uses an interface to call contract2 function which updates it's storage.

My problem is that I can get a return value from an event, but data is not saved in that contract2 storage.

I get such an error:

  Transaction was not mined within 50 blocks, please make sure your
  transaction was properly sent. Be aware that it might still be mined!

here is a contract1 function which that user calls i.e. buy():

event itemBought(uint256 itemId);

Contract2Interface private contract2Interface;

constructor() public {
    contract2Interface = Contract2Interface('contract address');
}

function buy(uint256 itemId) public payable {
      // require(some condition);

    uint256 itemId = contract2Interface.buy(itemId, msg.sender);
    emit itemBought(itemId);
}

here is an interface:

contract contract2Interface {
    function buy(uint256 itemId, address owner) public returns(uint256);
}

here is contract2 function:

mapping(bytes32 => uint256) private storage;

function encodeFunc(uint256 itemId, address owner) private pure returns(bytes32) {
    return keccak256(abi.encodePacked(itemId, owner));
}

function buy(uint256 itemId, address owner) public returns(uint256) {
    storage[encodeFunc(itemId, owner)]++;
    return itemId;
}

So here I get that itemId from event, but data is not saved in storage, I don't get any errors either.

what do you think a problem is ?

Thank you!


texts: Error: Operator == not compatible with types address and bytes32

texts:
How can I change the last line in the following code to make it work?

contract University {
    address public owner;
    address public student;
    bytes32 fName;
    bytes32 lName;
    bytes32 Studies;
    bytes32 private caCertificate;
    bytes32 ipfs_hash;

    constructor() public {
        owner = msg.sender;
    }

     modifier onlyOwner() { if (msg.sender == owner) _; }
     modifier onlyOwnerOrStudent() {
         if (msg.sender == owner || msg.sender == student) _;

    .....
}

I get the error message:

  Operator == not compatible with types address and bytes32


texts:
I recently did a course on uDemy and get the first concepts. I'm starting to build a real-life app for a training center. I want to register in the blockchain that Jhon Doe, ID (document) xxxx, approved the course "Master of blockchain" at specific date, and also register the "expiration date" for the certification/permission.
In PHP I would create an array like this:
$certifications[123456] = [
    [
    "name" => "Jhon",
    "lastName" => "Doe",
    "courseName" => "Blockchain master",
    "Expiration date" => "2022-01-01"
    ],
    [
    "name" => "Jhon",
    "lastName" => "Doe",
    "courseName" => "Just another course",
    "Expiration date" => "2021-01-01"
    ]
];

With the output:
array (size=1)
  123456 =>
    array (size=2)
      0 =>
        array (size=4)
          'name' => string 'Jhon' (length=4)
          'lastName' => string 'Doe' (length=3)
          'courseName' => string 'Blockchain master' (length=17)
          'Expiration date' => string '2022-01-01' (length=10)
      1 =>
        array (size=4)
          'name' => string 'Jhon' (length=4)
          'lastName' => string 'Doe' (length=3)
          'courseName' => string 'Just another course' (length=19)
          'Expiration date' => string '2021-01-01' (length=10)

Furthermore, I want to create a function to find by document ID the certification he/she did.
Needless to say that I want to keep it on memory on a persistent way, using gas if necesary.
I thought in create a mix between mapping and array for this, maybe struct... But I've the feeling that I'm on the wrong way.
So... Anybody can guide me or send me a similar example to check how to approach?
Thanks in advance!


texts: Is there any optimal time to check ipfs-hash exist or not?

texts:
ipfs object stat:

'ipfs object stat' is a plumbing command to print DAG node statistics.
 is a base58 encoded multihash.

If given hash is valid, it returns some information (if and only if shared node's ipfs daemon is on).
$ ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1tpt
NumLinks: 0
BlockSize: 39
LinksSize: 2
DataSize: 37
CumulativeSize: 39

Now I try it with an invalid hash or node (which shares the ipfsHash)'s ipfs daemon is off: I observe that the command halts.
$ ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1t88 #invalid hash
#waits.

If I enter an invalid has into ipfs object stat it pauses. I can do timeout N to terminate it: But I am not sure how long should I wait.
timeout 30 ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1t88

Overall, I just want to check does given ipfs-hash exists for me to retrieve its information.
[Q] Is there any optimal time for me to wait until ipfs object stat <ipfsHash> returns a valid value or not? Would around 30 seconds to wait be enough?
Please note that:  I tried between node in Europe and node in States, it took around 120 seconds on first try. But after I assume a path route is generated between those nodes, my next try with different hash between same nodes takes less than a second. What might be the reason for this?
Thank you for your valuable time and help.


texts: Why isn't my initial sendEther function not recognized as a receive ether function, am getting the error shown below

texts:
Error: This contract has a payable fallback function, but no receive ether function. Consider adding a receive ether function.
Here is my code:
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

contract MyContract {

 string public functionCalled;

 function sendEther () external payable {
     functionCalled = 'sendEther';
 }
 fallback () external payable {
     functionCalled = 'fallback';
 }
}


texts: Sign a raw transaction with Metamask or Mist

texts:
Is there a way to use the private key from my Metamask or Mist account to sign a raw transaction?

I cannot use ethereumjs-tx without the private key, but I want to be able to use injected Web3 and not create the keypairs myself.


texts: Can't launch mist wallet. Stuck after pressing 'launch application' in windows 10

texts:
Hi.
I downloaded Mist wallet and then after some time when the 'launch application' button came up, I pressed that. However, now I only see the following image on my screen and the figures shown below are stuck in that state for more than an hour. Do I need to do something differently?


texts: get all transfer events with getPastEvents that are from or to an address

texts:
i want to get all the events transfer from a erc20 token , that has a relation with an address either he send tokens or he recived them ,but filter with both fields with the same addres  is like an &&
the ref i've used
https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#getpastevents
this is my code
contract
      .getPastEvents("Transfer", {
        filter: {
          from: useraccounts[0],
          to: useraccounts[0]
        },
        fromBlock: 0,
        toBlock: "latest",
      })
      .then((data) => {
        console.log(data);
      });


texts: Initiate transaction from server to smart contract

texts:
In my case, i have an API written in PHP which periodically checks the database. If certain condition was met, i need to send an alert message from the API to an account/node in the Ethereum blockchain network through smart contract. Any idea how can this be done? or is this even possible?

PS: I am using Apache web server with MYSQL database


texts: Is it possible to have mappings inside mappings?

texts:
Is this possible?

mapping(address => mapping(uint => customStruct[])) someName

Because I cannot debug and find my mistake... is there not enough gas, or it crashes on this code, while trying to fill someName.

For example:

uint length = someName[msg.sender][1].length;
someName[msg.sender][1][length].timestamp = block.timestamp;


texts: I accidentally sent ERC20 tokens to my Ledger Live wallet, which does not support them. How do I get the tokens out?

texts:
The Ledger Live wallet does not support ERC 20 tokens.

How do I see and remove ERC20 tokens accidentally sent to a Ledger Live wallet address?


texts: I have a smart contract. I want to update the contents (list of names) of that contract let's say after every 5 minutes. The names change after this set duration. My approach is to create an instance of that contract(new address) and then write  the new set of names. I however feel this is not efficient. Is it possible to update stuff without having to change the address or creating a new instance? Is there a better way to do this?


texts: How to sign a transaction on an offline computer?

texts:
Short version: Is there a way to sign a transaction on an offline-computer using only official or widely trusted tools?

Long version of this question: There are several posts on how to do that but all of them link to more or less experimental tools. Is there a way to sign a transaction using only widely trusted tools like geth and move it already signed as a file via USB-stick to an online-computer?


texts: ethereumjs-tx Returned error: invalid sender

texts:
When i am trying to send signed transaction via ethereumjs-tx. I get this Returned error: invalid sender
web3Http.eth.getTransactionCount(myAddress,"pending").then(function(blockcount){

    result = web3Http.utils.toWei(amt.toString(), 'ether');

          count = blockcount;

          var rawTransaction = {
           "from":myAddress,
           "gasPrice":web3Http.utils.toHex(20* 1e9),
           "gasLimit":web3Http.utils.toHex(210000),
           "to":contractAddress,"value":"0x0",
           "data":contract.methods.approve(fromAddress,web3Http.utils.toHex(result)).encodeABI(),
           "nonce":web3Http.utils.toHex(count)
          }

          var transaction = new Tx(rawTransaction,{'chain':'rinkeby',hardfork: 'petersburg'});

          transaction.sign(Buffer.from(process.env.Key, 'hex'));

          web3Http.eth.sendSignedTransaction('0x'+transaction.serialize().toString('hex'))
          .on('receipt', ((data)=>{
            resolve(data);

          }))


texts: How do I REALLY setup a ETH mining on Ubuntu Linux together with Jaxx? Polo: ethereumpool.co

texts: I tried to setup a ETH miner on Linux Ubuntu 16.04.2 together with Jaxx. But it was too messy. Can someone go through step by step together with me?


texts: checking if an address exists inside a struct

texts:
I was wondering if anyone could help. I'm trying to check to see if an address has been stored in a struct, but the results I'm getting are not what I'm expecting.

So basically I have two functions....one is to store a value, and the other is to check if an address has already used the first function and stored a value.

so if I call storeValue() and then I input a value, the value gets stored correctly, but if I then call checkForAddress() and input my address, it still shows "false". I'm expecting it to show true because it was the same address I called storeValue() with to begin with.

I need to be able to confirm if addresses have already stored values....ultimately it will mean that if they have stored a vlue, then they won't be able to call storeValue() any more....they only get one chance to store a value from a single address.

Can anyone help, as I'm not really sure what I've done wrong :-(

thanks

pragma solidity 0.4.24;

import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol";

// MAIN CONTRACT

contract DoesAddressExist {
        using SafeMath for uint256;

constructor() public {
}

function () private payable {}

struct ValueRecorded {
    uint valueEntered;
    uint8 flag;
}

ValueRecorded[] public valueRecorded;

mapping(address => ValueRecorded) user;

function storeValue(uint _value) public {
        ValueRecorded memory newValueRecorded = ValueRecorded ({
                valueEntered: _value,
                flag: 1
                });
        valueRecorded.push(newValueRecorded);

}

function checkForAddress(address _address) public view returns (bool) {
    if(user[_address].flag == 1) {
    return true; }
    else return false;
    }

}


texts: How to wallet sync with blockchain network

texts:
I'm newbie, I have question: when a wallet connect to a network blockchain, does it connect to ALL of node in network or SOME node? And how to a wallet sync blockchain ?

Thank you very much!


texts: How do smart contracts handle race conditions?

texts: Let's say I have deployed a smart contract game that rewards the first user that writes to contract after a point in time T. Naturally, every player will try to be that winner, causing many requests to hit the network at once. If anyone could go into as much technical detail as possible, how does the Ethereum network determine who would be the winner of this game?


texts: go-ethereum rpc connection via http for native dapps

texts:
For native dapps we can establish an rcp connection over IPC using

conn, err := rpc.NewIPCClient("/home/karalabe/.ethereum/testnet/geth.ipc")

Now what if I want to establish an rpc connection over http i.e.

conn, err := rpc.NewHTTPClient("http://127.0.0.1:8545")

I am unaware whether than methods exists on the rpc package nor was I able to find the documentation for the rpc package. Can anyone provide examples of using HTTP connection over rpc or the full documentation of that struct?


texts: Setting a price for a payable function (Ethereum Pet Shop)

texts:
I'm following the Ethereum Pet Shop tutorial online, and everything works fine. However, to "adopt" a pet, the MetaMask transaction on my site is only requiring me to pay for the gas. I've taken a look at the Solidity docs and I think I'm supposed to make my function "payable", which I've tried, but actually setting a required price in wei to execute the contract is unclear to me.

Here's my Adoption.sol file:

pragma solidity ^0.4.17;

contract Adoption {
    address[16] public adopters;
    // Adopting a pet
    function adopt(uint petId) public payable returns (uint) {
        require(petId >= 0 && petId <= 15);

        adopters[petId] = msg.sender;

        return petId;
    }
    // Retrieving the adopters
    function getAdopters() public view returns (address[16]) {
        return adopters;
    }

}

And my TestAdoption.sol file:

pragma solidity ^0.4.17;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";

contract TestAdoption {
    Adoption adoption = Adoption(DeployedAddresses.Adoption());

    //Testing the adopt() function
    function testUserCanAdoptPet() public {
      uint returnedId = adoption.adopt(8);
      uint expected = 8;
      Assert.equal(returnedId, expected, "Adoption of pet ID 8 should be recorded.");
    }

    // Testing retrieval of a single pet's owner
    function testGetAdopterAddressByPetId() public {
        // Expected owner is this contract
        address expected = this;
        address adopter = adoption.adopters(8);
        Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded.");
    }

    // Testing retrieval of all pet owners
    function testGetAdopterAddressByPetIdInArray() public {
        // Expected owner is this contract
        address expected = this;

        // Store adopters in memory rather than contract's storage
        address[16] memory adopters = adoption.getAdopters();

        Assert.equal(adopters[8], expected, "Owner of pet ID 8 should be recorded.");
    }

}

Can anyone point me in the right direction?


texts: How open local ethereum chain (leveldb) using PyEthereum package?

texts:
I got local private blockchain in:

  /Users/User/EthereumTestNet/geth/chaindata

How i can connect to it, to get chain data by ethereum.pow.chain.get_block(hash)?
I know that to look at chain data i first must get state and in that point i have problem.
I tried do like:

levelDB = leveldb.LevelDB('/Users/User/EthereumTestNet/geth/chaindata')
state = trie.Trie(levelDB, '81fe149a7edc2e26b6cb14c17077ed6fd0d31f3a2c6b3e48eb8c42908493cbdc'.decode('hex'))

levelDB = leveldb.LevelDB('/Users/User/EthereumTestNet/geth/chaindata')
state = trie.Trie(db.BaseDB(levelDB), '81fe149a7edc2e26b6cb14c17077ed6fd0d31f3a2c6b3e48eb8c42908493cbdc'.decode('hex'))

baseDB = db.BaseDB(filename='/Users/User/EthereumTestNet/geth/chaindata')
state = trie.Trie(db.EphemDB(), '81fe149a7edc2e26b6cb14c17077ed6fd0d31f3a2c6b3e48eb8c42908493cbdc'.decode('hex'))

No any ideas, can anybody help?

use last pyethereum, last geth, MacOS