texts: How to log an event which emits state of the contract in nethereum?

texts:
I am logging a specific event from a specific contract using nethereum. However, my event emits contract state (enum in solidity). My log processor shows 0 events instead of 2.

Solidity code snippet:

// event

event Transaction(address from, StateType contractState);

// function

    function submitProof
    (string memory clm_num, string memory lin_typ, string memory lin_st, string memory out_rsrv, string memory tot_paid, string memory date_post) public
    {
        ProofData memory inputTransaction;
        inputTransaction.claim_num = clm_num;
        inputTransaction.line_typ = lin_typ;
        inputTransaction.line_status = lin_st;
        inputTransaction.outstanding_rsrv = out_rsrv;
        inputTransaction.total_paid = tot_paid;
        inputTransaction.date_posted = date_post;
        inputTransaction.isDataPresent = true;

        if (contractState == StateType.ZeroState || contractState == StateType.RetrievedState) {
            cedeData = inputTransaction;
            contractState = StateType.CedeState;
        }
        else {
            if (cedeData.isDataPresent && contractState == StateType.CedeState) {
                verifiedData = inputTransaction;
                if (sha256(abi.encode(cedeData)) == sha256(abi.encode(verifiedData)))
                    contractState = StateType.AuditState;
            }
        }
        emit Transaction(msg.sender, contractState);
    }

Nethereum code snippet:

// event class

[Event("Transaction")]

        public class Transaction : IEventDTO
        {
            [Parameter("address", "from", 1, false)]
            public string Sender { get; set; }

            [Parameter("int", "contractState", 2, false)]
            public string ContractState { get; set; }
        }

// logic to log event

The logs show count 0 where I expect count to be 2.
Also how to extract data from log to show that on UI? I couldn't find any extraction logic in Nethereum docs.


texts: converting keccak from old version: pragma solidity 0.4.19;

texts:
I am trying to compile following code:

pragma solidity 0.5.9;
contract test{
//https://github.com/ethereum/solidity/issues/3469

address payable owner;
mapping (address => bool) pd;
uint public sS;
function lnA(address addr) public view returns(uint n) {
        // 1 in 8 chance
        n = uint(keccak256(uint(addr), sS)[0]) % 8;

    }
}

  solc keccakSyntaxerr.sol

    keccakSyntaxerr.sol:10:18: Error: Wrong argument count for function call: 2 arguments given but expected 1. This function
    requires a single bytes argument. Use abi.encodePacked(...) to obtain
    the pre-0.5.0 behaviour or abi.encode(...) to use ABI encoding.

    n = uint(keccak256(uint(addr), sS)[0]) % 8;
                         ^-----------------------^
        keccakSyntaxerr.sol:10:13: Error: Explicit type conversion not allowed from "bytes1" to "uint256".
                n = uint(keccak256(uint(addr), sS)[0]) % 8;
                    ^--------------------------------^

How to convert the above syntax into lastest Solidity versions? Somebody please guide me.

Zulfi.


texts: ATTENTION!This page does not represent the entire state of the ethereum network - listing a node on this page is a voluntary process

texts: I am trying to attach my private blockchain to ethstats. When i run the npm, it gives me this error.


texts: I am using "https://rinkeby.etherscan.io/" testnet and api "https://rinkeby.etherscan.io/apis" with PHP. But problem is that when someone give me a ether, i am not getting payment receiving ping, is there anything that i can use to have notification whenever i receive payment on my address.


texts: How to calculate optimal gasPrice and gasLimit?

texts:
I am using rawTransactions and web3Instance.eth.sendSignedTransaction to deploy and interact  with smart-contracts.

The problem is that I can't figure out hot to calculate optimal gasPrice & gasLimit, so the transactions get mined & approved asap.

Currently I have these two functions:

async function getGasPrice() {
    return web3Instance.eth.getGasPrice()
        .then((gasPrice) => {
            return gasPrice;
        })
        .catch((err) => {
            console.log('getGasPrice-error', err);
        });
}

async function getGasLimit() {
    return web3Instance.eth.getBlock('latest', false)
        .then((result) => {
            return result.gasLimit;
        })
        .catch((err) => {
            console.log('getGasLimit-error', err);
        });
}

But when I try to deploy the contract it takes veeeeery long the transaction to get approved and mined. Then it shows Transaction was not mined within750 seconds error and gets deployed after undefined amount of time, which is not what we expect. :/

Any suggestions?


texts:
I have paid for an ICO company who issue tokens into MEW, using fiat money (AUD)
I believe they will exchange the fiat for Eth when the sale ends in about 19 days time.
What they cannot advise me on is how the tokens find their way into my ETH wallet.
Do I send them a 'send to' key address to send them to or is there a different token address which I need to access so that the tokens arrive correctly.
Please advise.


texts: Fail with error 'TransferHelper: TRANSFER_FROM_FAILED' / ERC20: transfer amount exceeds balance

texts:
I am Swap Tokens to ETH via uniswap but its failing due the following:
Fail with error 'TransferHelper: TRANSFER_FROM_FAILED' on EtherScan but on Tenderly I am seeing  ERC20: transfer amount exceeds balance
I have ETH and TOKEN amounts, so I believe it should work, can anyone help?
https://etherscan.io/tx/0x4cbed777d59733dbc0824bad0f365f2e6b8f9bbe0d3605a00bf8752b6b1756b3
https://dashboard.tenderly.co/tx/main/0x4cbed777d59733dbc0824bad0f365f2e6b8f9bbe0d3605a00bf8752b6b1756b3


texts:
i was hoping someone could help, I sent some ether to an initial coin offering and got my  coins in return all good.
But when i tried to do it again i get Tx receipt status failed and when i look at the transaction on etherscan i get Value transfer did not complete most likely as a result of a revert opcode.
I am new to this industry so i don't no where to start.thanks smarx tx,
0xf534e41bf64722e1daa35c626815374a19fc4bdca1ba6113e3ec67e4de837182


texts: How Ethereum prevents miners to sent same transaction multiple time on different blocks?

texts:
For example, userA submitted transactionX (ex: which send 10 ether to minerM), and this is deployed via minerM on the block #100.

If mineM is an attacker, and it is consecutively elected as a leader on block #101, 102 ...

From the example above, attacker realizes that transactionX sends money to itself and want to re-deploy same transaction on a new block.

Can minerM or any other miner re-deploy the transactionX again, even the userA didn't submit it on the second time?

I know it is now possible but:

[Q] How Ethereum-Virtual-Machine prevents miners to sent the same transaction, as accepted, more than once in different blocks?


texts:
I am using IPFS to store data [As per suggestion from an answer in ethereum stackexchange ,I couldnt find link to the question:( ]. The hash of file stored in ipfs is inserted into the data field of a transaction. But I couldnt find a way to access these datafields . Tried fetching transaction by using the transactionhash , but the retrieved result does not have a data field . Is there any function similar to eth.filter in web3 v1.0 ?.

function(req,res){
console.log(req.body)
web3.eth.getAccounts(function(e,accounts){

    web3.eth.personal.unlockAccount(accounts[0],req.body.pass, 1000000);
    web3.eth.sendTransaction({
        from:accounts[0],
        to:req.body.address,
        data: req.body.id
    }, function(error, hash){
       console.log(error)
       console.log(hash)
    });

})

}

Running the above code returns a transaction hash . req.body.id is fetched from an api endpoint which returns hash of the uploaded file . To list all transactions , I tried to use web3.eth.filter but it returned an error :

  TypeError: web3.eth.filter is not a function

Then I console logged web3.eth and couldnt find any filter function in the log .Is there any function to list all the transactions from/to an address ?


texts: How to create account using mnemonic words or private key in web3js and call contracts using that account

texts:
I have a simple React Project with web3@1.2.4 installed and I want to call a contract's method like this:

await maincontract.methods.CurrentMethod("arguments").send({ from: accounts[0]/*my account should go here*/, gas: 3000000 });

This code works well in localhost Ganache but instead of accounts[0] from localhost I want to use my own account that I have in Ropsten network and I guess that to use that account, I need an infura project that can connect me to the Ropsten network and I also need the mnemonic phrase or private key of that account in order to use that account to call contract methods.

So basically how can I use my account located in Ropsten network to call a contract located in the same, Ropsten network? Do I need to pass in mnemonic phrase? Do I need to pass private key? what do I need to do?

I have tried using truffle-wallet-provider but it doesn't install, don't even ask about the errors. There is another truffle-wallet-provider.

This is what I am trying locally on Ganache but it doesn't seem to work, the contract code is working great, tested using Ethereum Remix.

const web3 = new Web3("HTTP://127.0.0.1:7545"); //Ganache Local Host
    const maincontract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS); //already deployed the contract using Ethereum Remix and copied the Contract address and ABI
    const privateKey = "c1937e53c13e500644f45d77e075ca0059dcbae204ef06aa08494a129d871fdc"; //took the account right below the first account and copy pasted its private key
    const account = web3.eth.accounts.privateKeyToAccount(privateKey); //creating account
    const transaction = maincontract.methods.CurrentMethod("arguments");
    const options = { //TransactionConfig I guess
      to: transaction._parent._address,
      data: transaction.encodeABI(),
      gas: await transaction.estimateGas({ from: account.address }),
      gasPrice: await web3.eth.getGasPrice()
    };
    await web3.eth.accounts.signTransaction(options, privateKey).then(tx => {
      //signed = tx.rawTransaction;
      console.log(tx.rawTransaction.toString()) //this is showing random Hex but I see no transaction log in Ganache
    });


texts: Why solidity's keccak returns different value from online generators?

texts:
I try to implement my own little modifited commit&reveal voting. I have problem with revael phase. Reveal metod signature look like:

function reveal(bytes32[] memory _reveals, bytes32[] memory _commits)

So I need to compare hashed reveal phrase and commit phrase. I discover that these hashes do not match each other.

To demonstrate my problem I created this contract:

pragma solidity >=0.5.10;

contract Utils{
   event HashedData(bytes32);

   function getHash(bytes32 data) public pure returns(bytes32){
       return keccak256(abi.encodePacked(data));
   }

   function checkHash(bytes32 hash, bytes32 data) public returns(bool){
        bytes32 hashedData = getHash(data);
        emit HashedData(hashedData);
        return hash==hashedData;
    }
}

Example input data:
phrase: "1_john" to bytes32

  data: 0x315f6b6f74000000000000000000000000000000000000000000000000000000

hash from data (without 0x)

  hash: 0x90a0076f07f9884805bdc4d668c55756ff42238a0ad7b824b8a267783e822544

As result I receive:

Where I made mistake?


texts: Send total ether balance using geth/web3js

