texts: How can I create array of array contains characters with solidity

texts:
I recently approached the Smart contract two days ago. I'm still learning about it, and I have a lot of difficulties. Can you help me to create a variable like this photo?

It has a arrays of numbers from 1 to infinity. Each natural number has a array of characters. Each character has array of string, like ["abc","qwe"]

For example I have 2 functions:

One for add data, like addString(uint number, uint character, string
info)
One for get data, like getString(uint number, uint character)

When I call addString(1,"a","abc"). It will create "a" if it does not already exist, after that it will put "abc" to array.

When I call addString(1,"a","qwe"). it will put "qwe" to array. Now the array of "a" like ["abc","qwe"]

When I call addString(1,"b","abc"). It will create "b" if it does not already exist, after that it will put "abc" to array. Now the array of "b" like ["abc"]

When I call getString(1, "a"), It will return ["abc","qwe"]

When I call getString(1, "b"), It will return ["abc"]

When I call getString(1, "c"), It will return []

This guy has problems almost like me. You can view this

Thanks for helping me


texts:
Maybe stupid question, but just want to be sure before deploying contract on main net. In my contract user can change his name(:string) to whatever he likes.
Is it totally safe? I mean, is here some chance of 'overflow' string, change any other variables through that or something similar as SQL Injection?
Thanks.


texts: Gas requirement of function client.() high: infinite

texts:
I've tried fix that problem. but still i don't know what was wrong

If someone can fix this problem, please save me. I'm still trying this.

below sample code

contract HelloWorld {
    uint private simpleInt;

    function GetValue() public view returns (uint) {
        return simpleInt;
    }

    function SetValue(uint _value) public {
        simpleInt = _value;
    }
}

contract client {
    address obj ;

    function setObject(address _obj) external {
        obj = _obj;
    }

    function UseExistingAddress() public payable returns (uint) {
        HelloWorld myObj = HelloWorld(obj);
        myObj.SetValue(10);
        return myObj.GetValue();
    }
}

when i tried to created contract HelloWorld first and next created contract client. I executed setValue method first with that parameter and I got error when i executed useExistingAddress method

I use Geth window version in my computer and show you genesis.json

{
  "config": {
    "chainId": 15,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
  },
  "nonce": "0x0000000000000042",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0xffffffff",
  "difficulty": "0x200",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0100000000000000000000000000000000000000",
  "alloc": {}
}

this is my geth command in .bat file

start geth --networkid 15 --nodiscover --maxpeers 0 --datadir "D:\myeth\chaindata" --rpc --rpcapi "eth,web3,miner,admin,personal,net" --rpccorsdomain "*" --unlock 0,1,2,3 --password "D:\myeth\pass.txt"
start geth attach rpc:http://127.0.0.1:8545

and this is state when i executed setObject function.

I have a question. I set gas limit 30000000. but when i executed setObject function and check logs, gas and transaction cost were same. Is this normal?

please help me.


texts:
I am using php to connect RPC server. In localhost, everything works fine. I moved my files to host to test and I realised that $geth->Method_Name() is not working.

If I print_r($geth), here is the result.

  GethApi Object ( [_options:protected] => Array ( [version] => 2.0 [host] => 165.227.103.219 [port] => 8545 [assoc] => 1 ) [_address:protected] => http://165.227.103.219:8545 [_id:protected] => 0 )

But if I wanna get block number with $geth->eth_blockNumber() here is the result in localhost:

4495121

But in php server:

  Fatal error:  Uncaught exception 'RuntimeException' with message 'Failed to connect to 165.227.103.219 port 8545: Connection refused' in /home/crypuekb/public_html/GethApi.php:86

    | Stack trace:
    | #0 /home/crypuekb/public_html/GethApi.php(152): GethApi->;__call('eth_blockNumber', Array)
    | #1 /home/crypuekb/public_html/geth.php(14): GethApi->eth_blockNumber()
    | #2 /home/crypuekb/public_html/php/db.php(7): require_once('/home/crypuekb/...')
    | #3 /home/crypuekb/public_html/register.php(4): include('/home/crypuekb/...')
    | #4 {main}
    | thrown in /home/crypuekb/public_html/GethApi.php on line 86

Here is the line 86:

throw new \RuntimeException(curl_error($curl), curl_errno($curl));

I am using this command to start geth server:

geth --rpcapi "web3,eth,personal"  --rpc --rpcaddr "0.0.0.0" --rpccorsdomain "*" --light

As I said, everything works perfect on localhost.. Also my php server and ethereum server is based on different hosts. And I tried my php codes at three different hosts.


texts: Deploying multiple contracts with web3js 1.0 at once

texts:
I'm new to Nodejs and Ethereum so I apologize in advance for any obvious mistakes.

I want to deploy multiple contracts in advance to have addresses ready when they are needed.

I use this to deploy the contract:

depositContract.deploy({
    data: contractCode,

})
.send({
    from: ownerAddress,
    gas: 4000000,
    gasPrice: gasPrice,
}, function (error, transactionHash) {

    if(error) console.log(error);

    console.log('HASH');
    console.log(transactionHash);

})

which works fine so far if I only deploy one contract. If I try to deploy multiple ones with a for loop I get the error:

Error: Returned error: known transaction:

Does anyone know how to solve this?

Thanks in advance


texts:
I am new to Ethereum and i'm building a dapp by following this tutorial here

https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f

I have started geth node in Ropsten network and synced it in fast mode. I'm trying to deploy the contract to Rospten using Truffle framework, but i get the following error (while executing Truffle migrate method)

 insufficient funds for gas * price + value

I understand that this error arises due to lack of ether in my account but i do have a ether in my account that is in the Ropsten network (https://ropsten.etherscan.io). I get 0 when i execute getBalance()

My Account: 0xed055cd2c74efe8f00eb1d0657eb84b2a77ae6d7

Geth node start:

     geth --testnet --syncmode "fast" --rpc --rpcapi db,eth,net,web3,personal --cache=1024  --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --bootnodes "enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303"

truffle.js:

 // Allows us to use ES6 in our migrations and tests.
 require('babel-register')

 module.exports = {
   networks: {
     development: {
       host: '127.0.0.1',
       port: 8545,
       from: "0xed055cd2c74efe8f00eb1d0657eb84b2a77ae6d7",
       network_id: 3, // Match any network id
       gas: 470000
     }
   }
 }

Block number containing Transation of Ether : 2871859 https://ropsten.etherscan.io/block/2871859

and Transaction Receipt: https://ropsten.etherscan.io/tx/0x790efa1cec9c2cb6b245da9b13460e0d5214f41f21c197512ef2de2ebbcaa6ff

Downloaded Block data inside geth:

and Transaction Receipt:

eth.syncing

 {
   currentBlock: 2871991,
   highestBlock: 2872011,
   knownStates: 29461297,
   pulledStates: 29458752,
   startingBlock: 2871862
 }

getBalance in Truffle Console:

As you can see I have downloaded the block with my transaction and i have also tried downloading my block in syncemode "full".

I get the same result even when eth.syncing returns false.

I understand that there are already questions like this... but i have tried every one of their answers and its not working...

What am i doing wrong?

Any help would be appreciated...


texts: Is it feasible to have a coffee shop accepting ethereum?

texts: I know that there are transaction fees involved in ether transactions. What if want to have a coffee shop which sells coffee of 1$(dollar) value in ether. Is such a thing feasible considering the transaction fees involved? What would be the transaction fees in such case? Would miners consider mining such small transactions?


texts: How to deploy a contract using metamask and the callback?

texts:
I'm trying to deploy a new contract with metamask (in my javascript frontend app). The problem is that, when the receipt is returned, the address is "undefined" since, I suppose, the transaction is not already mined and so the address not exists yet. The deploying result is:

Contract {_eth: Eth, transactionHash:
"0x9e3866f52f274874d96bf60932c03d9849ccdb2cef97c010d6b84c5b529768de",
 address: undefined, abi: Array(22)}
 abi:(22) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
 address: undefined
 transactionHash :"0x9e3866f52f274874d96bf60932c03d9849ccdb2cef97c010d6b84c5b529768de"
 _eth: Eth {_requestManager: RequestManager, getBalance: ƒ, getStorageAt: ƒ, getCode: ƒ, getBlock: ƒ, …}
 __proto__:Object

Moreover, if I try to access to the mining state into _eth > mining the output is:

[Exception: Error: The MetaMask Web3 object does not support synchronous methods like eth_mining without a callback parameter. See https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#dizzy-all-async

The Javascript code is:

deployContent = (name, author, genre, cost) => {
  return new Promise((succ, rej) => {
   this.web3.eth.contract(Content.abi).new(name, author, genre, cost, {gas: 400000},
    (err, res) => {if(!err)succ(res); else rej(err);});
  })
}

deployAndPublish = async (name, author, genre, cost) => {
    let contRes = await this.deployContent(name, author, genre, cost);
    console.log(contRes);
    console.log(contRes.address);
    // I need the address here in order to push it into an array
}

Any idea how to wait for the address?


texts:
I am working on an dapp (private blockchain) wherein users can exchange fiat currency for a token. The token can then be exchanged for particular goods and services, for example: groceries, health, transport, bills and so on. At the outset of the transaction, the sender can opt for the token to be linked to particular good or service. Alternatively, they can create a blank token, and have the sender decide what goods/service to link the token to.

The purpose of the application is to facilitate trust between two parties wherein the sender requires the receiver to spend the funds for a particular purpose. For example, an individual working in Italy can send back a set of tokens (2x grocery, 1x transport, 1x bill) to family back home in South Africa, who can then spend it as requested.

With the above outline in mind, I wanted to ask how an individual token would be valued. Given the nature of the system, it doesn’t seem sensible for the token to be volatile and traded on the open market. Furthermore, given the fact that the token to be consumed within the context of business partners (eg retailers,  public transport services and utility companies => who can then exchange it for fiat) all across the world, how do I go about determining the exchange rate of token => goods, services in each country? Also, do any dapps exist which perform this function?


texts:
We are working on a crypto exchange and need to organize deposits and withdrawals.
How would we organize our wallet?
The only HD Wallet I found so far is https://www.npmjs.com/package/eth-hd-wallet.
I am trying to figure out what is the capability/function of a wallet and what we need to implement our self.
For deposits I need to be able to create new addresses for customers. Is the wallet capable of giving me new unused addresses or do I need to write an iterator myself and keep track of the address usage?
For withdrawals I need to create a transaction - do I need to specify sender addresses myself or can the wallet do it automatically?
What are the best practices/design patterns for this? What additional libraries could be useful?
Is a HD Wallet a good idea or should we maybe just keep track of all the addresses?


texts: What if a service provider deletes the smart contract

texts:
As we know, smart contracts are used for agreements between non-trusting parties. So let's take an example of an insurance provider creating a smart contract for a customer with the smart contract containing the all the terms of insurance. He then shares the address and json interface with the customer so that the customer can verify the contract on the blockchain, call the function "SignTheTerm(customer_address)" and the function transfers the premium to the insurance_provider_address. But in this case, since the insurance provider has created the smart contract, doesn't he have the control to go and delete it? Contract is gone and the customer loses money.

Any ideas on how this can be prevented and where I am going wrong in the use case?


texts:
I have been learning Solidity and I have run into a scoping issue with the structs. I thought by default, all properties of a struct are put into storage. When I try to add the battles variable as an argument, it is not identified by the EVM compiler. Why is this? Thanks.

struct TargetCoreBase {
uint hp;
uint levels;
uint AlienCount;
uint TargetAliens;
uint LossCounter;
uint WinCounter;
uint battles;
}

TargetCoreBase[] target;

mapping(uint => address) base;

        address owner = msg.sender;

function CreateTarget(string _hp, uint _levels, uint _AlienCount, uint _TargetAliens, uint _LossCounter, uint _WinCounter, uint _battles) internal {
       require(msg.sender == ownerOf(_CoreBaseId));
       uint TargetId =  target.push(TargetCoreBase(_hp, _levels, _AlienCount, _LossCounter, _WinCounter, 0));
       base[TargetId];
    }

string TargetCoreBaseErr = "No CoreBase level";

function CheckTargetPairing(_battles) returns (bool) {
   if(TargetCoreBase.battles = 0) {
       return true;
   }
   else {
       return false;
   }

UPDATE

I have the right number of arguments now, but the problem still persists. In fact, replacing _battles with any of the other struct variables returns the same result of - "identifier not found".


texts:
I like to code smart contracts using python for my project.
I done a project using Flask web framework in python. I like to implement the same project in ethereum block chain. Where can I learn the python library for the ethereum access. or is there any tutorial videos for this. Thanks in advance


texts:
I am trying to understand what is the "workflow" (for the lack of a better word) of an ERC token in.  Looking at this guy (nothing special about it, just a randon token), I can see that the first sucecssfull transaction on that contract is this one where an account (that starts with 3dc) called the Transfer function on contract and transfered 1 token (from its balance I believe) to an account that starts with "1caa". And then several hundred token transfers followed.

Im wondering how did account 0x3dc... have the token in the first place? I have been trought its transactions on etherscan and it never transfered ether to the contract.

Also, am I correct to assume that accounts get tokens by simply making ether transfers to the token's contract them, assuming the contract implement a payable function, the contract will get the ether and then updates the account's token balance on its "balances" variable?

Thanks


texts: Where can one get token fee calculations instead of it keep eating up my ETH for gas for guessing the gas limit?

texts: This is kind of ridiculous, every time I try to send out tokens to another address from metamask, it fails. I doubled my GAS limit from 20K to 70K and it still fails. Where can one even find the appropriate GAS limit setting? Every time it fails it eats up my eth which is not cheap for sending tokens at .20-.50 USD.


texts:
I am working on a web application backend (completely unrelated to Ethereum) that returns XML in response to certain queries. I have just set up the environment again and came across something weird: displayed in the first tag in the root tag was a <script>, which clearly has no business being there. It looks like this:

<script>
/*global Web3*/ cleanContextForImports() require('web3/dist/web3.min.js') const LocalMessageDuplexStream = require('post-message-stream')
[... too long ...]
</script>

I thought the code was broken, but on inspection it was MetaMask javascript code. I have MetaMask installed and running, but this is strange. Does MetaMask rewrite all pages like this? And why would it rewrite XML files, does it not detect HTML? The Content-Type is text/xml.


texts: Understanding how a simple contract breaks into bytecode

texts:
I'm trying to understand how contracts look in terms of bytecode and struggling to do that just based on the yellow paper. In particular, consider the following empty contract:

pragma solidity ^0.4.17;

contract Simplest {
}

Using the Remix compiler, I'm able to compile into the following bytecode:

6080604052348015600f57600080fd5b50603580601d6000396000f3006080604052600080fd00a165627a7a7230582053a24015f887e1dd9fbd5e5cadb397bb5fb34e8aab7b5782d9e28dfd4e9862810029

Which translates to the following op-codes:

PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x35 DUP1 PUSH1 0x1D PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN STOP PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT STOP LOG1 PUSH6 0x627A7A723058 KECCAK256 MSTORE8 LOG2 BLOCKHASH ISZERO 0xf8 DUP8 0xe1 0xdd SWAP16 0xbd 0x5e 0x5c 0xad 0xb3 SWAP8 0xbb 0x5f 0xb3 0x4e DUP11 0xab PUSH28 0x5782D9E28DFD4E986281002900000000000000000000000000000000

1) What does this represent? Is this meant to be the bytecode for the constructor function?

2) There are several sequences which don't make sense to me, in particular:

ISZERO 0xf8 DUP8 0xe1 0xdd SWAP16

Why are 0xf8, 0xe1, 0xdd following opcodes that don't take any arguments? What is their purpose?

3) Once the contract is compiled, where is the bytecode for the "functions" of the contract?

I suspect the 3 questions are quite linked hence asking them together.


texts: Compiler solc expected a state variable declaration

texts:
I try example from book Mastering Ethereum:
contract Faucet {
    function withdraw(uint withdraw_amount) public {
        require(withdraw_amount<=10000000000000000);
        msg.sender.transfer(withdraw_amount);
    }
    function () public payable {}
}

Is error:
Error: Expected a state variable declaration. If you intended this as a fallback function or a function to handle plain ether transactions, use the "fallback" keyword or the "receive" keyword instead.
--> Faucet.sol:6:32:
|
6 |     function () public payable {}
|                                ^

Compiler solc is in version 0.7.4.
How correct it?


texts: Issue with contact deployment on etherscan

texts:
I have created a new token and deployed it on Ropsten Network using Metamask. I have also followed the norms of ERC20 Token Standard.

Now, when I am trying to find my token using Contract address on EtherScan (Ropsten) ERC20 Token Search box, I get the following message:

I ensure you that i have already verified the decimal attribute which is set to 8 in my code.

What can be the possible reason for not able to display decimal units in my contract?


texts:
Corrupted keystore file
I accedently deleted my keystore files. Used recovery program and got them back. But the one file with most eth on it seems to be corrupted. The size is the same as the other but when i open with notepad there is no text at all. Ethereum wallet program does not recognize the file. Tried myetherwallet with same result.
Are there anything that can be done to get access to my money ?
Sorry for bad english


texts: what happens if you fill the maximum size of the index of an array

texts:
suppose I have an array with 2 ^ 256-1 elements
What happens if I add another element?


texts:
I am trying to send 2  transactions.

  eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1],
  value: web3.toWei(5, "ether")})

  eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1],
  value: web3.toWei(5, "ether")})