texts:
I installed a full node and synced to rinkeby testnet. I created 3 accounts using

eth.personal.newAccount

Assumed the balances of 3 accounts

Account A: 1 eth (this is coinbase account)
Account B: 1 eth
Account C: 1 eth

What i want is sending 2 eth to Account D at one time to reduce the fee?

Is it possible using geth or web3js API?

Cheers


texts: Updating ERC-721 Token's Metadata after it was Minted

texts:
Is it possible to somehow update an existing ERC-721 Token's MetaData after it was already minted?
Let's say we've created a Knight character for a game - by minting an NFT for it, and 3 months later we want to update that Knight's attributes to reflect the amount of experience or treasure it has amassed through game play.
The original URI for this Knight-Token looked something like this:
{
    "name" : "KnightToken1",
    "description" : "One-of-a-kind-Knight",
    "image" : "http://www.mydomain.com/myImages/knightImage.png”,
    "attributes" :
     {
        “Age” : “30",
        "Treasure” : “2 Gold Crates”
     }

}

We now want to update the "Treasure" attribute to "100 Gold Crates" - how can it be done?
My understanding was that it can't be done - the Blockchain is supposedly immutable after all - but I've seen some posts essentially saying "with our API you CAN do this!" - except they don't tell you how.
So I'm wondering: is this a false claim - or is there really some clever way of updating an already-minted ERC-721's token metadata? And if so, how?


texts: I want to send 100 Tokens but receive 0.0000000000000001 Token? Amount unit256 What is so I can send 100 Token?

texts:
I tried to send 100 Token by multitransfer but received 0.0000000000000001. I performed by remix. How can I send the correct token number I want?

 function multitranfer(address[] addrs, uint256 amount) public {
for (uint256 i = 0; i < addrs.length; i++) {
  transfer(addrs[i], amount);
}

}

Thanks you!


texts: Functions with boolean return type while using require()

texts:
I am trying to understand the reasoning for this: (for an online class)

mapping (uint => uint) public multiplier;
/**
 * Called by the owner of the TollBoothOperator.
 *   Can be used to update a value.
 *   It should roll back if the vehicle type is 0.
 *   Setting the multiplier to 0 is equivalent to removing it and is acceptable.
 *   It should roll back if the same multiplier is already set to the vehicle type.
 * @param vehicleType The type of the vehicle being set.
 * @param multiplier The multiplier to use.
 * @return Whether the action was successful.
 * Emits LogMultiplierSet.
 */
function setMultiplier(uint vehicleType, uint multiplier) public returns(bool success) {
    require(vehicleType > 0); //maybe just not equal to 0
    int currentMultiplier = multiplier[vehicleType];
    require(currentMultiplier == 0);
    return true;
}

What is the point of having a boolean return type since the function will never get to the return value if it will not succeed since the transaction will be rolled back by the require statements.


texts: Automatically create setters and getters

texts: I've read that getters are automatically created when you make a variable public. Can other contracts access these getters or is it only for web3.eth? Also what would be the getter name?


texts: Require messages on Remix or a similar tool

texts:
Our team is using Remix for a long time for the first exploratory tests or to call administrative methods (that we do not have specific UI).
I remember that some time ago I saw the messages that we include in require statements (I mean, when the require is false), but I am not seeing these messages anymore.
Are there some alternative tools or any way to configure Remix to that?


texts: How to handle structs within solidity any

texts:
What's the possible workaround for passing an array of strings (not supported by solidity at current time). I am using an array of struct that is state variable to a contract.

pragma solidity ^0.4.23;
contract Person {
struct edu {
string title;
string institute;
string date;
string details;
}
edu[] public education;
constructor (string[] title, string[] institute, string[] date, string[]
details
) public {
for (uint i=0; i<title.length; i++)
edu memory newEdu = edu({
title : title[i],
institute : institute[i],
date : date[i],
details : details[i]
});
}
}


texts: Unable to deposit ether to a payee in an escrow contract

texts:
I am unable to deposit ether to a payee in an escrow contract.
The error is:
transact to Escrow.deposit errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
How do I solve this? With thanks.
pragma solidity ^0.5.0;

contract Escrow {

    address agent;
    mapping(address => uint256) public deposits;

    modifier onlyAgent() {
        require(msg.sender == agent);
        _;
    }

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

    function deposit(address payee) public onlyAgent payable {
        uint256 amount = msg.value;
        deposits[payee] = deposits[payee] + amount;
    }

    function withdraw(address payable payee) public onlyAgent {
        uint256 payment = deposits[payee];
        deposits[payee] = 0;
        payee.transfer(payment);
    }
}


texts: How to unlock the ethereum contract account?

texts:
I installed the package from this link and its working fine. Then I create the one multisig contract. when creating the contract I got one new address.

I can deposit that address but for withdraw process it shows the error message like you need to unlock the account on send transaction process on Web3 API.

I am also trying the unlock function but here we need to provide the password but for this contract address we didn't know the password.

So please help anyone to unlock the contract account. I should use that address for withdraw process because by that process only the multisig process working.


texts: Rainbow Table, compromised Geth Node and any possible recourse

texts: If and/or when a geth node is compromised, and the hacker uses a rainbow table, will he or she be able to get many private keys to sign his/her way to be the king of ether?


texts: JSON RPC call from javascript with axios

texts:
I would like to call a geth method via JSON RPC from within a react component. I tried this but I always get the Error: 405 (Method Not Allowed)

Here is my code:

try {
      const response = await axios.post('http://localhost:8501', {
        jsonrpc: '2.0',
        id: + new Date(),
        method: 'eth_accounts',
        params: {
        },
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
      })

      console.log(response.data.result.address)
      console.log(response.data.result.publicKey)
      console.log(response.data.result.wif)
      console.log(response.data.result)
    } catch(error) {
      console.error(error)
    }

Do the requests have to be POST or GET?

My geth instance is running with the following arguments:

geth --datadir node1/ --syncmode 'full' --port 30311 --rpc --rpcaddr 'localhost' --rpcport 8501 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://<enode@<127.0.0.1:30310' --networkid 1515 --gasprice '1' -unlock '0x0' --mine

Thank you very much for your help


texts: Why do knownStates and Pulled states reset to zero on restarting geth?

texts:
I've noticed that, if I restart geth, attach a console and run eth.syncing, the knownStates and pulledStates values reset to zero and gradually increase again.

Possibly naively, I'd expect that, once known, the states should not be forgotten. Why am I seeing this behaviour?