The transactions are getting submitted and getting the hash of the transaction

INFO [08-25|21:14:21] Submitted transaction
fullhash=0xe1b58ddcb6d8c3f3a8308e0eb275f10c0c3b7bd8807cd24ff6a315a3917ab2a5 recipient=0x939f34bc9253a62927871c889bcf62f398d264a6 INFO [08-25|21:14:29] Submitted transaction
fullhash=0x33ca6bb00a70de13bd8b1fdec5d0a7995ad09a90e416ac8ab686fc650a324331 recipient=0x939f34bc9253a62927871c889bcf62f398d264a6 INFO [08-25|21:14:57] Updated mining threads threads=1 INFO [08-25|21:14:57] Transaction pool price threshold updated price=18000000000 INFO [08-25|21:14:57] Starting mining operation INFO [08-25|21:14:57] Commit new mining work
number=1 txs=2 uncles=0 elapsed=73.574ms

But the transactions are still in pending state.
as they get listed in the following query

  eth.pendingTransactions

So my question is

1) When will my transactions will execute and the transfer amount will be reflected?

2) Do I need to send any command?

I am using private blockchain and using geth

Any comment or suggestion will be of great help.


texts: Retrieving historical balance and lifespan of an address

texts:
I am coding up a PoC for a free market basic income mechanism, and am trying to figure out how to get the historical balance of msg.sender, as well as the time since that address was generated.

Historical balance: There is no 'total received' variable for an address, right? Should this then be calculated by the contract, or would it be far more gas effective to have this done by a javascript app, or use a block explorer?

Life span of address: how do I retrieve the block number of msg.sender's first transaction and then calculate the rough time in days or months since that occurred?

I am fairly new to Solidity and haven't had too much programming experience.


texts: Error npm installing consensys diligence takehome bignumber util

texts:
```
/sudo npm install
Password:
Unhandled rejection Error: Command failed: /usr/local/bin/git clone --depth=1 -q -b master https://github.com/debris/bignumber.js.git /Users/quantum/.npm/_cacache/tmp/git-clone-f59a30ef
/Users/quantum/.npm/_cacache/tmp/git-clone-f59a30ef/.git: Permission denied

    at ChildProcess.exithandler (child_process.js:291:12)
    at ChildProcess.emit (events.js:182:13)
    at maybeClose (internal/child_process.js:961:16)
    at Socket.stream.socket.on (internal/child_process.js:380:11)
    at Socket.emit (events.js:182:13)
    at Pipe._handle.close (net.js:599:12)
```

Why is this failing? I reinstalled node and git.

It now is stuck on
Unhandled rejection Error: Command failed: /usr/local/bin/git clone --depth=1 -q -b master https://github.com/debris/bignumber.js.git /Users/quantum/.npm/_cacache/tmp/git-clone-f59a30ef
/Users/quantum/.npm/_cacache/tmp/git-clone-f59a30ef/.git: Permission denied

at ChildProcess.exithandler (child_process.js:291:12)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:961:16)
at Socket.stream.socket.on (internal/child_process.js:380:11)
at Socket.emit (events.js:182:13)
at Pipe._handle.close (net.js:599:12)

⸨            ░░░░░░⸩ ⠇ extract:npm: sill extract caller-path@0.1.0


texts: Can you store anything other than Eth in one wallet

texts:
Total newbie to blockchain. I want to use ethereum to store information and not so much currency. For example, I want to create a game where I can store someones point. Can the wallet address store any other value other than ETH? can it store someone's point?

for example player A plays a round of game, gets 1500 points. I want to add the 1500 points to his account and have the moderator do a getbalance, on every account to see who is in first place.

Obviously I can name name the "wallet" points, but from my understanding the gas uses the same currency as the "Wallet", that way the point balance gets diluted.

The other way around is to send empty messages and parse the blockchain network for the messages send to that particular wallet, and su up the points.....but there has to be a more efficient way.

Any suggestions will help.
thanks.


texts: If two people create the same smart contract, is it stored twice?

texts: There are many cases where the same contract gets deployed many times. Now obviously each contract has its own persistent data storage and everything, but is each contract’s bytecode also taking up space multiple times on Ethereum nodes’ computers? Or is there some mechanism that deduplicates contract code, and instead of saving all the code again and again, can just store it once and then on subsequent identical contract creation can just save something like <same as contract 0xABC...>?


texts: How to verify a contract in etherscan older than 0.4.11?

texts:
It seems that the verification feature of Etherscan supports contracts written since Solidity 0.4.11.

I want to verify a contract written with Solidity 0.4.8. Is this possible?

I'm wondering if this is a new restriction, because I'm seeing other 0.4.8 contracts that are already verified.


texts:
What are the different techniques to count nodes in ethereum? ethernodes.org has a count of nodes, how can we verify if that is true ?
Are there any other techniques to do similar counting. Can you please list/link them.


texts: Please look over my contract for re-entrancy

texts:
I know the random number generator isn't secure and is susceptible to manipulation from miners and any advice on the method to generate random numbers will be appreciated.
However, the reason I'm posting my code is to ask if you (the community) could take a look and see if it's safe from re-entrancy. I've done what I think is necessary to secure my code but I just want to double check before deploying on the Rinkeby network.
pragma solidity >=0.6.2 <0.7.0;
//SPDX-License-Identifier: UNLICENSED

contract Slot_Machine is Mortal{

  event MyGuess(address indexed from, uint myguess);
  event Message(address indexed from, string  message, uint guess, uint random_number, uint  deposit, uint  winnings);

  // A struct type that defines state variables of a player.
  //Every player has a wallet, amount they are willing to
  //deposit and a guess.
  struct Player{
      address payable wallet;
      uint deposit;
      uint guess;
  }

  bool reEntrancyMutex = false;
  bool isWinner;
  mapping (address => Player) public player;

  //The random number returned from the generator.
  uint randomNumber;

  constructor() public{}

  //psuedo-random number generator.
  function generateRandomNumber() internal returns(uint) {
    uint balancer = uint(keccak256(abi.encodePacked(block.number,block.difficulty,msg.sender))) % 100;
    randomNumber = uint(keccak256(abi.encodePacked(block.number,block.number-balancer,msg.sender))) % 100;
    return randomNumber;
  }

  //get random number. Used to display results on UI.
  function getRandomNumber() public view returns(uint){
    return randomNumber;
  }

  //create new player.
  function newPlayer(uint pdeposit, uint pguess) private{
    player[msg.sender] = Player(msg.sender, pdeposit, pguess);
  }

  //initiate bool to determine how player wins.
  function playResult() public{
    isWinner = player[msg.sender].guess == randomNumber;
  }

  //transfer players ether is they win.
  function transferWinnings() private{
    player[msg.sender].wallet.transfer(player[msg.sender].deposit*2 wei);
  }

  //Pay out double the players deposit if they guess correctly the randomly generated number.
  function getBalance() public view returns(uint) {
    return address(this).balance;
  }

  fallback () external payable{}

  receive () external payable{
    require(msg.sender.balance >= msg.value,
          "Insufficient balance to complete transaction.");
  }

  function main(uint pguess) public payable{
    require(!reEntrancyMutex);
    //create new player with deposit and guess.
    newPlayer(msg.value,pguess);
    //generate random number.
    generateRandomNumber();
    //initiate result checking mechanism.
    playResult();
    reEntrancyMutex = true;
    //check if player is a winner.
    if(!isWinner){
      emit Message(player[msg.sender].wallet,"Loss",pguess,getRandomNumber(),msg.value, 0);

    } else {
          transferWinnings();
          emit Message(player[msg.sender].wallet,"Win",pguess,getRandomNumber(),msg.value, msg.value*2);
    }

    reEntrancyMutex = false;

  }
}


texts: How can I use performance data on Rinkeby to project performance data on the Ethereum Mainnet?

texts:
I'm testing a DApp on the Rinkeby testnet, and want to know how well it would perform on the mainnet if I deployed it there, specifically how much gas was consumed by the DApp. Is there any way for one to compare the statistics I gathered from Rinkeby to potential statistics on the mainnet?

Thanks so much in advance!


texts: How to get transaction failed reason with transaction hash with web3?


texts: Web3 js events not listening after 5 mins of idle time

texts:
My contract is deployed on ropsten infura test-network and that contract has events which gets fired when there is some transaction.

contract file

function functionName(address from, address destination, uint256 amount) stoppable public {
        myEvent(from, destination, amount);
}

I am trying to listen this event in my node js code in below manner

let web3 = new Web3()
web3.setProvider(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'));

Contract.events.myEvent(function (err, res) {
      if (!err) {
        console.log('Event Log :', res);
      }
})

After restarting node server and doing instant transactions which calls method "functionName" from contract which emits event, node js is properly listening for the events and I am getting expected output.

But if I wait 5 min or more idle without making any transactions or any activity and if I make transaction after that interval the method from contract "functionName" is getting called but node js is not able to listen for that event.

Can any one please let me know if you face such issues ever.


texts:
I've used the default crowdfunding code from the ethereum website, but I'm having a lot of trouble figuring out how to set the price for each token as an ether decimal (e.g. 0.0005 ether for each token)

Another problem I have is after creating the contract, I try to send ether from MyEtherWallet and this error comes up.


texts:
I've just completed my first Gh and i'm really thinking to solo mine, is it worth? what's the variance?
i know it can be shorter or longer to find a block, but what's the medium variance?

I'm currently mining on dwarf, but it's mining 20% lower than what's expected on the calculator and this is really bothering me!


texts: How to create test accounts with custom balance programatically in web3.py?

texts:
I am trying to write tests for a smart contract and am having trouble transferring funds to the contract's address.

I'm using web3.py app which (if I understand correctly) runs its own TestRPC, like this:

w3 = Web3(TestRPCProvider())

Then I deploy contract, after which I try to send funds to it:

ACCT_PASSPHRASE = 'KEYSMASH FJAFJKLDSKF7JKFDJ 1530'
acct_addr = w3.personal.newAccount(ACCT_PASSPHRASE)
w3.personal.unlockAccount(acct_addr, ACCT_PASSPHRASE, 1000)
txn_hash = w3.eth.sendTransaction(transaction={
    "from": acct_addr,
    "to": crowdsale_contract_address,
    "value": 5,
    "gas": 3000000,
})
txn = w3.eth.getTransaction(txn_hash)

Result is of course an exception:

ethereum.exceptions.InsufficientBalance: <Transaction(b'30c4')>: 'balance' actual:0 target:3000005

So, how do I create an account with sufficient balance?

Alternatively, how do I use one of the preexisting accounts? What are their passwords? Do they have any balance?


texts:
I have installed Geth on my mac Mojave 10.14.3 by

brew tap ethereum/ethereum

and

brew install ethereum

Just the same as the instruction and
everything goes well, but when I run

geth console

there comes a fatal error:

Fatal: Error starting protocol stack: database version is v7, Geth 1.8.27-stable only supports v3

Can anyone helps me? Thanks!


texts: Truffle test doesn't recognize estimateGas function

texts:
I'm trying to test my contracts using Truffle and Ganache, but I'm facing some problems with some functions. When I call a non view function, I'm getting the error "out of gas". Moreover, if I try to use the "estimateGas" function to check how much gas is spent on that transaction, the function isn't recognized and the console says that "estimateGas is not a function" even where, if I log my contract function, it clearly says that estimateGas exists.
I'm leaving here the code I'm using in the Javascript test file.
const MyContract= artifacts.require("MyContract");

contract("MyContract", (accounts) => {
  it("should construct correctly", async () => {
    let users = [
      "0x62CeeD6A2e86f1a4bA54cc7E9C1C1d61E229109a",
      "0xaFdB5c9612c0961Bb7f577202F5888d009ca84B0",
      "0x62CeeD6A2e86f1a4bA54cc7E9C1C1d61E229109a",
    ];
    let names = ["Jack", "Mark", "Jack"];
    let ids = [1, 2, 3];

    const instance = await MyContract.deployed();
    console.log(instance.fillUser.estimateGas); // This log says that estimateGas is a function
    instance
      .fillUser(users, names, ids)
      .estimateGas({ from: accounts[0], gasPrice: 20000000000 }, function (
        error,
        gasAmount
      ) {
        console.log(Number(gasAmount));
      }); // This fails because estimateGas is not recognized as a function
  });
});


texts:
I am decoding bytes as the following:

      // Decode Solidity tightly packed arguments
      (uint8 _, uint128 stakeId, address behalf) = abi.decode(userData, (uint8, uint128, address));  // solhint-disable-line

I get a compiler warning:

Variable '_' is declared but never used.

What would be the right way to suppress this warning beautifully? I know how to do this for function arguments, but not sure how what is a good practice with abi.decode.

The obvious way does not work:

/Users/moo/code/dawn-erc20/contracts/Staking.sol:255:23: ParserError: Expected ',' but got identifier
      (uint8, uint128 stakeId, address behalf) = abi.decode(userData, (uint8, uint128, address));  // solhint-disable-line


texts: how to make getAccounts() return a list of all 10 accounts?

texts:
I am using Truffle Development (or Ganache at times) and the problem is web3.eth.accounts is only one account and not the list of all 10 accounts

I want to get hold of at least first two so that I can do token transfer (ERC721) using safeTransferFrom

For now I have just hardcoded the second parameter (to account) and that works, but every time I switch Development to Ganche I have to recode the second account, which is not nice.

I have tried all kinds of ways for getAccounts (callback or promise) but no use.

For example:

web3.eth.getAccounts((error, accounts) => {
  this.setState( {accounts : accounts} );
}


texts: Is there some way to save an array (write file) through geth to a text file?

texts:
I'm looking to save or extract an array inside a file.js file in geth console to a text file. I have
shearched this subject but i could find nothing related to this. Is this possible?

I tried:

  /.geth --jspsth"path/to/file" --exec "eth.namereg(loadScript('file.js'))" > file.txt

but it doesn't work.

I hope someone could help me.

Thanks


texts: Can't access nested mapping in another contract in Solidity

texts:
I have a contract:

contract KeyValueStorage {
    mapping (address => mapping(bytes32 => uint256)) refreshTime;
    ....
}

and in another file:

import "./KeyValueStorage.sol";
contract GlobalGeneric {
    KeyValueStorage globalS;
    constructor(KeyValueStorage storage_) public {
        globalS = storage_;
    }
    function claimInterests(address _memberAddr, bytes32 _identifier) public returns (bool success) {
        require(now > globalS.refreshTime[_memberAddr][_identifier] + 90 days);
        .....
    }
....
}

But I got an error as refreshTime not found or not visible after argument-dependent lookup in contract KeyValueStorage


texts: Errors messages re: Flags and Genesis file when initialising a private blockchain

texts:
I used to initialise a private blockchain in this way:

geth --identity "Prashant" --fast --cache=1024 --jitvm --rpc  --rpcport "8013" --rpccorsdomain "*" --datadir "myPrivateNetwork2" --port "30312"  --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi "db,eth,net,web3,admin,debug,miner,personal,web3" --autodag --networkid 1902 --nat "any" init customGenesis.json console

I tried that again after a long time and I am getting an error message stating that --jitvm, --ipcapi, --autodag flags are provided but no defined.

Are these flags completely deprecated, or are there alternatives?  How can I specify whatipc apis I need to expose?

I am also getting this issue:

  Fatal: invalid genesis file: hex string has odd length

My genesis.json is this:

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

I have read other threads on the Genesis issue, all suggesting to use the latest version of geth, but I am already using it.

Edit:
The genesis issue was resolved by making extraData value an even length (0x00), as well as I needed to add a config to the customGenesiss.json,

    "extraData": "0x00",
    "config": {
            "chainId": 15,
            "homesteadBlock": 0,
            "eip155Block": 0,
            "eip158Block": 0
        }


texts: how to call contract method using sendRawTransaction

texts:
const privateKeyStr = "";
const privateKey = new Buffer(privateKeyStr, 'hex');
const contractAddress = '0x';
const COO = '0x';
let contractAddress = '0x';

let myContract = ...;
//some other articles told use getData method , but getData is undefined. so is use request instead.
let payloadData = myContract.contractMethodName.request(methodParams).params[0].data;

let rawTx = {
    nonce:  web3.toHex(web3.eth.getTransactionCount(fromAccount)),
    gas:   web3.toHex("21000"),
    gasPrice: web3.toHex(web3.eth.gasPrice.toNumber()),
    gasLimit: web3.toHex(40000),
    from:   fromAccount,
    to: contractAddress,
    data:   payloadData
};

var tx = new Tx(rawTx);
tx.sign(privateKey);

var serializedTx = '0x' + tx.serialize().toString('hex');
web3.eth.sendRawTransaction(serializedTx, function(err, hash) {
    if (!err){
        console.log('transaction hash : ',hash);
        process.exit(0);
    } else {
        console.error('error is ',err);
        process.exit(1);
    }
});


texts: 73: TypeError: "send" and "transfer" are only available for objects of type "address payable"

texts:
This is my simple code for following along a tutorial. We are building a Lottery Smart Contract.
However, I am failing to transfer the contract's balance to the winner. (see the last line inside of the contract.)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Lottery {
    address public manager;
    address [] public players;

    constructor() {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);

        players.push(msg.sender);
    }

    function random() private view returns (uint) {
        return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players)));
    }

    function pickWinner() public {
        uint index = random() % players.length;

        players[index].transfer(address(this).balance);
    }
}