Why do knownStates and pulledStates reset to zero on restarting geth (after running eth.syncing?


texts: How do pools calculate the "expected daily earnings"?

texts:
I've been looking at the "expected daily earnings per 100MH/s" on the hiveon.net pool and it was 0.006eth to more than 0.007eth for the past few weeks, but very recently it's gone down to a lot of the times less than 0.005eth. I also mine a little bit and the average earnings seem to match. The past 2 days have had way less earnings than usual.
I'm struggling to understand why it changed so drastically.
I looked at the etherscan.io block explorer and it seems that the average block reward has stayed almost the same for the entire time and the network hashrate / difficulty didn't go up substantially either. Is there something more to the expected daily earnings per mh than just the total network hashrate and the block reward? does the mining speed slow down substantially if the difficulty increases slightly?


texts: State Variables: What are they and how to create them?

texts:
I am new to ethereum and Solidity.
I thought state variables are supposed to retain their value between calls.
In the Solidity documentation, in the section State Variables, it says that state variables are created like this:
contract SimpleStorage {
    uint storedData; // State variable
    // ...
}

I created the following contract to test the theory.
contract Test {
    uint256 times_called;

    function tc () public returns (uint256) {
        times_called += 1;
        return times_called;
    }
}

I am calling it with web3 like this:
const test = new web3.eth.Contract (contract_abi, contract_address, { from: from_address, data: contract_bytecode });
var value = await test.methods.tc ().call ();

It returns 1 every time.
Have I not declared a state variable here? Or am I mistaken about how state variables are supposed to work?


texts: How does a relying party learn a PageSigner server's public key?

texts:
Hoping for some insight Into to page signing... I understand that:

https://tlsnotary.org/pagesigner.html can provide proofs that a specific web page was returned from a third-party TLS-protected server.
it's possible to set up an AWS instance to "provably" run the PageSigner server.

What I can't understand is: if you give me a signed statement, and you tell me that it has been signed by a specific PageSigner server running in AWS (with untampered code), how do I know which public key is  associated with this PageSigner server? I can verify that the server you tell me about is running untampered code, but how do I interrogate this server to learn its public key (for verifying signatures)?

The PageSigner service generates a keypair at boot time (stored in a RAM-backed filesystem at /dev/shm) -- and it outputs the public key to the AWS Console for the service operator to see -- but I can't see where/how this key is verifiably published for the rest of the world to see.

I expect I'm missing something straightforward... but from the outside world, if I don't know which public key the PageSigner service is using, how can I tell that a proof was signed by this particular PageSigner instance?


texts:
I am developing an application from the truffle webpack and I have created my own wallet, adding my account to a json file:

 $.getJSON('../wallet.json', function(data) {
        var password = "xxx";
        var json = JSON.stringify(data);
        ethers.Wallet.fromEncryptedWallet(json, password).then(function(wallet) {...})

Everything works, but I have a problem with Browser-sync. It recognizes that something is being changed all time and my web is reloading constantly since I am mining and the wallet balance changes. I would like to know which file is changing to ignore it.


texts: After a suicide operation, is contract’s nonce reset to 0?

texts:
Simple question, but I couldn’t find the answer in the yellow paper.

Is it reset to 0 or is it kept at the latest value before destruction ?


texts: Can't establish the connection with bootnode and two nodes

texts:
I have problem with starting my private network.

Two nodes on different PC and with external IP addresses, starts with next parameters:

--verbosity 3 --identity "TestNet" --rpc --rpcport "8081" --rpccorsdomain "*"
--datadir "%datadir%" --port 25565
--rpcapi "admin,debug,miner,shh,txpool,personal,eth,net,web3"
--bootnodes "enode//:ID@IP:port"
--networkid 255655 console

Bootnode starts on third PC with own external IP address too::

 --nodekey geth/bootnode.key --verbosity 9 --addr "ip:port"

Bootnode reports PING\PONGS with both nodes. But they still have 0 peers.

I dont know what to do.
I try to change parameters to discovery5 protocol
     --v5disc --bootnodesv5 (for nodes)
     --v5 (for bootnode)
Bootnode still have strong connection with nodes, but they still have no peers.
And bootnode report error: invalid neighbor : is self

I try to reinitialize nodes, start to mine on one or both. But nothing helps.

What im doing wrong?


texts: Does running a light client add extra security for Ethereum compared to doing nothing?

texts:
These may answer the question:

https://github.com/ethereum/wiki/wiki/Light-client-protocol

https://blog.ethereum.org/2015/01/10/light-clients-proof-stake/

Of course you want to be secure, but assuming that running a light client is relatively secure for a user, my question was more about whether running a light client vs not running any client would be more secure for Ethereum. Obviously if you can run a full node or a full state node or a miner that will increase the security of the network, but if your computers can't feasibly do that, then a light client is the only option compared to not running any client.l


texts: How does Ether-Pudding/Truffle handle Metamask and Mist browser?

texts: Is there anything different with how the accounts are managed?


texts: How to execute a smart contract and get Events without broadcasting transaction to MainNet?

texts:
Is it possible to emulate execution of a transaction without sending it to MainNet?

I can't use testrpc or private network for it because my contracts use data from other contracts in MainNet.

How miners execute pending transactions?


texts:
first time Mining! Watching a YouTube Tutorial about Blockchain basics and it shows how to set up a Genesis Block as well as how to start Mining.
I've followed all the steps to the best of my abilities and got stuck up until the point where we actually Mine the block.
The YouTube instructor says it takes a bit to start mining, ~10 min according to him.
But after 10 minutes nothing was happening. After using the "Miner.stop()", it returned null. Upon further investigation, the boolean function eth.mining returned true after miner.start() and false after miner.stop(). eth.hashrate was also returning numbers ranging from 322700 to 322943. Also, under System Monitor, the CPU was all running at 100%. Being my first time mining and fixing this laptop, I didn't want anything to happen.
Any idea what's going on? Does Mining require Good Internet (using Satellite)


texts: Can't compile contract - pragma error and Cannot read property 'interface' of undefined

texts:
I am trying to compile this simple contract:

pragma solidity ^0.4.18;

contract Tasks
{

    struct TaskOwner {
      address TaskOwnerAddress;
      bytes32 TaskOwnerName;
    }
    mapping (address => TaskOwner) public theTaskOwner;

    //Task owner information
    address TaskOwnerAddress;
    bytes32 TaskOwnerName;

    modifier onlyOwner(){
      if(msg.sender != TaskOwnerAddress) revert();
      _;
    }

    event NewTaskStarted(bytes32 TaskOwnerName, address TaskOwnerAddress);

    function Tasks(bytes32 TaskOwnerName) {

        //establish the owner
        TaskOwnerAddress = msg.sender;
        TaskOwnerName    = TaskOwnerName;

        //fire a new Task started event
        NewTaskStarted(TaskOwnerName, TaskOwnerAddress);
    }
}

using this script in the contracts directory after starting rpc in another Mac terminal tab:

node

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

code = fs.readFileSync('Tasks.sol').toString()
solc = require('solc')
compileCode = solc.compile(code)

abiDefinition = JSON.parse(compileCode.contracts[':Tasks'].interface)

but the solc.compile produces this warning:

  compileCode = solc.compile(code)
  { contracts: {},
    errors: [ ':1:1: Warning: Source file does not specify required compiler version!Consider adding "pragma solidity ^0.4.18\n\n^\n' ],
    sourceList: [ '' ],
    sources: { '': { AST: [Object] } } }

and then when I use this command next:

abiDefinition = JSON.parse(compileCode.contracts[':Tasks'].interface)

produces this error:

TypeError: Cannot read property 'interface' of undefined
    at repl:1:59
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:233:10)
    at REPLServer.Interface._line (readline.js:584:8)
    at REPLServer.Interface._ttyWrite (readline.js:861:14)
    at REPLServer.self._ttyWrite (repl.js:611:7)
    at ReadStream.onkeypress (readline.js:120:10)
    at emitTwo (events.js:106:13)
    at ReadStream.emit (events.js:191:7)
    at emitKeys (internal/readline.js:389:14)
    at next (native)
    at ReadStream.onData (readline.js:971:36)
    at emitOne (events.js:96:13)
    at ReadStream.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at ReadStream.Readable.push (_stream_readable.js:134:10)
    at TTY.onread (net.js:547:20)

I'm trying to understand why it is saying that there is no pragma comment when there is. And I'm trying to understand the meaning of the TypeError: Cannot read property as well.

I am running this in the contracts directory of this truffle unbox pet-shop file structure.

Any comments to improve the code would be appreciated as well as I am learning solidity.

Thank you


texts: How to call a function by different addresses using dapple

texts: I'm new to dapple. I have a contract contains five functions and each function is called by different addresses. I want to write unit test using dapple how can I call a function by two addresses?


texts: Will I be able to get past contract events through rpc if I use geth --fast?

texts: Or in other words, will geth --fast download the events logs?


texts: What is rpc and p2p code for Ethereum token? What to give as GitHub source code of an Ethereum token in exchange?

texts: I’m new to Ethereum development. From ethereum token docs I came to know the process of deploying the token. But at some exchanges they ask for RPC and P2P port as well as the github source of the coin. I’ve searched everywhere almost. No direct answer. Maybe I’m a complete newbie but please give me a direction.


texts: Ethereum geth mainnet blocked on “Looking for peers”

texts:
I installed Geth for setup a ethereum node on my linux server and use it on my RPC API.
The problem is, Geth is posting "Looking for peers" forever, I don't really understand why. This is not a firewall problem, port 30303 TCP and UDP is allowed and works.

Here is my geth configuration:
geth --networkid 1 --http --http.port 6666 --http.api "personal, eth, web3" --datadir /root/.ethereum --syncmode fast --cache 2048 --nodiscover
My geth version is 1.9.20.
Thanks you for your help.


texts: Can you help me parse this input data from a newProposal transaction from The DAO?

texts:
Every Ethereum transaction that represents a function call on a smart contract holds an input field with data that corresponds to the data sent through the interface of the function. For example, this transaction (
https://etherscan.io/tx/0x3a7d091970d7931dd5ef4872e59093234e132f861139403d2b69db80ac2d0ecb) is a newProposal function on The DAO. You can that etherscan separates the data into 32 byte chunks. It's relatively easy to pick off the first 'address' and the second 'debatingPeriod,' but I'm having trouble from there. I'm assuming that the next 32 byte second is the start of the string description, and I am further assuming that it is in RLP format as described here: https://github.com/ethereum/wiki/wiki/RLP, but I'm not so sure.

According the RLP document, a third 32 byte section should be only a single byte long and if it represents 0xca it means an empty list (see examples at the bottom).

So two questions: (1) how does one parse the input data (particularly strings) of the data provided by ehterscan.io, and (2) does etherscan represent the data as it actually exists on the blockchain?

Function: newProposal(address _recipient, uint256 _amount, string _description, bytes _transactionData, uint256 _debatingPeriod, bool _newCurator)


texts: What’s the full changelog for things which actually had been implemented by Constantinople?

texts:
It’s being said that the Constantinople hard fork is a minor one.
But as far I know, this is isn’t just a miner reduction fees. They are additional things which were implemented (like a special ꜱꜱᴛᴏʀᴇ case fee change which was later reverted).

So what’s the full set of changes and functionalities implemented by this latest hard fork ?


texts: Sending and Receiving funds from/to Contract Adresses to/from Exchanges

texts: I am new to Ethereum. We want to be able to receive funds (ETH and ERC20 tokens). It seems that exchanges do not allow to send funds to smart contracts, is it possible vice versa to send funds from contract address to exchanges or is it necessary to send them to a "normal" address first?


texts: How does Ethereum calculate balance for a new transaction if there are already unconfirmed transactions in the mempool?

texts:
Whenever a new transaction is made, it is added to the mempool and a miner will take these transactions from the pool and try to generate a block which contains this transaction.

However, before making the transaction, we need to make sure that the sender has enough balance to broadcast the transaction which is calculated from iterating through the blockchain.

The problem arises when a transaction is made by the sender (who had previously made an unconfirmed transaction and which is sent to the miner) and the mining process is still happening since we cannot calculate the sender's balance as the previous transaction is still being mined and the balance needs to be confirmed by the blockchain. Technically, we can still calculate the balance but the balance calculated will be incorrect and outdated.

So, how does Ethereum calculate the balance before making a transaction?


texts: Swap Ether to tokens on Uniswap V2 Router Gas Estimation Error

texts:
I am trying to buy DAI tokens from my smart contract using IUniswapV2Router02:
contract BuyToken {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //  Uniswap Router Address
  address private multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI Kovan Address, Mainet: 0x6B175474E89094C44Da98b954EedeAC495271d0F
  IUniswapV2Router02 public uniswapRouter;

  constructor() {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
  }

  function getPathForETHtoToken() private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = multiDaiKovan;

    return path;
  }

  function getEstimatedETHforToken(uint daiAmount) public view returns (uint[] memory) {
    return uniswapRouter.getAmountsIn(daiAmount, getPathForETHtoToken());
  }

  event Debug(
    uint256 ethAmountDerivable
  );

  function buy(uint tokenAmount) public payable {
    uint deadline = block.timestamp + 15;
    uint ethAmountDerivable = getEstimatedETHforToken(tokenAmount)[0];

    // Swap ETH for DAI
    uniswapRouter.swapETHForExactTokens{ value: ethAmountDerivable }(daiAmount, getPathForETHtoToken(), address(this), deadline);

    IERC20 token = IERC20(multiDaiKovan);
    require(token.transferFrom(msg.sender, address(this), tokenAmount), 'transferFrom failed.');
    require(token.approve(address(uniswapRouter), tokenAmount), 'approve failed.');

    emit Debug(ethAmountDerivable);
  }

  // important to receive ETH
  receive() payable external {}
}

If I try on Remix to call the getAmountsIn and paste the value for swapETHForExactTokens it works fine, but directly using the variable to supply into the swap function causes Gas Estimation Error. I looked into the value of ethAmountDerivable the result is just exactly the same as the one I am pasting.
Why do I get gas estimation error even if the value I used manually and thru variable is exactly the same? And how do I resolve this?


texts: Is there a layered architecture diagram for Ethereum?

texts:
I wonder if there is a layered architecture diagram for Ethereum that shows from the lowest level to the highest level like the one of Java (http://docs.oracle.com/javase/8/docs/index.html)?

It could be very useful indeed.


texts: How many transactions per second can Kovan or Rinkeby Network handle?

texts:
Now, Ethereum can handle only 8-12 transactions per second by using PoW Consensus.
I know that Kovan and Rinkeby is using PoA Consensus. PoA is lightweight than PoW. So how many transactions per second can Kovan or Rinkeby Network handle?


texts: What does it mean that Medalla hasn't reached finality?

texts: For a couple of weeks Eth 2.0 testnet Medalla hasn't reached finality. What does it mean? What are the consecuenses?


texts:
I am developing a sidechain that will store data and I want to evaluate the processing of this data in the ethereum network to get the cost in gas. I'm going to develop a smart contract that will process the algorithm and return the data processing information to my sidechain. My doubts are:

Will the Ethereum network charge me some gas costs for processing smart contracts? Or will you only be charged the cost of creating the contract?
Is it possible to obtain information regarding the cost of processing using GANACHE?


texts: solidity ecrecovery and ethereumjs ecsign return different address

texts: I have a code as follow using web3 0.2 and ethereumjs-util to interact with smart contract. What exactly am i doing it wrong? is it incompatible between ecsign of ehtereumjs with smart contract ecrecovery? How can i fix it?


texts: Digital asset management dapp using Ethereum

texts:
I am new to ethereum and also I have tried out some examples for building smart contract using truffle and ganache. But I want to make Digital asset management dapp using ethereum.

Like, if have I have 50 person and 60 machines in organization, in that
 - one person is allocated to multiple machines
 - one machine can operate by only one person at a time
 - If any person wants to access the machine then current owner of that machine needs to releases that machine first.

So, all this information I need to store on blockchain.
Can anyone suggest how to at least start with this requieremnts, is it possible to do inside ethereum or any other blockchain network ?


texts:
Why is geth not letting me post a transaction with a low gasPrice?

> ./geth console
> eth.sendTransaction({ "from": "...", "to": "...", "gas": "30000", "gasPrice": "10", "value": "0.1" })
Gas price too low for acceptance

My understanding of Ethereum is that gasPrice is set by the user and either a miner will process it or they won't (presumably based on the gas price).  However, geth appears to be forcing me to pick a gasPrice that it believes is reasonable.  The exact algorithm is unclear, but also irrelevant to my question.  This behavior seems counter to the entire concept of market driven gas prices.

Is there a way I can tell geth, "no really, let me submit my transaction with a low gas price"?  Am I misunderstanding the whole gas model?  Is this a bug in geth?


texts:
I have a GETH synced node and can run eth_syncing, net_peerCount, eth_getBlockByNumber, and eth_getTransactionByHash with no errors. I get a valid result. When I run the below code, I get a error. I searched for about a day and can't find anything telling me the reason for the error or the meaning.
curl -X POST 'localhost:8545/' --header 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_getCode","params":["0xdac17f958d2ee523a2206206994597c13d831ec7","0x2"],"id":1}'
returns:
{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"missing trie node 4943d941637411107494da9ec8bc04359d731bfd08b72b4d0edcbd4cd2ecb341 (path )"}}
Any help would be appreciated.
EDIT:
I have found this post Understanding geth trie node pruning
But this doesn't tell me what is wrong. What I'm doing is getting the lastest block and all the transaction hash and finding out what address has the most activity to/from. I then take that address and immediately try and run the eth_getCode and get the error. Does the trie node not exist at this time?
EDIT 2:
I get a response on GETH console when I execute eth.getCode("0xdac17f958d2ee523a2206206994597c13d831ec7") Just not using curl jsonrpc method.


texts: Why does mist block importing accounts when a geth node is already running?

texts:
I have run into this issue. The cause is described in that thread, but not explained.

If I run mist and let it launch its own node, then the Accounts>Import menu item is available.

If I run geth myself and then run mist --rpc /home/me/.ethereum/geth.ipc then the menu item is greyed-out.

The tone in the bug report thread seems to indicate that this is normal, expected behaviour. What is the reason for this behaviour?


texts: How does Uniswap allow a user to specify which tokens the user wants to swap in this low level function?

texts:
I'm looking at the function swap that allows a user to swap token0 for token1 from Uniswaps UniswapV2Pair contract - https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol.
One thing that is unclear to me is how a user can specify which tokens they want to swap. It seems that _token1 and _token2 are both state variables that can't be set by the user. My suspicion is that it can be set in the "data" argument but I'm unsure how passing the relevant info in the data argument sets the state variables.
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {

        require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');

        uint balance0;
        uint balance1;

        { // scope for _token{0,1}, avoids stack too deep errors
        address _token0 = token0;
        address _token1 = token1;
        require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
        if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
        if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
        if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
        balance0 = IERC20(_token0).balanceOf(address(this));
        balance1 = IERC20(_token1).balanceOf(address(this));
        }
        uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
        uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
        require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');

        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
        require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');

        }

        _update(balance0, balance1, _reserve0, _reserve1);
        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
    }


texts: Cannot connect to any ethereum networks using API key

texts:
I followed a tutorial about how to connect web3 with ethereum networks.
I registered in infura.io and get all the urls. But when I try to connect to any network it is not connecting.When I print web3 connection status is always false. Below is my code and I use 1.0.0-beta.34 of web3

web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/MY_API_KEY'));
web3.eth.net.getNetworkType(function(err, res){
     console.log("Network Type: "+res); //Displaying undefined
});

I tried with main net, ropsten and kovan. All are displaying undefined. I don't know what is the problem here. All example in web are showing these lines only. Can some one help me to solve this? Thank you.


texts: Can someone help me get started on the Ethereum platform like all the basics?

texts: Im looking to get started in the cryptocurrency field and expand my knowledge in Ethereum


texts: Can a contract address have both ERC20 and ERC721 transactions

texts: Some addresses on Etherscan like this one show both type of transactions (ERC20 and ERC721) on Etherscan. So, does that mean that both standards can be implemented at the same time for a token?


texts: WEI to ETHER conversion issue with Web3 and Javascript

texts:
So i have a form where the user enters a price for an item in ETHER. I understand the blockchain does not handle floatin point numbers currently, so i am attempting to convert to WEI and store it on the block chain that way.

What im doing is the following

const price =.34 //this should be ether
const weiPrice = web3.toWei(cleanPrice, 'ether');
console.log('weiPrice', weiPrice);

output is
weiPrice 340000000000000000, which is correct. I am then passing the variable weiPrice into the truffle-contract promise to create a new item.

   return contractInstance.createItem(
        Number(weiPrice),
        Number(cleanQuantity),
        Number(cleanQuantity), {
          from: account,
        })

Everything appears to work, but when i retrieve the value from the blockchain for this item i am getting the following result.

retrieved item

BigNumber {s: 1, e: 17, c: Array(1)}
c: [3400]
e: 17
s: 1__proto__: Object

I need to convert the price back to ether or wei but i guess i just dont understand whats happening here. Can anyone help me understand?

I tried the suggestions from the first couple of comments, here are the results.

console.log('test', item[0].c.valueOf());

output

test [3400]
 0: 3400
 length: 1
 __proto__: Array(0)

console.log('test2', item[0].c.toNumber());

output

Uncaught (in promise) TypeError: item[0].c.toNumber is not a function


texts: Solidity triggered event that shows a message to everyone who is currently in the site

texts:
Just a small question regarding how solidity event works. Let's say I have a function buyCandy(). At the end of the function I attached event:

emit LogBuyCandy(msg.sender);

event LogBuyCandy(address _buyer);

Let's say there are 10 people who's in the site at the same time, viewing the list of candies to buy. When one of the users bought the candy which triggered the event, I'm popping up a message that reads something like "0x...(address) bought the candy".

ex:

listenToEvents: function() {
    App.contracts.Candy.deployed().then(function(instance) {
        instance.LogBuyCandy({},{}).watch(function(error, event) {
            if (!error) {
                // popup message

My question is, can everyone see that message at the same time? or is it just the one who bought the candy seeing the message only?


texts: Why are transaction fees defined by both gas price and gas limit, and not just one cost limit?

texts:
I understand that the gas limit is there so that we don't lose all our ETH when something goes wrong. The gas price is there to define how much 1 gas costs. But the fee is always gas price * gas limit, so why doesn't the Ethereum blockchain simply ask for a fee cost limit?

For example, I could set:

Gas limit to 10^6 and gas price to 10^9 Wei.

Gas limit to 10^9 and gas price to 10^6 Wei.

Gas limit to 10^10 and gas price to 10^5 Wei.

It all ends up in the same transaction fee: 10^15 Wei. So when we send an ETH transaction to the blockchain, instead of

    txData = {
      nonce: 20,
      gasPrice: 1000000000,
      gasLimit: 1000000,
      to: '0x8f2b163fd3a871ce',
      value: 10^18,
      data: '0x'
    };

why wasn't it built like this:

    txData = {
      nonce: 20,
      feeLimit: 10^15,
      to: '0x8f2b163fd3a871ce',
      value: 10^18,
      data: '0x'
    };

Finally, 1 gas is paid for each line of code, so that would mean a gas limit of 1 and a gas price of 10^15 wouldn't work. In this situation wouldn't it also be handier for the blockchain to automatically calculate the fee by dividing the fee limit (10^15) by the amount of lines so users don't have to gamble on gas price and gas limit?


texts:
I am thinking of building a capped crowd sale using CappedCrowdsale and MintableERC721 of OpenZeppelin. I wonder if its better to mint the tokens  once the cap is reached or to mint seperately once a payment is received?
I've started to build it by assuming to mint at the end of crowd sale but I am not certain about few things. I've come up with the following:

pragma solidity ^0.4.24;
import "./openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "./openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import "./openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol";
import "./openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";

contract SSale is CappedCrowdsale, ERC721Full {

using SafeMath for uint256;
/*
??? using ERC721Mintable for ERC721Full; ???
uint256 private _rate;
address private _wallet;
*/
IERC721 private _token;

/* @param _rate for Crowdsale
   @param _wallet for Crowdsale
   @param _token for Crowdsale
   @param _cap for CappedCrowdsale
   @param name for ERC721Full
   @param symbol for ERC721Full
*/
constructor(uint256 _rate, address _wallet, IERC721 token,
uint _cap,
string name, string symbol) public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
ERC721Full(name, symbol){}
}

The current version gives a DeclarationError: Identifier not found or not unique at line 17:

IERC721Full private _token;

Cause CappedCrowdsale is inheriting Crowdsale contract which takes (uint256 rate, address wallet, IERC20 token) as parameters in addition to _cap of CappedCrowdsale. In my case I'd have to replace IERC20 with IERC721.

I am not sure if/how I should import ERC721Full and interface ERC721Mintable, cause ERC721Mintable takes no constructor parameters but inherits ERC721Full which takes two strings name, symbol respectively. I'd appreciate any hints, corrections and suggestions on importing the relevant libraries and building the constructor accordingly. Feel free to comment about my choice of library as well, let me know what you think of 0xcert, Modular-Networks.


texts: Cannot allocate big buffer - Not enough graphics memory?

texts:
I am using Claymore's Dual Ethereum v9.5

Here is my config file:

setx GPU_FORCE_64BIT_PTR 0
setx GPU_MAX_HEAP_SIZE 100
setx GPU_USE_SYNC_OBJECTS 1
setx GPU_MAX_ALLOC_PERCENT 100
setx GPU_SINGLE_ALLOC_PERCENT 100
EthDcrMiner64.exe -epool eu2.ethermine.org:4444 -ewal 0x9C57aE119dd13EE9Cd444Cf96091f1e84446.rig-epsw x

I keep getting this error: "CUDA error: cannot allocate big buffer for DAG"

From what I've read this happens when graphics memory is too low. I use a Nvidia 750Ti with 2GB.

How can I fix this ?


texts: Mining Performance of AMD Radeon Pro Duo

texts: I would like to evaluate the purchase of that GPU for Ethereum Mining. Does someone already have benchmarks?


texts: Division/Percentages in Solidity (a workaround)

texts:
Division/percentages is a required part of many applications but is difficult to implement since fixed and ufixed are not supported yet in Solidity. I've come up with this workaround:

  pragma solidity ^0.4.9;

  contract Math {

    function Math() public {}

    function percent(uint a, uint b) public constant returns(uint, uint) {
      uint c = a*b;
      uint integer = c/100;
      uint fractional = c%100;
      return (integer, fractional);
    }

  }

If I want to get 12% of 27 and call percent(27, 12), I correctly get back 3 and 24 representing 3.24. The limitation to this of course is that percent(12.5, 100) isn't possible.

However if I call percent(17, 359), I get back 61 and 3. The real result is 61.03, however, because fractional is a uint, the 0 in front of the 3 is dropped. Is there a way to find out if a fractional has a leading zero?


texts: How to stop cpp-ethereum processes and remove cpp-ethereum and blockchain

texts:
Mac OS X, using command line:

How do I stop cpp-ethereum? I installed it last night, and it's been running my processor at 100% ever since. I kill the processes ($ kill < PID >) and it just starts a new one.

I was just trying to use cpp-ethereum, but for personal use, geth is great. And between geth, mist, and cpp-ethereum (eth), I now have 3 copies of the block chain, and no space on my hard drive. So how do I get out of this mess? I was thinking of removing cpp-ethereum and mist, and sticking with geth. But maybe you have another solution... Please help!

Thanks,
D


texts: I can only find instructions for geth, but cannot find anything about doing it using eth which is part of cpp-ethereum.


texts: How to access ethereum/client-go shell outside docker container

texts:
I have just started learning Blockchain and following a YouTube tutorial . In that tutorial he installed ethereum by cloning the repo , but I have installed the ethereum/go-client using docker as per the instructions given in official documentation . I am beginner to Docker too . When I run the docker container using docker run -it -p 30303:30303 ethereum/client-go command , my terminal looks like this :-

Now I want to make an account using personal.newAccount() command . But where I should run this command ? Container is not providing me any shell where I can run this command .
I have searched about this lot on internet but doesn't get a solution , all of them is showing how to install geth using docker only .
Please help me . I have just started learning blockchain .
Thank


texts: Downloading blocks problem and I can't see my transfer from Coinbase

texts:
Good afternoon to everyone!
I have a big problem. I've downloaded the ethereum wallet and I made a tranferency from coinbase to my adress. I can't see it in my wallet. I red in the answers that I must wait that the program downloads all the chain structure before I can see it in my wallet.
The problem is that every time I open the program it starts to download and it never ends because it increases constantly..what can I do?
How can I have my money back?Thank you!


texts: Why is my Greeter contract not mined on --testnet?

texts:
I'm working on the contracts tutorial. Here's the code (including contract):

var greeterSource = 'contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) suicide(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }'

var greeterCompiled = web3.eth.compile.solidity(greeterSource)

var _greeting = "Hello World!"
var greeterContract = web3.eth.contract(greeterCompiled.greeter.info.abiDefinition);

var greeter = greeterContract.new(_greeting,{from:web3.eth.accounts[0], data: greeterCompiled.greeter.code, gas: 10000000000000}, 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);
    }

  }
})

On the top line, the contract source code is written without line breaks.

I have 4 ether for testnet:

> eth.getBalance(eth.coinbase)
4000000000000000000

You're welcome to send me some more:

> eth.accounts
["0x425434d3a0f5da79d60769f2400896f0d85b41ec"]

In the geth-1.4.6 console, I import the complete script from above using

> loadScript("/home/work/projects/contracts/tutorial_greeter/setup_greeter.js")
true

Compiling works, but why does it not have an address even when a number of blocks have been mined in the meanwhile?

> greeter
{
  abi: [{
      constant: false,
      inputs: [],
      name: "kill",
      outputs: [],
      type: "function"
  }, {
      constant: true,
      inputs: [],
      name: "greet",
      outputs: [{...}],
      type: "function"
  }, {
      inputs: [{...}],
      type: "constructor"
  }],
  address: undefined,
  transactionHash: null


texts:
transgerFrom function is showing error and always falied . please help.

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
    uint256 allowance = allowed[_from][msg.sender];
    require(balances[_from] >= _value && allowance >= _value);
    balances[_to] += _value;
    balances[_from] -= _value;
    if (allowance < MAX_UINT256) {
        allowed[_from][msg.sender] -= _value;
    }
    emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
    return true;
}


texts: Geth keeps changing coinbase / miner account and stops working. (POA Network)

texts:
I have set up a Geth POA network of 2 nodes on different cloud instances. Network was running good for 2 months but now suddenly it's getting connections from unknown peers and mining stops working.
Geth Command:
geth --datadir ethdata/ --syncmode 'full' --port 30312 --rpc --rpcaddr '0.0.0.0' --rpcport 8545 --rpccorsdomain '<URL1>,<URL2>' --rpcapi 'personal,db,eth,net,web3,txpool,miner,admin' --ws --wsport 8546 --wsapi 'eth,net,web3' --wsorigins '<URL1>' --networkid <NETWORKID> --gasprice '1' --unlock <ACCOUNT1> --password pass.txt --mine --etherbase <ACCOUNT1> --allow-insecure-unlock --nat extip:<NODEIP> --nodiscover --netrestrict <NODE2IP>/32

Error Logs:
0|ethNode1  | INFO [10-02|21:10:19.001]  mined potential block                  number=394283 hash="2ef239…81cd72"
0|ethNode1  | INFO [10-02|21:10:19.002] Commit new mining work                   number=394284 sealhash="3377da…5031cd" uncles=0 txs=0 gas=0 fees=0 elapsed="318.567µs"
0|ethNode1  | INFO [10-02|21:10:19.002] Signed recently, must wait for others
0|ethNode1  | INFO [10-02|21:10:29.002] Imported new chain segment               blocks=1 txs=0 mgas=0.000 elapsed="442.732µs" mgasps=0.000 number=394284 hash="0612d1…139ef9" dirty=0.00B
0|ethNode1  | INFO [10-02|21:10:29.003]  block reached canonical chain          number=394277 hash="825454…683852"
0|ethNode1  | INFO [10-02|21:10:29.003] Commit new mining work                   number=394285 sealhash="f90c28…da2cd8" uncles=0 txs=0 gas=0 fees=0 elapsed="268.822µs"
0|ethNode1  | INFO [10-02|21:10:39.000] Successfully sealed new block            number=394285 sealhash="f90c28…da2cd8" hash="7f408c…1fe2df" elapsed=9.997s
0|ethNode1  | INFO [10-02|21:10:39.001] Signed recently, must wait for others
0|ethNode1  | INFO [10-02|21:10:39.000]  mined potential block                  number=394285 hash="7f408c…1fe2df"
0|ethNode1  | INFO [10-02|21:10:39.002] Commit new mining work                   number=394286 sealhash="190914…a34e63" uncles=0 txs=0 gas=0 fees=0 elapsed=1.583ms
0|ethNode1  | INFO [10-02|21:10:43.852] Transaction pool price threshold updated price=1
0|ethNode1  | ERROR[10-02|21:10:43.854] Etherbase account unavailable locally    err="unknown account"
0|ethNode1  | WARN [10-02|21:10:43.854] Served miner_start                       conn=217.227.191.41:61800 reqid=1643 t=2.034872ms err="signer missing: unknown account"
0|ethNode1  | WARN [10-02|21:10:44.863] Gas estimation capped by limited funds   original=8000000 balance=98712 sent=78962 gasprice=1 fundable=19750
0|ethNode1  | WARN [10-02|21:10:44.864] Served eth_sendTransaction               conn=217.227.191.41:61805 reqid=1125 t=3.726913ms err="gas required exceeds allowance (19750)"
0|ethNode1  | WARN [10-02|21:10:45.755] Served eth_sendTransaction               conn=217.227.191.41:61807 reqid=831  t=4.255632ms err="authentication needed: password or unlock"
0|ethNode1  | INFO [10-02|21:10:49.002] Imported new chain segment               blocks=1 txs=0 mgas=0.000 elapsed="301.13µs"  mgasps=0.000 number=394286 hash="5ae579…8ae413" dirty=0.00B
0|ethNode1  | INFO [10-02|21:10:54.250] Deep froze chain segment                 blocks=6 elapsed=7.777ms     number=304285 hash="2951e1…0aa545"

Connection from IP Address "217.227.191.41" seems to be from an unknown node. I've set --nodiscover as well as --netrestrict. Also blocked the IP address from Firewall using command:
ufw deny from 217.227.191.41 to any

But still the issue keeps happening and when I reload geth command, it works for a minute but same issue happens again. I'm also blocking RPC access as you can see in the GETH command. How do I prevent incoming connection that changes my miner account?


texts: Do I need to buy Eth for the transaction?

texts:
recently I've completed my transaction from empowr to ether wallet about 1003 empowr coin in total. But, the real problem is that the money doesn't show up in my wallet. But in etherscan it shows that transaction is success.
Please help me guys..


texts: gas_estimate returning error for too man arguments

texts:
running Web3 5.13; python 3.9; Mac 10.15.7
Trying to run test on solidity contract based on the example provided in teh Web3.py docs. When running this I receive an error stating TypeError: estimate_gas() takes 2 positional arguments but 3 were given.
When I pass a specific value in for gas I do not receive the error. But I have not received this when running similar smart contract transactions. How can I resolve this?
The error is called on the tx_hash = LotteryContract.constructor().transact({ 'from': deploy_address, }) line.
import os
import pytest
from solcx import compile_source
from web3 import EthereumTesterProvider, Web3

@pytest.fixture
def tester_provider():
    e = EthereumTesterProvider()
    return e

@pytest.fixture
def w3(tester_provider):
    return Web3(tester_provider)

@pytest.fixture
def ether_tester(tester_provider):
    return tester_provider.ethereum_tester

@pytest.fixture
def compiled_contract():
    contract_path = os.path.join(os.getcwd(), 'lottery.sol')

    with open(contract_path, 'r') as f:
        source = f.read()

    return compile_source(source)

@pytest.fixture
def lottery_contract(w3, ether_tester, compiled_contract):
    contract_id, contract_interface = compiled_contract.popitem()

    deploy_address = ether_tester.get_accounts()[0]

    LotteryContract = w3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bin']
    )

    tx_hash = LotteryContract.constructor().transact({
        'from': deploy_address,
    })

    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, 180)
    return LotteryContract(tx_receipt.contractAddress)

def test_deploys_contract(lottery_contract):
    i = lottery_contract.functions.getPlayers().call()
    assert 1 == i

error:
self = <eth_tester.main.EthereumTester object at 0x7ff073b85c40>
transaction = {'data': '0x6060604052341561000f57600080fd5b336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff0219169083...ad680f662db6452e96bfca95e817c346bcc2a08a49e6f6726acd20ec3a70029', 'from': '0xaBbACadABa000000000000000000000000000000'}
block_number = 'latest'

    def estimate_gas(self, transaction, block_number="latest"):
        self.validator.validate_inbound_transaction(transaction, txn_type='estimate')
        raw_transaction = self.normalizer.normalize_inbound_transaction(transaction)
        self.validator.validate_inbound_block_number(block_number)
        raw_block_number = self.normalizer.normalize_inbound_block_number(block_number)
>       raw_gas_estimate = self.backend.estimate_gas(raw_transaction, raw_block_number)
E       TypeError: estimate_gas() takes 2 positional arguments but 3 were given


texts: Can I limit the amount a contract can spend of my token per day?

texts:
For some reason, I'd like to create a kind of token which is limiting the amount someone can send daily (calendar day in a particular country) to others.

The reference time should be the time of the request for the movement.

I guess it may work using now (I'm not 100% sure how, example code is welcome with basic token example https://ethereum.org/token#the-coin ).

The only other option I thought of, would be to provide the time in the transfert call, and eventually to sign it to prevent messing with it : it should then be issued outside of the blockchain, in a central manner, and signed from the contract owner for example ( see How can I sign a piece of data with the private key of an Ethereum address? ), so we can check it in the contract.
But I'd really like to avoid this if possible.


texts: Getting Addresses using a Path causes the error: Could not derive hardened child key

texts:
I am using ethereumjs-wallet npm package to generate a unique wallet address for each user. However instead of using the mnemonic/seed, a public extended key xpub will be used instead to keep the private keys secure.

However the following code which I used is throwing the error

  AssertionError [ERR_ASSERTION]: Could not derive hardened child key

The code works fine if we were to replace

const hdWallet = hdkey.fromExtendedKey("xpub...")

with

const hdWallet = hdkey.fromSeed("seed or mnemonic ...")

It appears to be a problem with the hdPath, but which exactly is the problem? And how can we solve it?

JS Code

var hdkey = require('ethereumjs-wallet/hdkey')

const hdWallet = hdkey.fromExtendedKey("xpub...")
const hdPath  = "m/44'/60'/0'/1/0"
const node = hdWallet.derivePath(hdPath)
const nodeWallet = node.getWallet()
const address = nodeWallet.getAddressString()
return address


texts: Is there a way to convert a regular address to an ICAP address?

texts:
The ethkey guide mentions how a regular address can be obtained from an ICAP address.  But it doesn't mention how an ICAP address can be obtained from a regular address.

  Occasionally, however, it's important to convert between the two.
  ethkey provides the inspect command for this purpose. When passed any
  address, file or UUID, it will tell you information about it including
  both formats of address.

Since most people already have regular hex addresses, can they be converted to ICAP without having to create new private keys?  Or is there a way to use ICAP without needing to create a new ICAP address and sweeping the funds to this new address?


texts:
I would like to but a bittrain coin. I have gone through the list and I cant find it ranking.

Can I buy it on this platform?


texts: String to float maintaining decimal places

texts:
I've seen some thread already however I haven't found anywhere a way of converting a string number to float number and maintaining the decimals.
ie
"27.546" to 27.546


texts: I sent 1 ETH to an ICO, tx receipt failed, value (Cancelled)

texts:
I sent 1 ETH to an ICO today without reading instructions. I sent it from my Coinbase account, so the ERC-20 cannot be retrieved on my end without Coinbase being super cool and sending them to me.
Question:
it is showing up as TX Receipt Fail and Value (Cancelled). Is there a chance it will show. Sick up into my Coinbase wallet so I can do this properly? Thank you for your help in advanced.

Link to tx overview at Etherscan


texts: change web3-js version used in javascript

texts:
In the node command, the web3 version used is 1.0.0 and the function like:

web3.eth.accounts.create();

is working properly but in my webpage running on ganache-cli(testrpc) the same command is not working and its reporting error

web3.eth.accounts.create is not a function

how can I change the web3js version of ganache-cli/ the version used by my javascript file?


texts: Hot to debug a contract method invocation?

texts:
Running this code:

PrintProofOfWork.methods.printRequested(gcodeHash).send({from: web3.eth.defaultAccount})
            .then((result) => {
                console.log(`result of the invocation: ${result})`);
            });

prints nothing. I have no idea how to debug and understand what was not successful, in Etherscan can not see the transactions that I try to perform.

What can I do?


texts: smart contract and permissioned blockchain

texts:
I have some IoT(Internet of things) nodes sharing the received data from sensors with each others. I partitioned them to 2 permissioned networks:
Network 1 includes: X,Y,Z nodes trusting each other.
Network 2 includes: M,N,O nodes trusting each other.

Can I define a smart contract to each network containing the list of nodes (their PK) that enables nodes to accept the data of only its own peers in own network?

For instance, smart contract 1 includes the PK of X,Y,Z and enable them share data with each other. smart contract 2 includes the PK of M,N,O and enable them share data with each other.

Due to some conditions, for changing these partitions, for example, moving node Z from network 1 to network 2.

Can I send update list of members to two smart contracts 1 and 2 to change automatically partitions as follow?

Precisely, the list of smart contract 1 is updated to X,Y,

and Node z plus its logical or Physical address is added to smart contract 2.
That is,now, in network 2,
M,N,O and plus new node Z can share their data with each other.
Regards


texts: ERC20 contract not able to transfer large amount of tokens

texts:
I am building an ERC20 Token. I want to the decimals properly so that people can do transaction in deciamls also.
So, I am trying to transfer 10^21 tokens from my address to another.

Minted tokens : 1000000 * (10**decimals) # decimals = 18

So, I should have 10^23 tokens in total.

So I should be able to transfer this amount?

I made a UI and used web3.js where I got this error.

Unhandled Rejection (Error):
invalid number value (arg="_price", coderType="uint256", value="1e+21")

Then I also tried in Remix for the same values. there also the transaction failed.

Execution is failing for numbers like if I want to transfer 10*20 token. then also the transaction fails.

What am I doing wrong?

Thanks for the help.


texts: Is it possible to manipulate maximum callstack size in solidity?

texts:
I'm a student learning about solidity language.

According to solidity's official docs, the maximum callstack size is 1024.

But, I am wondering, can a developer change the maximum callstack size in solidity?

If so, could you give me links to reference.

Thank you for reading.


texts: How can I verify ownership to allow resale of NFTs?

texts:
I have discovered NFTs and ETH recently and would like to build a marketplace like opensea but allows resale of NFTs that are already minted on various block chains(ETH, FLOW). Starting with just ETH, when some one comes to marketplace to sell their NFT,  I would like to :

Verify the ownership of NFT that the seller is claiming to resell on my marketplace. How do I do this? Can I take the seller’s wallet’s public information and query the blockchain somehow?
when the seller sends the NFT to the buyer and claims that he sent it, how do i verify that the nft was safely sent to the buyer’s wallet?

From what I have read so far, etherscan seems to have a way to keep track of transactions and also extract NFT metadata to verify ownership of the NFT, how can I do the same?


texts:
Bitcoin is capped at 21,000,000 BTC.

I cannot find any definitive answer on whether Ethereum is capped in the same way, or whether it can continue to release currency into the ecosystem indefinitely.

Can someone please shed some light on this?


texts: I have customized the go-ethereum code a bit, compiled and running on 3 nodes (1 miner 1 bootnode 1 fullnode) in my private-net. I just wondered that why should I initialize genesis.json on each node? Otherwise nodes did not found each other. Also, in the beginning, does a fresh node start to synchronize from genesis block or sth else? Here, I just want to understand how the ethereum node discovery works for a node alone? or do they know some nodes be default?


texts: Tx's not getting mined on private network

texts: I'm running my own private network - I have 3 pending tx in the pool that are still there 6000 blocks later. I have the miner gas threshold at 0. Any idea why the tx's arent getting mined?


texts: Why pending transactions cost so long time to be included in blockchain?

texts:
Could anyone explain why a pending transaction cost so long to be confirmed?
As my comprehension, it just need to wait atmost 12 blocks(less than 4 minutes) to get confirmed?

https://etherscan.io/txsPending list all the pending transactions, and lots of them are more than 1 hour in age, here is one of them.


texts: Web3-core-helpers error: Uncaught (in promise) Error: Provided address "undefined" is invalid,

texts:
When I launch the app with with react.. this error occur when my exchange contract is loaded..
Here is the code i wrote to talk to the blockchain:

export const loadBalances = async (dispatch, web3, exchange, token, account) => {
  const etherBalance = await web3.eth.getBalance(account)
  dispatch(etherBalanceLoaded(etherBalance))

  const tokenBalance = await token.methods.balanceOf(account).call()
  dispatch(tokenBalanceLoaded(tokenBalance))

  const exchangeEtherBalance = await exchange.methods.balanceOf(ETHER_ADDRESS, account).call()
  dispatch(exchangeEtherBalanceLoaded(exchangeEtherBalance))

  const exchangeTokenBalance = await exchange.methods.balanceOf(token.options.address, account).call()
  dispatch(exchangeTokenBalanceLoaded(exchangeTokenBalance))

  dispatch(balancesLoaded())
}

web3 v1.0.0 beta46
Truffle v5.0.5 (core: 5.0.5)
Solidity v0.5.0 (solc-js)
Node v9.10.0

Here is the error when i use the debugger

Update: The error i get when i update to web3 v1.2.1


texts: In solidity, how can you set a bytes variable to empty

texts:
I tried this

contract MyContract{
    bytes public data = 0x3333;

    function clearData(){
         data = 0x;
    }
}

But solc doesn't like me trying to set data to 0x


texts:
I am integrating the new coin, for this i need to create the ICAP address. In this address generation process, we need to generate the checksum, for this how i may create the checksum. example my client give this address XE98BCCCCRB100000000 and they said here 98 is checksum. we dont have idea how it is calculated can anyone help to this checksum process.

And also we need any library for creating checksum


texts: Mandatory to do a full sync for token creation and contract deployment?

texts:
As the heading says, is it mandatory to do a full sync for token creation and contract deployment?

I have downloaded the etherelum wallet and geth, and right now it is syncing as I write this post. But is it necessary to achieve all the features in the wallet?

What are the disadvantages of a lightly synced wallet (syncmode=light)?


texts: How can I apply an effect to an address for a set time?

texts:
I am using a dividend pool system for my token. Currently, when a user withdraws their dividends they have this line of code is run:

    emit Transfer(address(this), msg.sender, DividendstoDividend);
emit Transfer(address(this), address(0), DividendsToBurn);
_SavedDividend[msg.sender] = 0;
RestrictedFromDividend[msg.sender] = true;

Is there some sort of way I can make it so that the "RestrictedFromDividend" mapping only lasts for a certain period of time, and then have it switch back to false?

Edit : mapping not modifier


texts:
After reading this article ("The Unreasonable Ecological Cost of #CryptoArt" Part 1, Part 2),
I'm keen to better understand what are the factors involved in energy consumption by NFTs.
The article uses Gas consumption as an approximation to measure the carbon footprint of transactions and provides data about the gas consumed on different kinds of NFT transactions.
For a specific marketplace, it mentions the following averages (Part 2 > Footprint per transaction type -- note: the article doesn't provide specific references at this point but it is packed with references and research and I believe it's based on the analysis of transactions for the smart contracts of that marketplace):

Minting: 260K Gas
Bids: 75K Gas
Cancel Bid: 22K Gas
Sale: 160K Gas
Transfers: 95K Gas

As far as I can see, since Feb 2020 the average gas per transaction has always been around 60-70k (source) so that makes me wonder why some transactions take much more amount of gas (Minting, Sale).
My initial thought would be that NFTs could be sent and stored in the blockchain, similar to smart contracts but as far as I can see the content of NFTs is actually not stored in the blockchain (source).
Questions:

What are the factors involved in NFT gas consumption?
What are good strategies to minify gas consumption? I can think of 2 important ones: deploy on a blockchain network which is not based on PoW / Proof of Work (we're likely to deploy on Matic/Polygon, which is based on PoS) + minify the amount of transactions. Any other suggestions?


texts: What are digital tokens? How are various tokens generated on Ethereum?

texts: I've heard in various talks, Ethereum can generate any token (besides ether), representing anything from bitcoin (through btc-relay), litecoin, dogecoin, digital assets, shares, ownership representation or other crypto coins.  How is this done? How can Ethereum distribute other digital tokens as a reword for mining and supporting the network?  Is this possible now or only when Serenity is implemented?


texts:
I have parity install on my Mac, even though I removed it via application folder. It's still running in the background. How can I remove it completely from my computer?

My localhost 8080 keeps routing to parity.


texts: Geth client shows old balance, can't transfer eth

texts:
I recently transferred some eth from my account to another (Kraken specifically to exchange it). That worked, then a couple days later I tried to transfer more, the geth console returned the same output (some sort of transaction id), but the other account never received it. I tried removing my ~/.ethereum folder and restarting geth to see if it was a problem with its state, but that didnt't help. Now it shows the old balance (before my first successful transaction), and I still can't transfer eth. Etherchain.org and others reflect the correct value.

Any ideas what would cause this? Here is my geth version:

Geth
Version: 1.4.6-stable
Protocol Versions: [63 62 61]
Network Id: 1
Go Version: go1.6.1
OS: linux
GOPATH=
GOROOT=/usr/lib/go-1.6


texts: CompilerError: Stack too deep, try removing local variables. -

texts:
i am trying to compile my contract and running into this issue: CompilerError: Stack too deep, try removing local variables. I am not really sure how to fix it. Below is my code that is throwing the error:
    function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
        (uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLottery, uint256 tLiquidity) = _getTValues(tAmount);
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 rLottery, uint256 rLiquidity) = _getRValues(tAmount, tFee, tBurn, tLottery, tLiquidity, _getRate());
        return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tLottery, tLiquidity);
    }

    function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
        uint256 tFee = calculateRewardFee(tAmount);
        uint256 tBurn = calculateBurnFee(tAmount);
        uint256 tLottery = calculateLotteryFee(tAmount);
        uint256 tLiquidity = calculateLiquidityFee(tAmount);
        uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
        return (tTransferAmount, tFee, tBurn, tLottery, tLiquidity);
    }

    function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tLottery, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256, uint256, uint256, uint256) {
        uint256 rAmount = tAmount.mul(currentRate);
        uint256 rFee = tFee.mul(currentRate);
        uint256 rBurn = tBurn.mul(currentRate);
        uint256 rLiquidity = tLiquidity.mul(currentRate);
        uint256 rLottery = tLottery.mul(currentRate);
        uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
        return (rAmount, rTransferAmount, rFee, rBurn, rLottery, rLiquidity);
    }


texts: How can I transfer ownership to another contract?

texts:
I have a contract which inherits from contract Claimable by OpenZeppelin (see here):

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

contract MyTestContract is Claimable {
    uint256 public id;
    function set(uint256 _id) external onlyOwner {id = _id;}
}

The purpose of course is to restrict the calling permission for function set.

This function can be called only from the account which I use in order to deploy the contract.

After deployment, I would like to transfer ownership from this account to another contract.

The reason for this is not a part of my question, but for all it matters, I need to enforce multiple-signature on the function, and allow it to be executed only after X out of Y permitted users have submitted a request. Hence I need to transfer the ownership of the contract from my account to a MultiSig contract by Gnosis (see here), which I deploy myself.

The issue which I am having a problem with and cannot really wrap my head around, is how to transfer ownership to something which is "not exactly an account".

When I transfer ownership from my account to another account on the network, it works fine.

For example, I set up a Ganache network with 8 accounts, and then run this Truffle test:

contract('MyTestContract', (accounts) => {
    it('Transfer Ownership', async () => {
        let   myTestContract = await artifacts.require('MyTestContract').new();
        let   owner = await myTestContract.owner();
        assert(owner === accounts[0]);
        await myTestContract.transferOwnership(accounts[1]);
        await myTestContract.claimOwnership({from: accounts[1]});
        let   newOwner = await myTestContract.owner();
        assert(newOwner === accounts[1]);
    });
});