I am getting the following error in remix:
TypeError: "send" and "transfer" are only available for objects of type "address payable"

I understand the error and tried changing the declaration of the players variable like this:
address payable[] public players;

But that gives me another error:
TypeError: Member "push" not found or not visible after argument-dependent lookup in address payable[] storage ref.

Can someone help me out?


texts:
This works fine in Remix but when trying to work in VSCode (for compiling purposes; DApp course, trying to build .json through compile.js ) it throws the error

  Using ".value(...)" is deprecated. Use "{value: ...}" instead.

  security/no-call-value: Consider using 'transfer' in place of 'call.value()'.
  from this line :-
  (bool success,) = recipient.call.value(request.value)("");    //Third last line below

pragma solidity >=0.5.16 <0.7.0;

contract CampaignFactory{
   Campaign[] public deployedCampaigns;

    function createCampaign(uint minimum) public{
        Campaign newCampaign = new Campaign(minimum,msg.sender);
        deployedCampaigns.push(newCampaign);

    }

    function getDeployedCampaigns() public view returns ( Campaign[] memory) {
        return deployedCampaigns;
    }
}

contract Campaign{

    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping( address => bool ) approvals;

    }

 Request[]  public requests;
 address public manager;
 uint public minimumContribution;
 mapping( address => bool) public approvers;
 uint public contributersCount;

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

  // constructor************************************************
    constructor(uint minimum,address creator) public {
        manager = creator;
        minimumContribution = minimum;

    }

    function contribute() public payable{
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        contributersCount++;

    }

    function createRequest(string memory description, uint value, address recipient ) public restricted() {
        Request memory newRequest = Request({
            description: description,
            value: value,
            recipient: recipient,
            complete: false,
            approvalCount: 0

        });

        requests.push(newRequest);

    }

    function approveRequest( uint index) public{
        Request storage request_index = requests[index];

        require(approvers[msg.sender]);

        require(!request_index.approvals[msg.sender]);

        request_index.approvals[msg.sender] = true;

        request_index.approvalCount++;

    }

    function finalizeRequest(uint  index) public payable restricted {
        Request storage  request = requests[index];
        require(request.approvalCount > (contributersCount / 2));
        require(!request.complete);

        address payable recipient = address(uint160(request.recipient));
        (bool success,) = recipient.call.value(request.value)("");
        (success, "Transfer failed.");
        request.complete = true;

    }

}


texts: Do Geth and Parity nodes have the same txpool?

texts: If I broadcast a transaction using a parity node, will it be more likely to be included in a block if the miner is also using Parity?  or do geth miners have an equal chance to include the transaction?


texts: Computer lagging & low MH/s & stop mining

texts:
Hi I am very new to mining and tried using Claymore DualMiner to mine ETH on the Nanopool.

I've set everything up, synced the blockchain and generated the config file from https://nanopool.org/ and started the "start.bat" batch file.

Now I have several questions:

Am I mining when it says "New job from eth-eu1.nanopool.org:9999"?
Why am I only getting about 2.6 Mh/s? (see system setup below)
Why is my PC lagging hard? How can I avoid this?
How can I stop mining and when & how will the ETH I mined get sent into my wallet? Can I just close the console window or are the mined ETH lost if I close it?

Thanks in advance

Processor: Intel Core i7-3770 @ 3.4GHz

RAM: 16.0 GB

Graphic Card: NVIDIA GeForce GTX Titan


texts: Difference between full node and bootstrap nodes in Ethereum?

texts:
I know that when a new geth instance runs it connects to the bootstrap nodes. What I want to know that do other nodes download blockchain from the bootstrap nodes or nor? Bootstrap nodes are highly available so why just simply connect to bootstrap nodes instead of connecting to some other node in the network.

What if bootstrap nodes provide wrong information. The whole network is compromised right?

How is a regular node different than a bootstrap node? And also How does peer discovery actually works? What if nodes only download and not upload? What if I execute a denial of service attack which connect to many nodes in the network and downloads blockchain?


texts: Self Destruct Design pattern - Loss of funds issue

texts:
I was exploring on self destruct design pattern for a time bound smart contract. So my contract should not accept any further state change after a certain given time period.

While working on that I have come across selfdestruct design pattern which is quite good for the need but leads to loss of funds if any one tries to send funds to a destroyed contract.

What should be the best approach to avoid loss of funds which are being sent to such contracts

Thanks


texts: Recalculated downloader QoS values & Current full block not old enough

texts:
I'm trying to build the private network between two raspberrry Pi3B with Geth.
But when i started the node and entered the javascript console,
it keeps showing the following message, and i don't know how to solve it:
Recalculated downloader QoS values
Current full block not old enough

also, when I wanna add another raspberry Pi by admin.addPeer(enode), it's not work.
the following is the inform of the geth and my raspberry:
Version: 1.9.25-stable
Git Commit: e7872729012a4871397307b12cc3f4772ffcbec6
Git Commit Date: 20201211
Architecture: arm
Protocol Versions: [65 64 63]
Go Version: go1.15.6
Operating System: linux
GOPATH=/root/go
GOROOT=/root/.go

I build the private chain with the following genesis:
{
  "config": {
    "chainId": 15312,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip155Block": 0,
    "eip158Block": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock": 0,
    "petersburgBlock": 0,
    "clique": {
      "period": 15,
      "epoch": 30000
}
},
  "difficulty": "1",
  "gasLimit": "8000000",
  "extradata": "0x00000000000000000000000000000000000000000000000000000000000000004c24e671f73bC1d110ee1Ff25d91ECa0Fb5630530000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "alloc": {
    "4c24e671f73bC1d110ee1Ff25d91ECa0Fb563053": { "balance": "3000" },
    "54610563D62F3a88CCAEfD6eFD391FE96d4A4c47": { "balance": "4000" }
}
}

and I started the node with the following command:
geth --identity "ETH-ViceNode" --rpc --rpcport "6060" --rpccorsdomain "*" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --datadir /home/pi/chain/data --port 30305 --networkid 15312 --verbosity 4 --nodiscover console

geth --identity "ETH-MainNode" --rpc --rpcport "6060" --rpccorsdomain "*" --rpcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --datadir /home/pi/chain/data --port 30304 --networkid 15312 --verbosity 4 --nodiscover console

anyone know where the problem is?


texts:
I come from a HTML/PHP/MYSQL background so bear with me on this. I am in the process of developing a contract and it is going pretty well. The main issue I have at the moment is how to filter an Array created with solidity.

At the minute the Array contains a list of Structs (these are items that can be purchased). I want to be able to filter them so that i have a list of unsold items.

Now in MYSQL you can obviously query but not here. At the minute I am doing the following:

Frontend - Call function that returns the length of the array.
Frontend - Taking the length loop through and fetch all the items.
Frontend - Check to see if the item is bought, if so separate into a "unsold" frontend array.
Display items in the unsold array.

The obvious issue here is that lets say we have 1000 items, the frontend has to loop through each one and then call the function to get the items details so we end up with 2000 calls plus the filtering on top into a separate array. This obviously takes time.

I could go down the route of taking all the items from the contract and then storing them in a MYSQL db for queries but I was looking to avoid the use of DBs if possible.

Im wondering if there is a better approach to this that I don't know about? For example should I be worrying about network performance like you would do when you are fetching from lets say a single server?

Edit
One way it could be made slightly easier is if I could return the Array containing the Structs in one go instead of having to do separate calls for each one based on the length.


texts:
I'm running Geth on an AWS micro server with 1GB of RAM of 50GB of storage (EBS). If I run it with the --fast flag on, it crashes after a couple of minutes because it runs out of memory. If I run it normal mode with --rpc on, any requests to the Geth client are processed with delays.

What are the RAM / CPU requirements so I can run it with the --fast flag on and so that it can handle a couple of rpc calls a second?


texts: Deploy contract from browser but ensure details saved to server

texts:
I'm very new to blockchain/Ethereum development and would like to allow users to directly deploy contracts from a site using MetaMask, however, I want to make sure that I can keep a record of contract addresses to be cross-referenced with user addresses.  I would then allow users to view their open contracts based on the MetaMask account number.