But when I transfer ownership from my account to the address of a contract which I deploy into the network, Truffle reports:

  Error: sender account not recognized

Now, the error by itself makes sense, because there is no such account on the network.

So my question here - is it even possible to do what I'm trying to achieve?

I feel that I have some fundamental misunderstanding of the difference between accounts and contracts, which I'd be very grateful if someone could clarify for me.

Thank you very much!

UPDATE:

To clarify, this is how I transfer ownership to the MultiSig contract:

await myTestContract.transferOwnership(multiSigContract.address);
await myTestContract.claimOwnership({from: multiSigContract.address});

And by the way, when I use Ownable instead of Claimable, i.e.:

On-Chain Code:

contract MyTestContract is Ownable {...}

Off-Chain Code:

await myTestContract.transferOwnership(multiSigContract.address);

The ownership-transfer completes successfully, and the MultiSig contract is the only one which can call the set function.

So the problem is essentially at:

await myTestContract.claimOwnership({from: multiSigContract.address});


texts: How to correctly account for transaction costs when swapping from one ERC-20 token to another using for example the Kyber network?

texts:
If I for example have 5 KNC (an ERC-20 token) and would like to swap them for x amount of DAI (another ERC-20), this would on the Kyber network, as far as I understand, be achieved via two conversions: first KNC to ETH followed by ETH to DAI.

Given the ask and bid rates of the involved pairs, the resulting DAI quantity obtained from 5 KNC would then, without any transaction fees, be:

DAIQTY = (KNCQTY × ETH_KNCBid rate) × (1 / ETH_DAIAsk rate)

My question is: how do I modify this expression to correctly account for transaction fees?

Are there two separate transaction fees since I have two swaps? The Kyber API can return the expected gas limit needed for a token2token swap (expressed in ETH), but I’m not sure how to apply it when calculating the expected token amount received given an input token amount.


texts: Error deploying new contract in Javascript using Meteor and TemplateVar

texts:
I am trying to create a new contract on button click using Meteor and TemplateVar. The relevant code is:

Template.Borrower.events({
  'click button'(event, instance) {
    // Create new Borrower
    var _borrower = "ABC"

    alert("I am working on it...")

    web3.eth.accounts.wallet.add("0x...");

    var newBorrower = web3.eth.contract(borrowerABIArray).new(_borrower,{from:eth.accounts[0],data:borrowerData,gas:500000}, function(err, newContract){
    if(!err) {

      if(!newContract.address) {
        alert("Contract transaction sent: TransactionHash: " + newContract.transactionHash + " waiting to be mined...");

      } else {
        alert("Contract mined! Address: " + newContract.address);
      }

    }
});

I don't even get an error, it just displays the first message "I am working on it..." and then nothing. I am logged into Metamask so my wallet is unlocked but I did try unlocking it as well and that did not work either.

When I deploy the contract directly with Remix it takes less than 300000 gas so it can't be a gas problem.

Thanks for your help.


texts: ERC20 Anyone can call approve if knows ABI on contract and my address?

texts:
I think I misunderstand something. I'm using a Ganache for developing dApp. I built a default ERC-20 smart-contract. I've built it with truffle. And just for test I write some code in NodeJS:

        const res = await contract.methods
            .approve('0xbB5fed33E455bA3efB1a6622c388A9aDaD9D9EB5', this.web3.utils.toWei('10'))
            .send({
                from: '0xD73292923DA1Fc18b04fADC4a004bb7dffB5f7Ca'
            });
        const tr = await contract.methods
            .transferFrom(
                '0xD73292923DA1Fc18b04fADC4a004bb7dffB5f7Ca',
                '0x460923eA0B788cBF8921f1cd1a696D3de7Fd487a',
                this.web3.utils.toWei('10')
            )
            .send({ from: '0xbB5fed33E455bA3efB1a6622c388A9aDaD9D9EB5' });

And this code works perfectly. Is it means that anybody who knows my address and ABI of a contract can call the same code in Main Network (Ethereum). Because all this information (ABI and my address) is public. I think it's quite silly question, but I can't find an answer. What I'm missing?


texts: How to find confirmation info in ethers.js？

texts: How can I find the confirmation information in ethers.js api? I cannot find such kind of function.


texts:
During the course of the Tezos ICO,

By mistake, send the Tezos ICO addresses Ethereum at the Bithumb exchange exchange address.

It's vaporized.

Is there any way I can find it?

Please help me.


texts:
My smart contract has pragma solidity 0.4.18;
According to Solidity: Best practices - Which compiler version should I use? Advantages / Disadvantages, this pragma will work on any compiler from 0.4.18 and upwards.
$ truffle version
Truffle v5.1.65 (core: 5.1.65)
Solidity v0.5.16 (solc-js)
Node v14.15.4
Web3.js v1.2.9
$ truffle compile

Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\Wrestling.sol

CompileError: /F/hackernoon/contracts/Wrestling.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.4.18;
^---------------------^

Error: Truffle is currently using solc 0.5.16, but one or more of your contracts specify "pragma solidity 0.4.18".
Please update your truffle config or pragma statement(s).
(See https://trufflesuite.com/docs/truffle/reference/configuration#compiler-configuration for information on
configuring Truffle to use a specific solc compiler version.)

My compiler version is 0.5.16, which I think is greater than 0.4.18. But truffle fails to compile my file.
I checked https://github.com/ethereum/solc-bin/blob/gh-pages/bin/soljson-v0.5.16%2Bcommit.9c3226ce.js, it doesn't look like a nightly build.
What caused the error?


texts: Copy Geth full node onto external drive then continue syncing

texts:
My 1TB internal SSD on my mac doesn't appear to be enough for a full sync with state data. I know I can fast sync but I need full state data. I'm currently on block 5.2million and its at around 900GB so I'm not gonna make it to current blockheight of 7.6million before my internal is full.

I bought an external 4TB SSD and would like to copy my current 900GB of full node data. It's taken almost a week to sync this 900GB so starting over on the external would suck.

I tried copying over the geth chaindata and keystate folders and then running geth with --datadir parameter pointing to the copied data on the external, but it just started resyncing from block 0. Maybe I did something wrong or maybe this just isn't supported?

Appreciate any info on how to do this.


texts: Transaction hash using web3.py received but variable state not changed

texts:
Trying to send a value to function and set it to a variable.

Making transaction using

txn = contractInstact.transact({
        'from':
Web3.toChecksumAddress("0xc5ce5f52ab724a2996aab373a14c21c3b9c8ece7"),
        'gasPrice': 500000
    }).makeInvestment(1)

 # https://github.com/ethereum/web3.py/blob/master/docs/examples.rst
 # FUNCTION from documentation mentioned above wait_for_receipt

 receipt = self.wait_for_receipt(txn, 1)

What I am missing to complete the transaction using Web3.py
because in this function  makeInvestment

import "./Relayer.sol";

uint public totalInvested;
bool investmentLaunched;
Relayer relayerObj;
address owner;

// mapping of amount invested by a peer
mapping (address => uint) private peerAmount;

// mapping of peers who invested
mapping (address => uint8) private isInvestedPeer;

// addresses of all invested peers
address[] private investedPeers;

// addresses of all peers
address[] private peers;

constructor() public{
     owner = address(0);
     totalInvested = 0;
     investmentLaunched = false;
     relayerObj = Relayer(0x8B23dEe880Fe20781655734b519dFB0E047020Ad);
 }

function makeInvestment(uint _amount)
    public
    returns(bool) {
    owner = msg.sender;
    if(validatePeer(owner) == true){
        if(isInvestedPeer[owner] == 0){
            investedPeers.push(owner);
            isInvestedPeer[owner] = 1;
        }
        peerAmount[owner] += _amount;
        totalInvested += peerAmount[owner];
        if(investmentLaunched == true){
            if(investedPeers.length == peers.length){
                relayerObj.triggerEvent(totalInvested, owner);
                return true;
            }
        }
        else{
            relayerObj.triggerEvent(totalInvested, owner);
            return true;
        }
    }
    return false;
}

// Where validatePeer function (returns bool) is to verify if peer exist in peersAddress array

And this totalInvested variable is Public
called in python as

print(peer_wallets_instance.functions.getTotalInvestedAmount().call())

but problem this returns 0 (zero).

Thanks


texts: How to design a GUI/webpage that can interact with my deployed contract?

texts:
At the moment I'm using MyEthereumWallet, testrpc and MetaMask to interact with my contract deployed on testrpc. So, I'm using only "contract" tab of "MyEthereumWallet", but I'd like to change the background and etc, so it looks more customized.

Question 1: How can I design a GUI, like MyEthereumWallet, that allows me to interact with my deployed contract?


texts: Geth eth.syncing returns false, admin.peers mostly empty and the ancientdb just reset out of the blue. Help?

texts:
My start command is as followed:
geth --syncmode fast --mine --miner.threads=15 --cache=4096 --miner.etherbase 0x0467f8979845f87614d36abe7de8fbb1968f919f

Output:
> eth.blockNumber
0
> eth.syncing
false
>

What am I doing wrong here? I am from Austria, if that changes anything?
Version:
Geth
Version: 1.10.1-stable
Git Commit: c2d2f4ed8f232bb11663a1b01a2e578aa22f24bd
Architecture: amd64
Go Version: go1.16
Operating System: linux
GOPATH=
GOROOT=go


texts: How do i withdraw Eth from a contract i created

texts:
New to blockchain.. havent a clue.. I managed to create a new contract with Eth. I moved money from MyEtherum Wallet to Metamask and into a contract, somehow? I have no coding experience but need someone to help with getting my Eth back out of the contract..
From looking around myetherwallet i found a ABI/JSON interface and now wondering if this is where the withdrawal code goes. If so anyone any idea what it might be?
Is this the correct way to withdraw Eth from a contract to a wallet?
Im new at this.. have no clue.
Using 'MyEtherwallet' and 'Metamask'
Also have the address of the contract.
Many thanks


texts: Can't very contract on created in Ethereum Wallet using Etherscan,

texts:
Used the following code, put it in to deploy new contract.

When I try to verify the code on etherscan it says it doesn't match the code of the contract?

Here's the Etherscan Link:

https://etherscan.io/address/0x84f7f794867642a47ce577fe0d9745da6ac37c44

And here's the code I inserted in the deploy contract part of the Ethereum wallet.

pragma solidity ^0.4.16;

contract MyKidsEducationFund {
  string public constant symbol = "MKEF";
  string public constant name = "MyKidsEducationFund";
  uint8 public constant decimals = 18;

  address owner = 0x3755530e18033E3EDe5E6b771F1F583bf86EfD10;

  mapping (address => uint256) public balances;

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

  function MyKidsEducationFund() public {
    balances[msg.sender] = 1000;
  }

  function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value);
    require(_value > 0);
    require(balances[_to] + _value >= balances[_to]);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    Transfer(msg.sender, _to, _value);
    return true;
  }

  function () payable public {
    require(msg.value >= 0);
    uint tokens = msg.value / 10 finney;
    balances[msg.sender] += tokens;
    owner.transfer(msg.value);
  }
}


texts: Can an ABI be embedded into a smart contract?

texts:
So one of the most unfriendly things about Ethereum is that every time I want to interact with a contract I need to load up the ABI from an external, centralized source.

Sure Parity lets me save these ABI's once loaded, but MEW does not when I use a Ledger Nano S.

Is there a way to embed the interface into a part of the smart contract so that they are more like web apps, where the user simply browses to the address and then has immediate full access to the smart contract without needing to search online for ABI's.

Case in point, look up CryptoDerivatives and look up their faq for adding contracts, each time you make a sell contract you must add the ABI from these external sources. Without a centralised website these smart contracts would be very much unusable for people such as myself.


texts: how blockchain can handle the concurrency?

texts:
I read some pages here about concurrency but I didn't give my answer, actually I am new to Bchain, consider this scenario:

There is a game contract on the blockchain for 4 Players, so far three players are registered to the game and there is only one remaining! for example two different people from two different regions want to Enter to the game. And both of them connect to two different nodes(miner). So in every single node the contract can compare the remaining players and let the guy be in. But at the end there are two players are registered while there were only one position remained.

1- are these type of scenarios possible in blockchain??

2- what is the solution?

if it was a centralized system I could block the code by lock, semaphore, etc but here the code are distributed on every single miner, I mean each request for transaction is sent to different miner.
Thanks

EDITED
if both of them enter to this code in two different miners and both miner just see that the count is less than 4 so they add the sender to the list and return "ok"..!!!!

function AddPlayer(string name) public returns(string)
{
if (PlayersCount < 4)
{
PlayersCount ++;
// add he address of player to a list and …..
return "ok";
}

EDITED 2

1- On how many nodes should this code be runned? I mean after sending the request from frontend application to this function it just return to me a true or false, right or wrong? So if it returns a true/false What is the broadcating? it is something like simple RPC. a function is called and the result is returned!!

2- what do you mean exactly by broadcasting transaction, does this "addPlayer" function call another "addPlayer" on the other node?? there isnt anything like this in the code,

3- I read something about validate the transaction, can you tell me how this function be validated after execution? does it need another function to validate it

Sorry for long questions , I really need the answers.


texts: abstract way of calling internal function instead of `this.call(callData)`

texts:
In Solidity I can call an internal function (inside the same contract that is calling it) the "usual" way:

myFunc();

or I can call it via .call, as discussed here or here:

callData = bytes4(sha3("myFunc()"));
this.call(callData);

(similarly also with appending parameters to callData).

The drawback of the second option is that it costs significantly much more gas (CALL is much more expensive than JUMP) and requires myFunc to be an externally available function - which could be fixed with an onlySelf modifier as suggested before.

The advantage of the second option is, that it allows for abstraction: A function (and it's parameters) could be provided dynamically and only be known at run-time. This would allow features similar to function pointers. Is there a way (potentially via inline assembly?) to call an internal function with the callData bytes instead of the explicit function name and parameters that have to be known at compile time without using the expensive .call?


texts: Should I use mainnet node provided by infura or create my own?

texts:
I am trying to implement a solution in my current system where payments can be made via ethereum main network. I have done some research and found out that I have two options of implementation:

Use node provided by infura.

Create and maintain my own node with go Ethereum client and connect with mainnet through it.
I just want to conduct transactions with this node. I don't need to implement custom smart contracts.

I know that the first option is a lot less work but is it reliable? Can I depend for all my transactions on the provided node?
What would be the advantages or disadvantages of both?


texts: How to modify the gasLimit of the private block chain on the console

texts: as the title,How to modify the "gasLimit" of the private block chain on the console?