I will also need to send data to the smart contract from the server at certain points, so it's crucial that I be able to record all smart contract addresses.

I don't want to run the risk of having to capture new contract addresses in the browser and send them to the server and, from what I'm seeing, I'm not sure that I can communicate data from a smart contract to an outside source without first having the address.  So what options do I have?

If all else fails, I can design a different structure to centrally manage contracts, but this could be a lot more complicated, use more gas, etc.


texts: Issue trying to retrieve data from contract using Web3 1.0

texts:
I feel like I must be missing something trivial here. I have a smart contract that populates an array of structs shown below. When trying to call addNewQuestion('0x12345') or getQuestionListSize() it seems like it is never adding a new Question struct to  questionList. When calling getQuestionListSize() it should be returning the counter which I named questionId but it is always just returning "1". Any help greatly appreciated.

Contract:

pragma solidity ^0.4.11;

contract EthUpVoting {

  struct Question {
    bytes32 ipfsHash;
    uint upvotes;
    address user;
  }

  uint private questionId;
  mapping (uint => Question) public questionList;

  event AddedQuestion(bytes32 ipfs_hash, uint qId);

  function EthUpVoting() public {
    questionId = 1;
    questionList[questionId] = Question({
        ipfsHash: "Hello, World!",
        upvotes: 0,
        user: msg.sender
    });
  }

  function addNewQuestion(bytes32 questionHash) public {
      questionId += 1;
      questionList[questionId] = Question({
          ipfsHash: questionHash,
          upvotes: 0,
          user: msg.sender
      });
      AddedQuestion(questionHash, questionId);
  }

  function voteForQuestion(uint qId) public {
    questionList[qId].upvotes += 1;
    questionId += 1;
  }

  function getQuestionTextAtIndex(uint qId) public constant returns (bytes32 ipfsHashReturn) {
      return questionList[qId].ipfsHash;
  }

   function getQuestionListSize() public constant returns (uint size) {
      return questionId;
  }

}

NodeJS:

const web3 = new Web3(Web3.givenProvider || "ws://127.0.0.1:8546")
const ethUpVotingContract = new web3.eth.Contract(config.eth.abi, config.eth.contractAddr);

ethUpVotingContract.methods.addNewQuestion('foo').send(ethOptions, (err, resp) => {
    if (err) {
      console.log(err)
    } else {
      // successfully returns transaction hash
      console.log(resp);
    }
}).then(resp => {
    // successfully returns transaction receipt
    console.log(resp);
});

ethUpVotingContract.methods.getQuestionListSize().call().then(function (resp) {
    // this always returns "1"
    console.log(resp);
});


texts: Why do Solidity audits include checks that function address arguments are not equal to 0x0?

texts:
I've recently completed an audit for some Solidity contracts, and one of the checks the auditor included for all of the contracts was to make sure that address function arguments are not equal to the zero address (0x0). Why do audits include this check, what are they trying to protect against?
I also see it in this (dated) checklist for Solidity audits: https://github.com/miguelmota/solidity-audit-checklist


texts:
I am using Metamask on Chrome. While I was clicking to send ETH on Private Network (localhost: 8545), I have been getting an error about "Unknown props network, identities, addressBook on  tag. Remove these props from the element." in Chrome Console screen. It is ok for connection and ETH balance.

Do you have any idea for this problem?


texts:
Are there any special steps to connect an web app to the gethrpc?

testing the webapp locally with ganache works fine.

I have an geth Ethereum node running and started the gethRPC. The web app can't connect to the RPC. Are there any special steps which I have to perform for establishing the connection?

chrome console shows:

OPTIONS http://localhost:8545/ net::ERR_CONNECTION_REFUSED


texts: A cheap way to convert between USDT and USDC

texts: Any decentralized cheaper way to convert usdt and USDC? I heard that usdt and usdt also freeze the assets? Any reliable usd service that can not freeze assets?


texts: What is the difference between web3.eth.coinbase and web3.eth.accounts[0]? Which is the best method to get the current address?  I am new to this community and I know this may be a silly question


texts: Accessing a public mapping within a contract from a different contract

texts:
Consider the case where I want to get the elements of a struct via a public mapping from product contract to price contract:

contract Product{
    struct prod{
        string name;
        uint id;
        bool status;
    }
    mapping(uint => prod) public products;

    function updateStudent (string n, uint ID) {
      products[ID].n = "Temp";
      products[ID].status = true;
    }
}

At this point, I would like to access the elements of the mapping from a different contract:

contract ProductList {
    address productAddr;
    string p_name;
    uint p_id;
    Product p;
    function ProductList(address addr) {
        productAddr = addr;
        p = Product(addr);
    }

    function readProduct (uint u) returns (bool c) {
      p_id = p.products[u].id;
      p_name = p.products[u].name;
      c = true;
    }
}

In the above scenario, I am always getting the error: Indexed expression has to a type, mapping or array (is function...). Any suggestions would be greatly helpful!


texts:
This smart contract is properly deployed on Rinkeby.
https://rinkeby.etherscan.io/token/0x551b092ae227414c5cf7c7e11e70c252e95bedf0

Questions:

Why on MetaMask the Beneficiary account address (provided in the code) can't load the majority tokens he should have own?
Where all the 17998500 tokens that should be in balance of the address holder? Havent they reached? The investors funds are received.
Why on Read Smart Contract it says
Sorry, we were unnable to retrieve a valid ContractABI for this contract.
Unable to read contract information


texts: Transfer function gives infinite gas warning in remix

texts:
If I use this simple payout contract in remix, it gives me a warning that the gas costs is infinite. Is this an intended behaviour?

contract Payout
{
    function payout() public {
        msg.sender.transfer(2);
    }
}

Context of this question: trying to debug my application and  gas costs could be possible problem source.


texts: Sample Token contracts dont work - "The contract won't allow this transaction to be executed"

texts:
The sample "Advanced Token" contract here:
https://www.ethereum.org/token

Does not work when deployed on the test net. Trying to send ether to the contract to buy tokens results in the error message:

The contract won't allow this transaction to be executed

Nothing in the tutorial explains why this would happen.


texts: Is necesary pass a Dapp to mainnet or in testnet is ok for a production smart contract process?

texts:
Because the client Dapp propietary don´t have real Ether, only Ropsten test Ether via faucet.ropsten.be/
is necesary buy Real Ether to preserve smart contracts in ethereum or in Ropsten testnetwok is possible have a production Dapp? excuse me i´m a new Ethereum developer


texts:
I have sent this transaction to testnet through json-rpc with my geth node using eth_sendTransaction method and the following parameters:

"from": "0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d",
"to": "0x90e8682b63d7922a3e942d4bbd4c88095634a17b",
"value": "0xf4240"

// 0xf4240 = 1 million wei, 1 babbage

Geth node log receives the tx as showed here:

I0915 08:29:03.639166 eth/api.go:1193] Tx(0x2dac8edc68d40f2b09e2f06d455c51ea6f29a6199eeeccbff8b946f5c2e330d9) to: 0x90e8682b63d7922a3e942d4bbd4c88095634a17b

But transaction is not propagating through testnet ...

Two days ago this very same transaction (same from, to and value, but obviously not same txHash) was accepted (mined) in Ethereum testnet in less than 20 seconds. Today every transaction I sent seems to be stall.

The txHash assigned to the transaction is 0x2dac8edc68d40f2b09e2f06d455c51ea6f29a6199eeeccbff8b946f5c2e330d9 . On etherscan there's no info about it: https://testnet.etherscan.io/tx/0x2dac8edc68d40f2b09e2f06d455c51ea6f29a6199eeeccbff8b946f5c2e330d9

When I query the node about the tx with eth_getTransactionByHash method this is the result:

        [blockHash] => 0x0000000000000000000000000000000000000000000000000000000000000000
        [blockNumber] =>
        [from] => 0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d
        [gas] => 0x15f90
        [gasPrice] => 0x4a817c800
        [hash] => 0x2dac8edc68d40f2b09e2f06d455c51ea6f29a6199eeeccbff8b946f5c2e330d9
        [input] => 0x
        [nonce] => 0x10000e
        [to] => 0x90e8682b63d7922a3e942d4bbd4c88095634a17b
        [transactionIndex] =>
        [value] => 0xf4240

It seems like it's waiting to be mined forever...

Has this transaction been brodcasted to testnet? Has it been mined? Why not? How can I track the mining status of this transaction?

After reading a similar question Why are these transactions not broadcasted in my private network? I realize I have unlocked from_account. Do I have to unlock to_account too?

It seems transactions became stuck on nonce 0x100004. Here it is the details of the previous tx (nonce 0x100003) and the tx with nonce 0x100004:

eth_getTransactionByHash: ["0x59af3aec8331c407a5a33a58203ee62a89b1efa772806b2c4319c395bb70bdd0"]
Array
(
    [jsonrpc] => 2.0
    [id] => 1
    [result] => Array
        (
            [blockHash] => 0x0aceab7d5e8a1d44efc36dfadabcbe3eaa14de08e7625a3208ca07fac6275014
            [blockNumber] => 0x190dce
            [from] => 0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d
            [gas] => 0x15f90
            [gasPrice] => 0x4a817c800
            [hash] => 0x59af3aec8331c407a5a33a58203ee62a89b1efa772806b2c4319c395bb70bdd0
            [input] => 0x
            [nonce] => 0x100003
            [to] => 0x90e8682b63d7922a3e942d4bbd4c88095634a17b
            [transactionIndex] => 0x0
            [value] => 0x2540be400
        )

)
eth_getTransactionByHash: ["0x824eeda61dba30c107400a5ab43dffa8408aae7f925f530699f69c94ed0c008b"]
Array
(
    [jsonrpc] => 2.0
    [id] => 1
    [result] => Array
        (
            [blockHash] => 0x0000000000000000000000000000000000000000000000000000000000000000
            [blockNumber] =>
            [from] => 0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d
            [gas] => 0x15f90
            [gasPrice] => 0x4e20
            [hash] => 0x824eeda61dba30c107400a5ab43dffa8408aae7f925f530699f69c94ed0c008b
            [input] => 0x
            [nonce] => 0x100004
            [to] => 0x90e8682b63d7922a3e942d4bbd4c88095634a17b
            [transactionIndex] =>
            [value] => 0x2540be400
        )

)

Well, thx for your comments, because I did it! Resending tx with nonce 0x100004 worked and has been mined. Thx!

Nevertheless, I still don't know why tx 0x824eeda61dba30c107400a5ab43dffa8408aae7f925f530699f69c94ed0c008b got stuck ... any hint about this could help me a lot. Thx anyway!


texts: Why is fast sync not working with geth 1.1?

texts:
When I run geth --fast

I get:

Incorrect Usage.

geth [global options] command [command options] [arguments...]

VERSION:
   1.1.0

[...]

flag provided but not defined: -fast

How do I fix this?


texts: Sending money from Coinbase to My Ethereum wallet. It doesn't appear the money

texts:
it has been one day, when I pass Ethers from Coinbase to my Ethereum wallet. And I still have 0.00 money. I've checked the address and it's ok.

What is the reason? Thank you.


texts: How many peers can an Ethereum node have?

texts:
Is there any maximum limit on the number of peers an Ethereum node can have? Does this vary for private and public networks?

In case of Bitcoin, is there a limit?


texts: geth: shh_newIdentity does not exists/is not available

texts:
I'm trying out whispers with web3 and geth on a private testnet. I'm just running the following code taken from Ethereum Whisper wiki.

function sendWhisper() {
    var shh = web3.shh;
    var appName = "My silly app!";
    var myName = "Gav Would";
    var myIdentity = shh.newIdentity();
}

However, I'm getting this problem:

  app.js:5318 Uncaught Error: The method shh_newIdentity does not exist/is not available

I'm having a wild guess that there is something wrong with geth. According to this issue the JSON RPC shh_newIdentity, should have been implemented already. Any ideas?


texts:
Whenever I edit a file called filename.something, my text editor creates a file called .#filename.something when I modify anything. That file exists until I save. These files never were a problem until now. However, Truffle does not get along with them. Whenever I run

truffle test

with any modified but unsaved files, I now get this error message:

Error: ENOENT: no such file or directory, stat '/path/to/project/test/.#Contract.test.js'

This even happens when I run the command and start editing as my contracts compile. So I always have to sit through that, not doing anything. How can I tell Truffle to just ignore file names that start with .#?

I use Truffle v5.0.37.


texts:
What's the magic numbers meaning of 27 or 28 in VRS ( use to ecrover the sender) ? why not 0 or 1?
Ecrecover need 0 or 1, but transaction RLP is 27 or 28. Before ecrecover, sub 27 to get 0 or 1. Why not encode the transaction use 0 or 1 directly? What's the magic number 27 and 28 mean?


texts: Difference between sending a transaction with no to field and create() opcode?

texts: What is the difference between sending a transaction with no to field and create() opcode ?


texts:
I define a balance as follows :

mapping (address => uint[]) Energy_Balance

to keep the history of each transaction. I set its new value as follows :

First Transaction: balances[owner][0] = balances[owner][0] + value;
Second Transaction: balances[owner][1] = balances[owner][1] + value;

Now, I want to define a uint counter such that it can keep its last value every time it is increased one unit as follows :

balances[owner][counter] = balances[owner][counter] + value

If I define counter as follows, is it correct in solidity and it can keep its last value ?

static uint counter = 0;
function myFunction(uint value) {
    balances[owner][counter] = balances[owner][counter] + value;
    counter = counter +1;
}


texts:
I have written and deployed my smart contract in Ropsten and all the calls are failing with status failed . Says out of gas but same problem if I passed additional gas argument.
I am using web3 python transact method .

Transactions : https://ropsten.etherscan.io/address/0x56eafd2f8528875d779bb1b7290a8608d8fcc72e


texts:
I've written a smart contract in which if the same address is entered again. Then it will be stored on address and index value. Now I want to return the data from 1 to 10 at a time.

The code is like

contract Bar{

    struct Foo{
        uint x;
    }
    mapping(uint => Foo[]) foo;

    function add(uint id, uint _x) public {
        foo[id].push(Foo(_x));
    }

    function get(uint id, uint index) public returns(uint){
        return foo[id][index].x;
    }
}

can somebody help me with this?


texts:
I am curious if ERC1155 token is able to stake or something else with smart contracts?
I know ERC721 is able but not sure about ERC1155.
Thank you.


texts: Deploy contract from contract in Solidity

texts:
It's a common pattern to use a hub/factory contract to create multiple instances of a standard contract.

It's also common to require a way to enumerate the addresses of the created contracts.

Is there a simple minimal example of a good approach?


texts: What are incoming transactions to Binance

texts:
The Binance addresses and most other centralised exchanges exhibit a clear transaction pattern: All of the incoming transactions are from arbitrary EOAs and transfer Ether with them.
Does anybody know the purpose and the background of these transactions?
My guess was that trader on Binance connect their ETH wallets to the Binance wallet and send ETH to the Binance wallet to fund trades or their trading account to trade on the platform. Is this correct?
https://etherscan.io/txs?a=0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be&f=3&p=1


texts: Truffle testing:How to convert from Mocha to Solidity

texts:
I am following the tutorial at:
truffle- Mocha
It shows a mocha code for testing. I want to do the testing in Solidity.
const SimpleContract = artifacts.require("SimpleContract");

contract('SimpleContract', (accounts) => {
  it("should return the list of accounts", async ()=> {
    console.log(accounts);
  });
});

Please guide me how to convert Mocha code into Solidity?
Zulfi.


texts: How is it possible for ethereum-bridge to deploy a contract at a deterministic address?

texts:
Here I provide a snippet of the output generated by ethereum-bridge on startup:

[2017-10-13T07:25:55.920Z] INFO deploying the oraclize connector contract...
[2017-10-13T07:26:16.357Z] INFO connector deployed to: 0x3ae9795a5c4ef9f803d56437163b3abd39649525
[2017-10-13T07:26:16.482Z] INFO deploying the address resolver with a deterministic address...
[2017-10-13T07:26:47.730Z] INFO address resolver (OAR) deployed to: 0x6f485c8bf6fc43ea212e93bbf8ce046c7f1cb475

Indeed, the address of the OAR contract is always 0x6f485c8bf6fc43ea212e93bbf8ce046c7f1cb475, but as the contract's address is determined by hashing the sender's account + nonce, how can Oraclize (ethereum-bridge) always deploy to the same address?


texts:
I am doing research on using the erc721 interface to represent a digital good on an exchange. For simplicity's sake, let's say that these goods are a digital representation of a collectible card game (e.g. Magic the Gathering).

It is my understanding that each erc721 token will be unique. But taking the card game example, what if each product is not necessarily unique (has the same functionality)? For instance, if there are 20 of the same card in existence and each is owned by a separate address. Would erc721 be useful for such a situation?

My thinking is that each card of the same type would have a different ID, but the same metadata pertaining to the card's functionality or description. Any input on whether I'm on the right track is greatly appreciated.


texts: BalanceOf from BasicToken & totalSupply from ERC20Basic not working from Crowdsale.sol

texts:
I'm using Crowdsale.sol from OpenZeppelin / zeppelin-solidity.  Here's a snippet:

import '../token/MintableToken.sol';
import '../math/SafeMath.sol';

/**
 * @title Crowdsale
 * @dev Crowdsale is a base contract for managing a token crowdsale.
 * Crowdsales have a start and end block, where investors can make
 * token purchases and the crowdsale will assign them tokens based
 * on a token per ETH rate. Funds collected are forwarded to a wallet
 * as they arrive.
 */
contract Crowdsale {
  using SafeMath for uint256;

  // The token being sold
  MintableToken public token;

Is this inheriting from MintableToken?

MintableToken.sol inherits from StandardToken.sol and Ownable.sol.  StandardToken.sol inherits from BasicToken.sol and ERC20.sol.  BasicToken.sol inherits from ERC20Basic.sol and SafeMath.sol.

I want to use function balanceOf from BasicToken.sol and uint256 public totalSupply from ERC20Basic.sol, but these do not appear on remix.ethereum.org (using "JavaScript VM") after creating the Crowdsale contract .

If I change Crowdsale.sol to any of the following:

contract Crowdsale is StandardToken {

contract Crowdsale is MintableToken {

contract Crowdsale is BasicToken {

...balanceOf and totalSupply appear (after creating contract), but they only return 0. I send some funds to the contract and enter the sender's address into balanceOf and it returns 0.  I click on totalSupply and it returns zero.  They do not seem to be working.

What do I need to do to get these to work?


texts: Secure paper wallet creation for ETH using JS

texts:
I am about to start the process of transferring my ETH to paper wallets for safe keeping. Currently the funds are stored on an online exchange. History shows that this is a very bad idea. It is not much, but my threat-model is only on loosing the ETH. The questions relate to the creation of secure paper wallets.

For convenience I would like to use web wallet creation tools, such as MyEtherWallet and/or EthAddress. I analysed their source code and in none of them I could find a possible backdoor. (I couldn’t find - that doesn’t mean there isn’t)

What I did was:

Verified the TLS certificate chain of github.com
Download the code from the GitHub repos
Reviewed all the code, especially the JavaScript functions
Checked and compared if they used the same unmodified Ethereum JavaScript classes from the official repo
Analyzed the wallet creation code
Debugged each step with the dev tools in the browser
Generated 1000 wallets for a very short collision test

I now know that it uses window.crypto.getRandomValues for its PRNG, which is currently the best way in a web-browser, without using a third-party library. And they don’t use broken hashing algorithms.

Possible issues:

Collisions of wallet address public key (less likely with a cryptographically secure entropy/randomness source and the length of 40 characters - compared to Bitcoin’s 34-1 chars)
Bug in the code of the website and/or bug in the EthereumJS libs and/or the crypto implementations (It wouldn't be the first time it would contain a heavy bug in ethereumJS-utils)
Probably less tested in production than the official desktop wallet software

Precausions:

Creating the wallets on an air-gapped computer
Encrypting and storing the information in multiple physical locations
Wipe browser cache

Questions that need answering:

Will the wallets created at this moment in time be backwards compatible in the future? (Metropolis, Serenity, ...)
How do I verify if the wallets have been created correctly (private key), without first sending a small amount in and out of the wallet?
Is there anything else I have to consider and I am correct with my assumptions?
Why are there only third-party web wallet creation pages on the internet and no official ones (yet)? (Maybe because of: Ethereum: "We are making tools for tool-makers“?)

Thank you very much


texts: Is it possible to do an escrow for ERC20 Token

texts:
I am developing a website which helps users to perform the escrow of ERC20 tokens. The particular platform only accepts the said ERC20 token. I need my client to deposit the ERC20 token to the escrow contract until he get delivered with the service/product. My doubts are,

Is it possible to do an escrow contract for ERC20 tokens. I can't use Metamask(As web3 provider)since it is not possible to transfer tokens using metamask.

It will be great if someone guide me to find a solution with a sample contract if available, Thanks a lot :).


texts: What happened on June 17, 2016 with the DAO?

texts: It seems the DAO was attacked. What exactly happened? What can be done?


texts:
Is there a comprehensive list of the commands available in the geth terminal anywhere?

(eg. miner.start(), eth.accounts, admin.nodeInfo, etc.)


texts: Raw transaction nonce won't increment until confirmation

texts:
I am building transactions manually and have been able to successfully create raw transactions which can be broadcasted to the network.

My problem is, that while I can get a nonce from the web3.getTransactionCount(address) method, this nonce only returns from the latest confirmed transaction meaning I have nonce conflicts when multiple transactions are broadcasted before confirmation of the other.

Has anyone encountered this problem and if so, how did you work around it?


texts: An error occurred while running C:\Users\path marketplace1\marketplace1\truffle-config.js! Did you forget to `npm install` your project?

texts: I am getting this error when I try to add the truffle-config file to my project in ganache. What to do?


texts: Why doesn't remix allow inputs of letters in this code?

texts:
Okay, so this code is actually designed to revert when anything but 0, 1, ...9, is entered, but let me explain.

I created this code for general practice.  It may not have practical use, but it's intent is to convert a string version of the digits 0 - 9 to the uint version.  In testing it, it works perfectly when I enter any string with the characters 0 - 9.

pragma solidity ^0.4.24;

contract ConvertStringToUint {       // This version does not limit the number of bytes in the string to 78.

function stringToUint(string _number) public pure returns(uint) {

    bytes memory strBytes = bytes(_number);

    uint i;
    uint digit;
    uint result;

    for (i = 0; i < strBytes.length; i++) {

        if (strBytes[i] == byte(48))        {
            digit = 0;
        } else if (strBytes[i] == byte(49)) {
            digit = 1;
        } else if (strBytes[i] == byte(50)) {
            digit = 2;
        } else if (strBytes[i] == byte(51)) {
            digit = 3;
        } else if (strBytes[i] == byte(52)) {
            digit = 4;
        } else if (strBytes[i] == byte(53)) {
            digit = 5;
        } else if (strBytes[i] == byte(54)) {
            digit = 6;
        } else if (strBytes[i] == byte(55)) {
            digit = 7;
        } else if (strBytes[i] == byte(56)) {
            digit = 8;
        } else if (strBytes[i] == byte(57)) {
            digit = 9;
        } else {
            revert();
        }

        result = result * 10 + digit;

    }
        return result;
}

}

However, when I add a letter or any other character, I get an error I didn't expect.

For example, if I enter string "324", it returns the uint "324".  But if I enter string "3a24", I get the error:

  Error encoding arguments: SyntaxError: Unexpected token a in JSON at position 2

This suggests that it is not even allowing me to enter these characters as a string in the first place, which I don't understand because the input parameter is a string.

To further test this, I changed the line else if (strBytes[i] == byte(49)) to else if (strBytes[i] == byte(97)), so that now the character "a" will set digit to 0 and the character "0" should cause an error.  Sure enough, entering "0" gives me the error:

  ... VM error: revert.
  revert The transaction has been reverted to the initial state.

And even at this point, entering "a" still gives me the error:

  .. Unexpected token a in JSON at position 1

I've been through it several times and can't account for these error differences.  What is going on?


texts:
I am trying to deploy a contract in the ethereum blockchain with solidity. When i press the create button directly under it, a message saying

  "Waiting for transaction to be mined..."

shows up indefinitely. The contract i am trying to deploy is pretty simple and straight forward and i got it from a youtube tutorial. In the tutorial, after pressing the create button the metamask plugin pops up a message to make sure you want to deploy the contract which in my case it doesn't since it is stuck at "Waiting for transaction to be mined... ".
Any ideas why this is happening? Thank you in advance

(in metamask i am connected to the testnet morden)


texts: How to test with Mocha and Chai that a call at the kill() function of a Smart Contract (i.e., which does the selfdestruct) has gone right?


texts: Can I spend funds from a pending transaction?

texts:
Assuming I have two accounts, A and B, with balance 10 and 0 ETH respectively, and I send a transaction to a node transferring all balance from A to B.

If I try to create a new transaction sending balance from B to another account, while the previous transaction is still pending on the node, it seems I'm getting an insufficient balance error.

Going through the code in Parity, it seems that Parity checks for latest_balance of an account when checking if balance is enough, which is the balance on the latest mined block, not pending.

Is this a standard in Ethereum, or something dependent on the node's implementation? Do we know how Geth handles this?

Thank you!


texts:
Hello i m learning vyper and i have this issue: I deployed a standard ERC20 token contract using vyper default contract: https://github.com/ethereum/vyper/blob/master/examples/tokens/ERC20.vy

When i write my own contract to interact with it i have an issue transfering tokens from the current address that has tokens to the desired address, here is the code that i wrote in vyper to do the transfer:

contract Pcoin():
    def transfer(_to : address, _value : uint256) -> bool: modifying

@public
def transfer(_token_contract: address, _to: address, _value: uint256) -> bool:
    return Pcoin(_token_contract).transfer(_to, _value)

When i call the transfer method i get a failed transaction.
I tried also using the transferFrom method:

contract Pcoin():
    def transferFrom(_from : address, _to : address, _value : uint256) -> bool: modifying

@public
def transfer(_token_contract: address, _from: address, _to: address, _value: uint256) -> bool:
    return Pcoin(_token_contract).transferFrom(_from, _to, _value)

Also no luck with that.

Can someone please point out what i m doing wrong, Thanks :)


texts:
Why does this not work

struct Structure {
    string _var;
}

Structure[] structure;

function addStructure(string _var) {
    Structure _s = Structure(_var);
    ->> structure.push(_s);
}

while this works

struct Structure {
    string _var;
}

Structure[] structure;

function addStructure(string _var) {
    X
    ->> structure.push(Structure(_var));
}

I saw this in an tutorial but it does not work for me.
Thank you for explanation!


texts: Truffle V3.1.9, error running migrations

texts:
Hey I'm updating my truffle project from V2 to V3, and I am getting this error after migrating:

sudo truffle migrate --network development
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: Migrations error: contract binary not set. Can't deploy new instance.
    at Function.new (/usr/lib/node_modules/truffle/node_modules/truffle-contract/contract.js:324:15)
    at /usr/lib/node_modules/truffle/node_modules/truffle-migrate/node_modules/truffle-deployer/src/actions/deploy.js:25:29
    at process._tickCallback (internal/process/next_tick.js:103:7)

Here is my truffle.js file:

module.exports = {
networks: {
development: {
  host: "localhost",
  port: 8545,
  network_id: "*"
},
staging: {
  host: "localhost",
  port: 8546,
  network_id: 1337
},
ropsten: {
  host: "158.253.8.12",
  port: 8545,
  network_id: 3
}

}
}

Deploy contracts file:

var Project = artifacts.require("./Project.sol");
var FundingHub = artifacts.require("./FundingHub.sol");

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


texts: What exactly is a transaction when working with SmartContracts?

texts:
I am very new in Blockchain and Ethereum. I know the has transactions and blocks with hashes etc.
I also followed this example https://www.ethereum.org/greeter to create my own private Network with 2 Nodes. But in this example what is the transaction? The other peer calling the greet function? Is every greet stored in the Blockchain as an transaction?
Or what happens if I provide a setter function for the greet String and someone uses it to change the greet String, is that a transaction and stored in the Blockchain?


texts:
I've got the following error when I'm trying to deploy my token on BSC Testnet.
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Internal JSON-RPC error. { "code": -32000, "message": "execution reverted" }
Also this is what I see on the error log

There is the contract code - https://codeshare.io/5XRgxj


texts: Using smart contract to verify computation on encrypted data

texts:
I’m working on a project where all data is stored encrypted on a blockchain. There are some off-chain compute nodes that have the key to decrypt the data and perform some computation and return results. I’d like to design a scheme where one can verify that computation is correct using smart contract. So, I’m thinking to have a smart contract that implements the verification function. Verification function would have two arguments: a key for decryption and the expected result. The function is constant, so private key should not be written to blockchain, hence remain hidden from all. The function returns true or false and signs this result. This function can be called only by the entity that knows the key.
In order to implement the above, I need a function for decryption and for signing in Solidity, but I was not able to find any.

Any advice if decryption, signing function exist in Solidity? Any libraries? Any advice on alternative designs for my problem


texts: I have a complete node up to date.  If I want a new independent node, I just rsync the complete .etherum dir to another machine, then delete the keysstore and create new account and I'm in businnes.  This is much much much faster than any kind of sync --fast or not. Am I missing anything here?


texts:
I am working through the pet shop tutorial in the Truffle Suite documentation and am hitting a error and have been looking at it for a while.
What is it that actually produces the DeployedAddresses.sol?  In my case it is not getting produced, due to some error somewhere on my part.
The output of the truffle test is included below.
Using network 'development'.

Compiling your contracts...
===========================
> Compiling .\test\TestAdoption.sol
> Artifacts written to C:\Users\asus\AppData\Local\Temp\test--22492-b1Oa5KHqOkGz
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

  TestAdoption
    √ testUserCanAdoptPet (641ms)
    √ testGetAdopterAddressByPetId (259ms)
    √ testGetAdopterAddressByPetIdInArray (305ms)

  Contract: Adoption
    1) can fetch the collection of all pet owners' addresses
    > No events were emitted
    adopting a pet and retrieving account addresses
      √ can fetch the address of an owner by pet id (83ms)

  4 passing (16s)
  1 failing

  1) Contract: Adoption
       can fetch the collection of all pet owners' addresses:
     ReferenceError: expectedAdopter is not defined
      at Context.<anonymous> (test\testAdoption.test.js:31:7)
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)```


texts:
I've been following the tutorial at https://www.ethereum.org/greeter , but when it gets to the point of installing Solidity, it is apparently no longer maintained on chocolatey so that step doesn't work.

How should I go about installing Solidity?


texts: Verifying ERC20 Contract that uses OpenZeppelin's library contracts

texts:
I deployed an ERC-20 Token contract and would like to now verify it on etherscan.io

My contract utilizes Open-Zeppelin's library of contracts - which means it's importing one of their contracts into itself, like so:

pragma solidity ^0.5.0;

import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";

contract MyTestCoin is ERC20 {

   // etc.

Of course, it so happens that this imported ERC20.sol contract imports other contracts into itself as well, so the rabbit hole gets even deeper.

So my question is basically this: if I want to verify my contract, can I just verify IT, or do I need to also somehow verify every other contract it imports as well?

Also, what Open Source License Type should I choose when I go through the verification process? etherscan.io has like 9 different options you can choose from - and I can't tell what's right for this.

Any help would be greatly appreciated.

UPDATE

ok, I tried using truffle flattened in Terminal. It combined and outputted the code of all the files I pointed it to into one stream, so I copy-pasted that code into the etherscan verification page and got this error:

Compiler debug log:
 Error! Unable to generate Contract ByteCode and ABI
 Found the following ContractName(s) in source code : ERC20, IERC20, MyTestCoin, SafeMath
 But we were unable to locate a matching bytecode (err_code_2)
 For troubleshooting, you can try compiling your source code with the Remix - Solidity IDE and check for exceptions

So - what's that all about?

UPDATE # 2

As per the suggestion in the error message I received, I took all the code and compiled it in Remix - there were no errors. So the code seems to be just fine...


texts: Why Am I getting this Type error when compiling, "Type contract is not implicitly convertible to expected type uint256"

texts:
This is the bit of code I added that is throwing the error,
function withdraw() public {
    address payable owner = 0x11AEA62f1575d87a509d0e25b1060B06600842Fc;
    owner.send(address[this].balance);
}

The error it throws is  "Type contract MyToken is not implicitly convertible to expected type uint256"
If I change the 3rd line to owner.send(this.balance);  the compiler tells me that it can't find "balance".   Can any one explain what I've done wrong?


texts: I need to rebuild solc on OSX. I followed http://solidity.readthedocs.org/en/latest/installing-solidity.html but old version still in place with solc --version. Is there a process to remove existing solc before building it again?


texts: Is the encoded ABI of a function guaranteed to be unique?

texts:
I assume that two functions of different prototypes will yield two different encoded ABIs.

Is that correct?

With regards to two functions of the same prototype, I tested a pair of functions which are identical not only in their prototype but also in their implementation:

address public owner;
address public pendingOwner;

function claimOwnership1() public {
    owner = pendingOwner;
    pendingOwner = address(0);
}

function claimOwnership2() public {
    owner = pendingOwner;
    pendingOwner = address(0);
}

I then checked the encoded ABI via web3.js (1.0.0-beta.34):

console.log("claimOwnership1:", myContract.methods.claimOwnership1().encodeABI());
console.log("claimOwnership2:", myContract.methods.claimOwnership2().encodeABI());

And the printout is:

claimOwnership1: 0x45fd9e23
claimOwnership2: 0xa75343bf

But of course, that doesn't guarantee encoded-ABI uniqueness.

Is such uniqueness guaranteed anywhere in the Solidity standard?

Thank you!


texts: How to dynamically charge a fee associated with executing a particular Solidity contract's function

texts:
I am trying to understand how to set a dynamic fee in Solidity. I have the following code

contract Test{
uint fee;

function Test(uint _feeNumerator, uint _feeDenominator){
    fee = _feeNumerator/_feeDenominator;
}

function updateFee(uint _numerator, uint _denominator){
    fee = _numerator / _denominator;
}

function testPayable(string _doesNothing) payable {
    require(msg.value == fee * (10**18));

}

function getFee() returns (uint fee){
    return fee;
}

}
Which generates a pre-compiled error stating "ParseError: Expected token Comma got 'SubEther'.

I had previously tried the same functionality, but instead using (_numerator**18)/10. When I previously ran that code it worked, but it is now giving me an "Error: gas required exceeds allowance or always failing transaction" whenever I attempt to run testPayable.

My two questions are, is there a limit to how much I can charge for a user to execute a function? And how would I properly create a dynamic fee similar to what's attempted in the first part of the question?


texts: How does one read whats going on in the Input Data of a Ethereum Transaction?

texts:
Function: execute(address _to, uint256 _value, bytes _data) ***

MethodID: 0xb61d27f6
    [0]:0000000000000000000000001dba1131000664b884a1ba238464159892252d3a
    [1]:00000000000000000000000000000000000000000000028b78bf6bd677fe7c17
    [2]:0000000000000000000000000000000000000000000000000000000000000060
    [3]:0000000000000000000000000000000000000000000000000000000000000000
    [4]:0000000000000000000000000000000000000000000000000000000000000000

I am looking at the following data above, i understand that line 0 somehow translates into the reveicing address, can someone show me how the translation is done?
The second value is the amount to send i believe, can someone explain how this one translates into the correct amount?

Ive been trying to translate it from hex, but im clearly not understanding it.


texts: Implementing a Simple Voting DApp on Ethereum Blockchain

texts:
I am new to Ethereum, Truffle and Solidity. I am looking for a good resource to get started on implementing a DApp for Voting on Ethereum Blockchain. Could you please point me to the correct resource?

Thank you!


texts: does the block's nonce in Ethash dependes on previous nonce?

texts:
does the algorithm of Ethash use previous nonce to calculate the nonce for the current block? If it doesn't depends, then I could implement the algorithm to run it in parallel, and then , I could find many nonces and reuse them for future blocks. Is this correct?

Basically , my question is, if nonces for the blocks can be accumulated for future reuse, or not.


texts:
I've deployed an ERC20 token on the main net that you can find on etherscan.io.

The problem I'm having, as you can see on etherscan, is that totalSupply always returns 0, even if I've already minted 6M+ tokens.

This is the ABI for the totalSupply function:

[{
  "constant": true,
  "inputs": [],
  "name": "totalSupply",
  "outputs": [
    {
      "name": "",
      "type": "uint256"
    }
  ],
  "payable": false,
  "stateMutability": "view",
  "type": "function"
}]

Defined in Solidity as:

uint256 public totalSupply;

and initialised in the main contract with:

uint256 public totalSupply = 0;

I don't understand if totalSupply is correctly stored internally and it's just a problem when getting the value from outside, or if the smart contract is actually not adding the minted tokens to the totalSupply.

Any help is appreciated.

EDIT: this is the minting function (the rest of the code is uploaded and verified on etherscan):

function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
    totalSupply = SafeMath.add(totalSupply, _amount);
    balances[_to] = balances[_to].add(_amount);
    emit Mint(_to, _amount);
    emit Transfer(0x0, _to, _amount);
    return true;
}


texts:
When I am calling this code(it's a test code related to the bigger contract, but the same problem can be observed here) I am receiving an error - ParserError - expected ';' but got '.' .
pragma solidity ^0.6.12;

import "./TRC20.sol";

contract Contract1 is ITRC20{

    address token;

    function emitter() {

        emit  ITRC20(token).Transfer(msg.sender, msg.sender, 25);
    }

}

why can't I emit an event this way?
Thanks.


texts: Difference between a pruned and unpruned blockchain

texts:
At the Berlin Blockchain Meetup, Gustav Simonsson teased the Homestead release coming soon (tm) and we were discussing blockchain bloat and the current size of the Ethereum blockchain.

We discussed the pruned and unpruned blockchain and the geth fast sync option. Now I wonder:

What is the difference between a pruned and unpruned blockchain? Does the pruned blockchain still consist of blocks? Is it even a "block chain"?
What is the difference in space requirements? The full, unpruned chain is currently 7GB in size. How much space does a pruned chain require?
How about pruned fast-sync clients to light clients? If the space requirements are lower, isn't it better to use fast-sync clients rather than unsafe light clients?

Could pruned chain clients be considered as light clients?


texts: Do I need to build my own Ethereum block explorer to read my own tokens and smart contract?

texts: I'm new to blockchain. I find that Etherscan's UI/UX is too complicated for average person to use. I basically need my users to read my Ethereum smart contract transactions and to view their own tokens (which my contract issues) content and data. Must I need to build my own block explorer using open source software and customize a nice UI/UX or could I just code a simple web app and pull this data from a public node?


texts: clone pancakeswap but it's show error Unhandled Rejection (Error)

texts:
I clone pancakeswap-frontend. when run I got above error. But I can't solve this problem.

Unhandled Rejection (Error): invalid address (argument="address", value=undefined, code=INVALID_ARGUMENT, version=address/5.0.10) (argument="owner", value=undefined, code=INVALID_ARGUMENT, version=abi/5.0.7)

Please help me.


texts: Geth takes more than 26 Gb in --fast mode!

texts:
I run geth with the arguments below:

geth --fast --cache=1024 --datadir ./.ethereum

Now the datadir (.ethereum) takes more than 26Gb and the syncing process is continue. Is it OK? Because it looks like it try to download a whole database.

I've found many topics about that fast sync mode should take about 10 Gb of disk space. Maybe it is outdated? Is there anybody who have geth client working in fast sync mode? Could you please check the size of your datadir directory?

Geth version is 1.6.7
Startup logs: https://gist.github.com/ValeryDubrava/23faf1285981b6b37afe8d2c39eeb713


texts: How can I run Ethereum node to profit from transaction fees and not from minning?

texts:
I understand that I need pretty good hardware for minning. But do I need the same hardware for running the Ethereum node just to confirm the transation and profit from Transaction fees?

I have a virtual machine as virtual sever running 24/h in datacenter and there are some CPU resources iddle, I pay the same price if the machine is use 1% or 99% percent of the resources I paid.

What are the recommended HW requirment to run this node for confirming transaction and not minning.


texts:
When we initiates a transaction(let say by remix using injected web3), we will get response which includes hash of transaction as transaction id which helps to track the transaction. Before this, if the transaction  will fails to broadcast then instantly throws some error message showing transaction failure.

Before submitting to network, do transaction is validated locally? and how ?


texts: How to access error statement written with require?

texts:
From solidity 0.4.22, we can use a message with revert and require keywords to get an exact error message.  ref

  You can specify error reason strings for revert and require (support
  by tooling is still pending).

A sample contract illustrating this :

pragma solidity ^0.4.23;
contract TestExceptionHandling{
    uint public a ;
    constructor(uint _a) public{
        a= _a;
    }
    function increaseA(uint b) public{
        require(b > a, 'new value must be greater than a');
        if (b > 50){
            revert('Very large value');
        }
        a = b;
    }
}

This code compiler without nay error. This is really awesome, thanks to devs for this.

But how can I capture this error in my DAPP using web3 or so?


texts:
I'm created a form where users can submit text to a smart contract.
The text limit is 160 characters.
Some text characters / emojis are correctly counted more than once. In my form, Javascript counts this correctly.
For instance: 1⃣is has three characters: The digit one: 1,  variation selector, a Combining Enclosing Keycap.
But in Solidity, 1⃣ is counted as 7.
pragma solidity >=0.7.0 <0.9.0;

contract MyTextCounter {
    function count(string memory text) external pure returns (uint256 count) {
        return bytes(text).length;
        // 1⃣ outputs 7
    }

    function echo(string calldata text) external pure returns (string calldata textReturn) {
        return string(text);
    }
}

How can something like this be accomplished in Solidity?


texts: Evaluate the performance of a smart contract

texts:
What is the best way and tools to evaluate the performance of a smart contract. More specifically, I want to test my contract for large scale deployment by making a script that emulate real world interaction scenarios with the contract.

Any hints about how to create such a script test? should I use web3.js or truffle framework test? How to program thousand of transactions to be sent to the blockchain? and what are the relevant metrics that I could measure after the test.

Thanks.


texts:
I have been reading the documentation. But, couldn't find any relevant information. However, it would be weird if this is not provided I guess.

Thanks.


texts: What is the official method for setting a static node with geth v1.6.0?

texts: I've tried placing a static-nodes.json file in the data directory and I've tried specifying the static node in a TOML file.  Neither approach seemed to have the desired effect.