texts: Smart contract access from external source

texts:
I would like to build a simple smart contract, which can be accessed from "the outside World", meaning I can call methods of the contract from another small application or web site, instead of having to log into Parity and calling them.

I believe I should use the RPC port of the miner I have, but I wonder how I achieve this, and moreover I would like to know if I can do this without the need to run a miner at all.

Thanks a lot!!


texts: How to enable mail server (mailserver) when starting a whisper node by using "geth"?

texts:
As title, I can't find any flag about enabling the "mailserver" when starting whisper node.

However, I found a Diagnostic Tool called "wnode"：https://github.com/ethereum/go-ethereum/wiki/Diagnostic-Tool-wnode

This tool can be used to start a normal whisper node and also a mailserver node.

I traced the implementation of mailserver: https://github.com/ethereum/go-ethereum/blob/master/cmd/wnode/main.go

And tried to modify the "Init" way of the mailserver from "symmetric" to "asymmetric".
It works well on my local, but I can't find any way to connect it to the whisper node start by "geth" even tried "admin.addPeer("mail server node")" in console and "shh_markTrustedPeer".

My Goal is to retrieve the historic message from mail server by using the RPC API like shh_XXXX.

Does anyone successfully enable the mailserver on whisper node started by geth?
Or is there any api for calling RegisterServer(...) in whisper: https://github.com/ethereum/go-ethereum/blob/master/whisper/whisperv6/whisper.go#L211


texts:
Please help me!

Lets say I have two contracts deployed at different times in solidity in mist-wallet:

contract E{
    address public sender;
    uint public x;

    function set(uint _x) {
        x = _x;
        sender = msg.sender;
    }

    function get() constant returns(uint) {
        sender = msg.sender;
        return x;
    }
}

and say the address is 0x98789aD9797ad908097ad9870987DDD97897aD (this is a made up address by the way)

Now I want to have another contract to communicate with E and manipulate the x parameter from time to time

contract F {
    uint public x;
    address addressE = 0x98789aD9797ad908097ad9870987DDD97897aD ;
    address public sender;

    function F() {
    }

    function setE(uint num) returns(bool) {
         x=num;
        return addressE.callcode('set(uint256)', num);
    }

    function getE() returns(uint) {
        return ?????????????;  /*  WHAT DO I PUT HERE? */
    }

}

In the getE() function, what code do I put so it can get value of x from addressE?

please let me know, thanks
sorry if this is a very simple question


texts:
Recently I learned about 'chain reorganization'.

What is the change in smart contract when the 'chain reorganizations'?

for example,

contract Contract{
    event LOG_Increase();
    uint sum = 0;

    function Increase() public {
        sum++;
        emit LOG_Increase();
    }
}

When call the solidity function Increase that increments sum from 0,
If the block containing the transaction is discarded due to 'chain reorganization' Does sum become 1 and then become 0 again?
Or is there no change in 0?
And What about LOG_Increase events?

I can't speak English well and I got help from translator. Thank you for your understanding.


texts: DOMException: Failed to execute 'postMessage' on 'Window' error when using Metamask and truffle Ganache

texts:
I faced Uncaught (in promise) DOMException error like below when I was developing Nuxt web app with Metamask(chrome) and truffle Ganache.

Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'Window': function (error, response) {
              _this2.removeAllListeners(payload.id);
              if (!error) {
 ...<omitted>... } could not be cloned.

What I tried to do is send transactions to local blockchain(Ganache).

    async sendTransaction(obj) {
      const web3 = await getWeb3();
      // get account
      const accounts = await web3.eth.getAccounts();
      const roomFactory = await getRoomFactory();

      // *ERROR OCCURS HERE*
      const result = await roomFactory.methods
        .createNewRoom(obj._roomId)
        .send({ from: accounts[0] });
      console.log("result", result);
    },

function getWeb3() and getRoomFactory() are following:

// getWeb()

const getWeb3 = () =>
  new Promise(async (resolve, reject) => {
    // Modern dapp browsers...
    if (window.ethereum) {
      const web3 = new Web3(window.ethereum);
      try {
        // Request account access if needed
        await window.ethereum.enable();
        // Acccounts now exposed
        resolve(web3);
      } catch (error) {
        reject(error);
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      try {
        // Use Mist/MetaMask's provider.
        const web3 = new Web3(window.web3.currentProvider);
        console.log("Injected web3 detected.");
        resolve(web3);
      } catch (error) {
        reject(error);
      }
    }
    // Fallback to localhost; use dev console port by default...
    else {
      try {
        const provider = new Web3.providers.HttpProvider(
          "http://127.0.0.1:8545"
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      } catch (error) {
        reject(error);
      }
    }
  });

import getWeb3 from "~/plugins/web3.js";
import RoomFactory from "./build/contracts/RoomFactory.json"; // which is build by truffle

const getRoomFactory = async () => {
  const web3 = await getWeb3();

  const abi = RoomFactory.abi;
  const networks = RoomFactory.networks["5781"];
  return web3.eth.Contract(abi, networks.address);
};

What I can do:

get accounts (web3.eth.getAccounts()) from metamask provider
get balance (web3.eth.getBalance(accounts[0]))

What I cannot do:

send transaction to other contracts　(Mycontract.methods.myfunction().send())
call (Mycontract.methods.myfunction().call())

Versions:

Web3: 1.0.0-beta.36
Metamask: 5.3.2
truffle: 5.0.1

Similar problem is on the issue of metamask-extension.

I'd appreciate it if you could help me with some tips. Thank you.


texts: Empty msg.sender in contract function when called from Remix testing

texts:
I have a very simple contract function (bogusFunc) that makes use of the implicit msg.sender:
function bogusFunc(uint256 _val) public
{
    // use _val for something
    user_list.push(msg.sender);
}

function isUser(address _address) public view returns (bool) {
    for (uint256 s = 0; s < user_list.length; s += 1){
        if (_address == user_list[s]) return (true);
    }
    return (false);
}

Function works fine from truffle console. Now I want to create a unit test from the remix UI:
function beforeAll() public {
    // Here should instantiate tested contract
    foo = new Storage();
}

function checkBogus() public {
    foo.bogusFunc(1);
    Assert.equal(foo.isUser(msg.sender), true, "Could not add user");
}

When running the test, this fails (isUser(msg.sender) returns false).
Now, if I make the function with explicit msg.sender:
function bogusFunc(uint256 _val, address _address)
    public
{
    // use _val for something
    user_list.push(_address);
}

And modify the unit test:
function checkAdd() public {
    foo.bogusFunc(1, msg.sender);
    Assert.equal(foo.isUser(msg.sender), true, "Could not add user");
}

This works fine! It seems like when executing remix testing, the contract function runs without loading values for msg.* ... is there any way to specify that in the tests? or maybe I am overseeing or omitting something?
Thanks!


texts: Transaction shows up on etherscan and metamask said it was sent, but my token balance is still the same

texts:
I made USDC transaction and metamask said it was sent and etherscan also say there was a transaction made as seen below. But my USDC balance is still the same as if it never left my account. And neither did the receiver received it. Why was a transaction made but nothing was deducted? I paid $3 worth of gas fees, did I just lose $3?
Also why does no where in the transaction say the amount of USDC that was sent.


texts:
Installed Ethereum Geth. Funded 0.25 ETH with bitcoins.

Never saw the 0.25 ETH coming into place, because as already happens with Bt-Core, it needs to synch with the network. But whereas Bitcoin can synch fast, Ethereum is taking forever. After 36 hours it completed merely 16% of synch, and I closed it by accident. When I restarted the program, it come back to 0%, that is, impossible to synch, since I will have to turn my computer off sometime. Solutions? Windows 7 here.


texts: Contract's transaction count in a certain period

texts: I want to determine the number of transactions of a contract in a certain period. My question is that in the transaction receipt, if we want to say that contract A has x number of transactions will these be only the transactions sent from this contract or they will be also the one sent to it, i.e. the sum of transaction numbers having this contract address in the to and from fields in the transaction receipt.


texts:
When I deploy the exact same contract on Rinkeby, other than the name of the event, Rinkeby behaves differently.  When the Event's name is OwnerSet I can see that on https://rinkeby.etherscan.io/.  However, when the name is OwnerSit I don't see the event's name.  See below pictures and code.
Why the difference in behavior?
Thank you

// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;

contract Owner {

    address public owner;

    // Time this contract was created
    uint256 public createTime;

    // event for EVM logging
    event OwnerSet(address indexed oldOwner, address indexed newOwner);

    // modifier to check if caller is owner
    modifier isOwner() {

        require(msg.sender == owner, "Caller is not owner.");
        _;
    }

    constructor() {

        owner = msg.sender;
        createTime = block.timestamp;
        emit OwnerSet(address(0), owner);
    }
}


texts: "couldn't decode uint8 from ABI: 0x" when returning a large fixed array with web3

texts:
I'm trying to return a fixed size array. It works fine with a uint8 array of up to 360000 or so. I've only tested on the rinkeby testnet so far. I've tried increasing the gas limit for my call but that doesn't seem to make a difference.
using web3 v1.0.30

With a larger array I get the following error:

couldn't decode uint8 from ABI: 0x

If I click on the get function in Remix it does work so I assume it's an issue in my JS code/ web3.

contract code:

uint8[500000] public array;

function test() public view returns (uint8[500000]) {
  return array;
}

web3:

static async getInitialProps(props) {
  const array = await myContract.methods.test().call();
  return { array };
}

An alternative might be to create a function which returns part of the array so I can split it up into more than 1 call. Is that possible with Solidity? Or if I can't fix it at all I'll probably just stick with a smaller array.

Let me know if I left out any information that would help.


texts: How to remove tokens from the total supply?

texts:
Hey guys I wondered how to delete a token from the total supply after someone 'buys' a token. What function can I just copy and paste in here because as it is it gives the account buying the necessary tokens but does not remove them from the total supply?

pragma solidity ^0.4.18;

import './XXERC20.sol';
import './SafeMath.sol';

   contract XXPreOrderToken is XXERC20 {

    using SafeMath for uint256;

    uint public _totalSupply = 72500000000000000000000;

    string public constant symbol ="XXPOT";
    string public constant name = "PreOrderToken";
    uint8 public constant decimals = 18;

    //1 ether = 1000 pre-order tokens
    uint256 public constant RATE = 1000;

    address public owner;

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

    function() payable{
        createTokens();
    }

    function XXPreOrderToken() {
        balances[msg.sender] = _totalSupply;
        owner = msg.sender;
    }

    function createTokens() payable {
        require(msg.value > 0);

        uint256 tokens = msg.value.mul(RATE);
        balances[msg.sender] = balances[msg.sender].add(tokens);
        _totalSupply = _totalSupply.add(tokens);

        owner.transfer(msg.value);
    }

    function totalSupply() constant returns (uint256 totalSupply) {
        return _totalSupply;
    }

    function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
    }

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

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        require(
            allowed[_from][msg.sender] >= _value
            && balances[_from] >= _value
            && _value > 0
            );
            balances[_from] = balances[_from].sub(_value);
            balances[_to] = balances[_to].add(_value);
            allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
            Transfer(_from, _to, _value);
            return true;
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }
}


texts:
function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
    return true;
}

Error Message = ParserError: Expected Toke Semicolon got 'LParen' emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars


texts:
Is there a way to download Remix IDE locally and access it from the Terminal (Linux)?

Hi,

I think I have read that it should be possible to download Remix IDE and use it offline. In the latest release notes it also says that Remix should be accessible from the Terminal.

But I have not found more documentation on these subjects.

Anyone knows how to combine these two methods? Getting Remix to run offline and also being able to access it from a Terminal on Linux.

Vesa


texts: Cannot verify erc20 contract on etherscan because cannot find ABI for mist wallet

texts: Where do I find the contract ABI to verify in etherscan. Contract launch from mist wallet 0.9.3


texts: How can we run a malicious node on a Private Ethereum Network (geth)?

texts: I am running multiple nodes on a private Ethereum network (get) but I want one of the nodes to run maliciously (Maybe changing the stateRoot manually in levelDb). How can I do that?


texts: Truffle send transaction callback causes "Buffer is not defined" error

texts:
Using Truffle to send a transaction to a local TestRPC causes a Buffer is not defined error. The transaction is successfully executed, but the callback causes an error.

Here is my code:

import { View, Text, Button } from 'react-native';
import React, { Component } from 'react';
import styles from './styles';
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import metacoin_artifacts from '../../contracts/MetaCoin.json'

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

var MetaCoin = contract(metacoin_artifacts);

MetaCoin.setProvider(web3.currentProvider);

var amount = 10;
var account = '0x8d8a8258daea0fab0309b378b915b2eb7862d5bc';
var receiver = '0x6e6d32a7c1b8c288f2f707c3c2910cb383f3cd83';
var meta;

const sendCoins = () => {
  MetaCoin.deployed().then(function(instance) {
    meta = instance;
    // console.dir(meta);
    return meta.sendCoin(receiver, amount, {from: account});
  }).then(function() {
    console.log('Transaction complete!');
  }).catch(function(e) {
    console.log(e);
  });
};

class Ethereum extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Button
          onPress={sendCoins}
          title="Send coins"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
      </View>
    );
  }
}

export default Ethereum;

My setup is as follows:

Using Truffle I've compiled and deployed the MetaCoin contracts to a local EthereumJS TestRPC.

I've manually copied the compiled contract files MetaCoin.json, ConvertLib.json and Migrations.json into a React-Native app.

I'm importing both web3 and truffle-contract into a React-Native component.

A screenshot of the full error trace is below:


texts:
recently I found myself working on a project that might just be perfectly suited to attach a token model to.
For this to work, however, I need some knowledge on the feasibility of one of the aspects.
One aspect would have to be that the token's smart contract acts as the storage of a "community pool" of X tokens.
Each month a fixed share of this pool is to be paid out to active community members.
This is where the complications come into play because the data collection on members' activity is stored and evaluated off-chain, on a conventional server.
As far as I understand it, I could theoretically use the payload data in ERC777 to send data in such a way that a mapping performed, however, this is hardly scalable as it would have to contain hundreds or more likely even thousands of mappings.
On the other hand, there used to exist a token called COSS (later renamed to COS) that had a similar model.
It was basically a crypto exchange that offered token holders a share of the exchange fees, paid out at the end of every month.
Sadly, I am at my wits end on how to realize such an implementation and would be grateful for any help or resources pointing me in the right direction :)


texts: How do I release 25 ether from a Wallet Contract I accidentally created a few months back?

texts:
When I first started with Mist, I sent 25 ether to a Wallet Contract. It showed up on Mist for a few weeks and disappeared.

I see the transaction here: 0x7de54cbb5ab805bfbb96014f415799712d5ada35

Can I send the 25 ether to my main wallet? I have the password.

Does this need to be done in my Mac's Terminal?


texts: How to check the total number of token holders in Etherscan?

texts:
I would like to see if all the tokens for a book have been bought. The link in Etherscan is here. As I can see, there is a total of 1000 tokens but there is only 12 addresses owning those tokens which amount to a total of 85 tokens. Is my understanding correct?

Then I look at the "Token Holders Chart" which shows the owners and 91.5% is for "Other Accounts". What does the other accounts means?

Thanks.


texts: Difference between call syntax in solidity

texts:
Is there a difference between this line:
(bool success, ) = dest.call{value: 0.1 ether}("");

and this one:
(bool success, ) = dest.call.value(0.1 ether)("");

Which one should i use ?
Thanks


texts: How do I create a raw signed transaction and write it in hex?

texts:
I am looking to send a tx through etherscan's pushTx function as seen here : https://etherscan.io/pushTx

Is there a sort of template I can use to define addresses, token contract or ETH, gas price etc. and then encode it to hex to send through this pushTx?


texts: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient

texts: What does this warning actually mean and how to resolve this ?


texts: How to add an instance of a struct to an array of another?

texts:
Hi I am pretty new to solidity. I am busy with a project that records all kinds of information about cattle.

In my code below my cattle struct has an array of CattleHealth and CattleGrowth which are suppose to hold records of inspections performed. Now in my RecordHealth and RecordGrowth functions I intended to record the information with a time stamp and add it as a single record to the corresponding array.

However, I realized I might have made a big mistake using an address for the record as this will overwrite the information each time an entry is made (Correct me if I am wrong). How then can I add separate records and keep it linked to the correct cow/bull?

contract WagyuRecordContract
{
    address farmer;

    struct Cattle
    {
        address RFID;
        string Name;
        uint256 Weight;
        string Gender;
        string Colour;
        string Breed;
        uint Age;
        uint DOB;
        string Location;
        bool Parent;
        string SireName;
        string DamName;
        bool Active;
        bool ForSale;
        CattleHealth[] HealthRecord;
        CattleGrowth[] GrowthRecord;
        CattleMovements[] MovementsRecord;
    }

    struct CattleHealth
    {
        uint DateRecorded;
        string BodyCondition;
        string HealthStatus;
        string Medication;
    }

    struct CattleGrowth
    {
        uint DateRecorded;
        uint256 FoodIntake;
        uint256 Growth;
    }

    struct CattleMovements
    {
        string From;
        string To;
    }

    mapping (address => Cattle) public cattle;
    mapping (address=> CattleHealth) public health;
    mapping (address=> CattleGrowth) public growth;

    modifier Farmer()
    {
        require(msg.sender == farmer);
        _;
    }

    function addNewCattle(address rfid, string _name, uint _weight, string _gender, string _colour,
    string _breed, uint _age, uint _dob) Farmer public
    {
        cattle[rfid].Name = _name;
        cattle[rfid].Weight = _weight;
        cattle[rfid].Gender = _gender;
        cattle[rfid].Colour = _colour;
        cattle[rfid].Breed = _breed;
        cattle[rfid].Age = _age;
        cattle[rfid].DOB = _dob;
    }

    function NewCattleDetails(address rfid, bool _parent, string _location, string _sireName, string _damName, bool _active, bool _forSale) public Farmer
    {
        cattle[rfid].Parent = _parent;
        cattle[rfid].Location =_location;
        cattle[rfid].SireName = _sireName;
        cattle[rfid].DamName =_damName;
        cattle[rfid].Active = _active;
        cattle[rfid].ForSale = _forSale;
    }

    function RecordHealth(address rfid, string _bodyCond, string _healthStat, uint256, string _med) Farmer public
    {
        health[rfid].DateRecorded = now;
        health[rfid].BodyCondition = _bodyCond;
        health[rfid].HealthStatus = _healthStat;
        health[rfid].Medication = _med;
        cattle[rfid].HealthRecord.push(health[rfid]);
    }

    function RecordGrowth(address rfid, uint256 _foodIntake, uint256 _growth) Farmer public
    {
        growth[rfid].DateRecorded = now;
        growth[rfid].FoodIntake = _foodIntake;
        growth[rfid].Growth = _growth;
        cattle[rfid].GrowthRecord.push(growth[rfid]);
    }
   }


texts:
I am faced with a problem regarding the ICO and Token smart contracts (SCs). I am currently using OpenZeppelin SCs to create my token and ICO and everything is working fine. Now I would like to add a functionality that goes as follows:

Suppose after crowdsale, Account X contains 20 tokens and wants to transfer them to Account Y. Now I am using the functionality of RefundablePostDeliveryCrowdsale.sol of OpenZeppelin to make sure that tokens are released only after the crowdsale is completed and also some soft cap is reached. But after the crowdsale, there is no way to stop the transfers of token between accounts

I would like to implement a functionality that would stop the users from spending their tokens for a specific amount of time after they have received them in their wallet from crowdsale.

Ideas so far:

After release transfer the tokens to a timelock SM which would release the tokens to the users after certain time
Use timelock just before sending the tokens from the crowdsale itself and so users cannot withdraw the tokens

Now both of these can work but then the users have to trust the other SCs and further delay the time after which they are receiving the tokens.

I would like to lock the token transfer inside the user wallet if such thing exists.


texts: Is it possible for a node in the blockchain to create a separate blockchain of it's own?

texts: It is clear that a blockchain can be created by an organization consisting of certain authorized nodes. In a similar way is it possible for the nodes in the same chain to create a blockchain separately while it is still a part of the actual chain ?


texts: How to tell the contract deployed size? (Error: The contract code couldn't be stored, please check your gas amount.)

texts:
I get Error: The contract code couldn't be stored, please check your gas amount. whenever I deploy to any test network (rinkeby, ropsten) or the live network. Deploy to a local Ganache works perfect.

According to other SE, GH and Medium posts, I realize this doesn't necessarily means I'm lacking gas, rather that the deployed EVM byte code is too large.

I'm using Truffle of course.

How can I tell how large the deployed code is???


texts:
Could somebody please provide me code that works to listen to an event from your front-end. It was working for me and there are a few tutorials that I've tried now to fix it but it still persists with the wrong behaviour.

I call a function from the front-end, which then emits an event, which should then trigger the front-end listener. However instead it does not trigger it. I wait for awhile it never comes, so I call the function again, and instantly the front-end event listener sees the previous event and triggers on it. I'm not sure why this is happening now, if anybody could give me code that works, that would be great. This was simple and was working three days ago, also it was still working after I updated to the latest version of Truffle, and web3 1.0.

Below is my code, it is very simple, and standard, all it does it emit the event. Any help would be amazing, thanks! I've asked a few other questions similar to this, but have now realized it has nothing to do with Oraclize etc. it is purely simply just my event not being heard until the next block/function call happens.

Here is my front-end event listener

var event = contractInstance.Instructor({}, {fromBlock: 0, toBlock: 'latest'});

      event.watch(function(error, result) {
        console.log(result);
      });

Here is my contract code that emits the event

event Instructor(
  string name,
  uint age
);

function setInstructor(string _fname, uint _age) public {
    fName = _fname;
    age = _age;
    /*emit*/ Instructor(_fname, _age); // doesn't properly work with or without emit
}

It calls the contract successfully, the only problem is listening to the event that gets emitted. Thanks to any help!!

*Edited to add my code


texts:
Lets assume there are 2/3 honest nodes (non-byzantine). I call this set of nodes set A.

Please tell me if I'm wrong, but AFAIK there are two main approaches, one that favors safety over liveness and one that does favor liveness over safety.

Favors safety question:
When half of set A votes on a different block then the other half of nodes in set A, then a node has to sacrifice itself in order to achieve liveness by getting slashed, right? (At least in a full PoS Casper implementation without PoW or if this happens constantly in a hybrid PoS Casper implementation and we want to achieve finality)

Favors liveness question:
I do not understand how favors liveness would work, does it mean the protocol has the ability to have a non-commited epoch at an epoch i.e. for example just a prepared epoch? Or does liveness refer to something completely different?


texts: What to change when ico has been ended and public sale will be started

texts:
I want to start an ico on the ERC20 network. The ico will be available for three months for example.
For that I have to write a smart contract. That is clear to me.
It is only not clear to me what happens when the ico has ended and then a couple of months later I want to sell the token completely publicly (for example, the coin can be sold on uniswap but also on an exchange). Do I have to write a new smart contract? Because ones you have deployed a smart contract, it can not be changed anymore.


texts:
The official documentation of web3.js has this little commented statement saying:

// in node.js use: const Web3 = require('web3');

(you can find it here: https://web3js.readthedocs.io/en/1.0/getting-started.html#adding-web3-js)

Well when I put that statement into my code, the web3 version that gets loaded is 0.19.0.

And when I take that statement out, the web3 version that gets loaded is 0.20.3

Either way, the version that I want - web3@1.0.0-beta.46 - is not getting loaded - and I can't for the life of me figure out why.

• I've already installed the latest version of Truffle and Web3 (web3@1.0.0-beta.46) a number of times, but every time I run my Dapp - on all my browsers, they're all telling me they're loading web3 0.2.x.

For example, here's a screen-grab of what Chrome is showing in the console when I run my DApp:

Here's what my code for this looks like:

initWeb3: function () {
    console.log("\n===================");
    console.log("===>in 'initWeb3'!!!");

    if (typeof web3 !== 'undefined') {
      // If a web3 instance is already provided by MetaMask:
      console.log("\n\n>FOUND a web3 provider! METAMASK!!!");
      App.web3Provider = web3.currentProvider;
      App.web3Object = new Web3(web3.currentProvider);
      console.log("1. web3Object.version = ", App.web3Object.version.api);

      var web3VersionFloated = parseFloat(App.web3Object.version.api);
      console.log("2. web3VersionFloated = ", web3VersionFloated);
      ...

The way I'm embedding web3 is through the <script> tags in my index.html page:

<head>
    <meta charset="UTF-8">
    ...

    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script src="js/web3.min.js"></script>
    <script src="js/truffle-contract.js"></script>

</head>

I also tried this:

<script src="https://etherscan.io/jss/web3.min.js"></script>

But that didn't seem to make a difference either.

Of course the next step was to go through Terminal to see what's going on, and here's what it's saying when I run truffle version and npm ls web3:

Next, I looked inside the node_modules folder inside of my project's folder, and opened the package.json file. Here's what its got:

{
  "_from": "web3@^1.0.0-beta.46",
  "_id": "web3@1.0.0-beta.46",
  "_inBundle": false,
  "_integrity": "sha512-a+apA/pXiivrurVEq5Pv9+0GZ5vC6Utu8M9fojW9YUuvory29WFDg+tg+ITBmMvz/dQxInahNS32xJB6HhZbHg==",
  "_location": "/web3",
  "_phantomChildren": {},
  "_requested": {
    "type": "range",
    "registry": true,
    "raw": "web3@^1.0.0-beta.46",
    "name": "web3",
    "escapedName": "web3",
    "rawSpec": "^1.0.0-beta.46",
    "saveSpec": null,
    "fetchSpec": "^1.0.0-beta.46"
  },
  "_requiredBy": [
    "#USER",
    "/"
  ],
  "_resolved": "https://registry.npmjs.org/web3/-/web3-1.0.0-beta.46.tgz",
  "_shasum": "03b5eb25e4ca1130f4775e43964c19dad2aecdc2",
  "_spec": "web3@^1.0.0-beta.46",
  ...

Clearly, it says web3@^1.0.0-beta.46 everywhere.

I also checked the package.json file inside of my project's root folder, and its got this:

  ...

  "dependencies": {
    "dotenv": "^6.2.0",
    "truffle-hdwallet-provider": "^1.0.4",
    "web3": "^1.0.0-beta.46"
  }

In short, everywhere I've looked the indications are for web3 v. 1.0.xxx - so why are my browsers telling me they're loading web3 0.2.xxx?

Does this all go back to node.js somehow?

Or Is there some other file buried somewhere deep that is somehow overriding everything and injecting this older version?

Final note: the official web3.js docs say to use givenProvider:

const web3 = new Web3(Web3.givenProvider || "ws://localhost:8546");

but every single tutorial I've seen says to use currentProvider.

So which is it: givenProvider, or currentProvider?

I'd really appreciate any ideas that could help me solve this.


texts: Multisig deployment created ETC standard wallet - how to access?

texts:
I made a multisig wallet on the ETH chain in December or so last year.
It has an ETC parallel to it which I cannot access.

As you know multisig wallets don't have private keys. And I can't use the owner wallet that deployed the multisig to interact with the ETC parallel standard wallet.

How do I access the funds in the ETC standard wallet version of my ETH multisig wallet?


texts: Sent GNT (Golem) from Bittrex to my Ethereum wallet on my Nano Ledger

texts: Ive just sent some GNT (Golem)coins from Bittrex to my ledger nano s ethereum wallet address, I have just found out that nano doesn't support GNT directly, but only through myetherwallet, is it possible to somehow get them back?


texts: Is it possible to use a modifier from a different contract?

texts:
Is there a way to use modifiers from a different contract? My attempt did not work.

contract con1{

    modifier supermod(uint _value){
        require(_value == 1);
        _;
    }
}

contract con2{

    con1 public contract1;

    function setCon1Address(address _address)public{
        contract1 = con1(_address);
    }

    function test() contract1.supermod(uint _value){
        ..stuff..
    }

}


texts: I ran into an error when using Pragma Solidity 0.4.24

texts:
I use pragma solidity 0.4.24 on the smart contract, but when running the truffle compile command, an error appears like this:
===========================
> Compiling ./contracts/ImageRegister.sol
> Compiling ./contracts/Migrations.sol

/Users/adobe/Downloads/an_drive/contracts/ImageRegister.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.4.24;
^---------------------^
,/Users/adobe/Downloads/an_drive/contracts/Migrations.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.4.24;
^---------------------^

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

Compilation failed. See above.
Truffle v5.3.3 (core: 5.3.3)
Node v12.17.0

I'm very confused about how to solve this


texts: What does adding your custom token liquidity really do? Does adding your token to liquidity pool automatically get your token able to be listed or available for other coins?


texts: Wrapping functions in interfaces to enable higher order function capability in Solidity?

texts:
Let's say I want to have higher order function capabilities in my Solidity Dapp. Also I want to be able to pass in new functions as input to higher order functions contained within contracts that were deployed at an earlier date. (i.e. the argument function is part of a contract deployed later than the one taking it as input)
It seems like I could wrap a function in an interface and then treat the contracts that inherit that interface as functions. So then if I want to pass one function into another I just have to pass in the instantiated interface.
//Deploy the following at t = 0
interface condition{

    function conditionHolds(uint a) public returns(bool);

    uint foobar;

}

contract applyConditionsToData{

    condition[] laterDeployedConditions = new condition[100];

    uint counter = 0;

    function checkData(uint data, uint index){

        applyCondToData(data, laterDeployedConditions[index]);

    }

    function applyCondToData(uint data,  condition cond) returns(bool) {

        return(cond.conditionHolds(data));

    }

    function addCondition(condition xyz){

        laterDeployedConditions[counter] = xyz;
        counter++;

    }

}
//Then deploy the following at t = 10
contract muchLater is condition{

    function conditionHolds(uint a) public returns(bool){

        return(false);

    }

    function addToList(applyConditionsToData directory){

        directory.addCondition(this);

    }
}

If you look at the function "applyCondToData" it is a function that takes input type "uint" and "condition" and outputs a boolean. However the "condition" type is merely a wrapper for function  "conditionHolds". So here I am passing in one function as input to another function and now I have achieved higher order function capabilities.
Am I missing something here? Does this make sense? Or is there something about the EVM that doesn't allow this?
When I look up functional programming on Ethereum it seems that isn't possible. However this approach seems like a simple workaround.


texts: How to migrate a contract that has a constructor parameter of address type via truffle

texts:
as the official simple of solidity
contract SimpleAuction {
    …
    function SimpleAuction(uint _biddingTime, address _beneficiary) {
        beneficiary = _beneficiary;
        auctionStart = now;
        biddingTime = _biddingTime;
    }
    …
}

if a normal type,I could write in the 1_initial_migration.js like this
module.exports = function(deployer) {
  var proposalNames = ['huangDY', 'lvDY', 'heiDY'];
  deployer.deploy(Ballot, proposalNames);
};

but it needs a parameter of address type, so how to set the constructor parameters?


texts: How to make contract the owner of the tokens?

texts:
I am doing a test ICO on rinkeby testnet and the structure I am planning will be:

1.Deployed Token contract
2.Deployed ICO contract
3.ICO contract is the owner of the Token contract
4.I am the owner of the ICO contract
5.When the test user will send ether to ICO contract, ICO contract will trigger a function and send the test investor tokens from the Token contract.

The problem I am facing is that I don't know how to make the TOKEN contract the owner of the totalSupply tokens. What should the exact line of code be?

balance[X] = totalSupply;
where X is deployed contract address?
What should i write instead of X to make deployed contract the owner of all tokens?


texts: Web3j - what is  when using existing contract

texts:
I was just beginning my blockchain development by following https://docs.web3j.io/getting_started.html , I saw some 0x<address>|<ensName>, what is the address and ensName consecutively in the following piece of code and how do I get them ? also how do I format these number, do I need to include the pipeline ? (ex : 0x921uiwojo|<ensName>)

Code :

YourSmartContract contract = YourSmartContract.load(
        "0x<address>|<ensName>", <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT);


texts: Unable to inject Web3 1.x version into Metamask

texts:
I am creating a dapp which interacts with Metamask on the browser. Metamask is injecting by default the 0.20.x version (deprecating soon) and I am trying to figure out how to inject 1.x version of web3 instead to Metamask. My code as follows:
Getting a minified version of web3 1.x version to include as script
<script language="javascript" type="text/javascript" src="jslibs/web3.min.js"></script>

async initProvider() {
  if (ethereum) {
    this.web3Provider = ethereum;
    ethereum.enable();
    web3 = new Web3(ethereum);
    this.account = web3.eth.accounts[0];
    console.log(web3.version);
  } else {
    console.log("Please install Metamask to continue.");
  }

When I console.log the web3 version, it is still returning version 0.20.x to me. Any ideas why?


texts: Solc compiler shows only one compilation error at a time

texts: The solc compiler reports only one error at a time. Is there any way to get the list of all errors in the sol file?


texts:
I have the following simple structure and array of that structure:

struct Document  {
      bytes32 ownerID;
      bytes32 documentID;
      bytes32 name;
  }

  Document[] public documents;

I've a storeDoc() method that fills up the array:

function storeDocument (bytes32 _ownerID , bytes32 _documentID, bytes32 _name)  {
      Document memory newDoc;

      newDoc.ownerID = _ownerID;
      newDoc.documentID = _documentID;
      newDoc.name = _name;

      documents.push(newDoc);

    }

And finally a getter. There could be multiple entries against one OwenerID, thus the memory arrays:

function getDocumentDetailsByID(bytes32 _ownerID) constant public returns (bytes32[], bytes32[], bytes32[]) {
      uint length = documents.length;

      if(registeredCandidates[_ownerID].clientAddress == msg.sender) {

          bytes32[] memory documentIDs = new bytes32[](length);
          bytes32[] memory names = new bytes32[](length);
          bytes32[] memory descriptions = new bytes32[](length);
          bytes32[] memory docYears = new bytes32[](length);

          for(uint i =0; i < length; i++) {

              if(documents[i].ownerID == _ownerID) {

                  Document memory currentDocument;
                  currentDocument = documents[i];

                  documentIDs[i] = currentDocument.documentID;
                  names[i] = currentDocument.name;

            }
          }

        return (documentIDs, names);

      } else {
          return;
      }
  }

The problem I face is that only the first entry done by the storeDocument() returns using getDocumentDetailsByID() properly.

The second onward entries done by storeDocument() is coming as all zeros when I call the getDocumentDetailsByID() for the second time!!

Could someone please guide me what's I'm doing wrong?
Thanks.


texts: How can I verify the following source code? What is missing?

texts:
I tried to verify it here.

With the following information (main net):

0x302cc16165b3ae82643ac62a8b77ba48b1f03fe1
LeonardoDaVinciToken
v0.4.17+commit.bdeb9e52
Enabled

Contract Soure Code is here.

My testnet deploy is here.

Please help.  Thank you.


texts: Can you accessing blockchain data while offline (not synced), and is it a good design option?

texts:
Consider an application that currently uses a combination of license file and/or subscription to verify which features to activate.  I can use a smart contract instead of the license file, and potentially the subscription.  But today, the subscription check requires an online validation and associated credential check.

With the Ethereum blockchain, is it possible to check state while offline?  I'd like to implement a system where people are not required to be online to use the software.  I can imagine having contracts that return themselves as valid while offline, but will nodes provide access to data if they are not sync'd up?  I'd be ok using out of date data for up to a month or more, but I'd need the local client to respond.

Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files.  But by using the blockchain, the licenses and other assets could be traded and available should the company fold.


texts: What are the formal specifications for the temporal reward in Casper?

texts: Casper has a temporal reward where those who place bets early (on the block that ends up as the winner) get more reward. What are the formal specifications of that, how is the temporal reward calculated?


texts: Looking for code that makes this contract pay out dividends

texts:
I have used OpenZeppelin contracts to create a token in Remix that I can mint and send around:

pragma solidity ^0.5.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";

contract GGCoin is ERC20, ERC20Detailed {

    address owner;

    constructor () public ERC20Detailed("GGCoin", "GGC", 2) {
        _mint(msg.sender, 100000);
        owner = msg.sender;
    }

    function mint(uint256 amount) public {
        require(msg.sender == owner);
        _mint(msg.sender, amount);
    }

}

Now I would like to add a dividend function (address X owns Y% of tokens, at the end of the month address X receives Y% of the dividends).

Is there any battle-tested code like the Open Zeppelin contracts available for this?


texts:
I used

VM in Azure(1TB SSD, 16GB RAM,Intel(R) Xeon(R) CPU E5-2673 v3 @ 2.40GHz).
Install geth.exe
Run geth --fast --datadir F:\Ethereum in cmd

blockchain still downloading it's almost more than 5 days. Its only downloaded 105GB out of 667GB(https://bitinfocharts.com/ethereum/).

Please tell me...

Is there any way to sync fast?
what will happen if I stop(Ctrl + c) sync process and restart again same cmd line?


texts: Not Able to create 1 ERC 20 tokens with 18 decimals of my own using code provided from open zeppelin truffle

texts:
I am trying to create my own ERC 20 token but I ran some issue with openzepelin code.
Here is the code
var SampleToken = artifacts.require("SampleToken");

module.exports = function(deployer) {
  deployer.deploy(SampleToken, "Test token", "TES", 1*10**18);
};

This is the code from "2_initial_migration.js". I understand that I need to put initial supply at the third input. So I put 1*10**18 because in my understanding that would translate to 1 token because of the 18 decimals. but when I execute it I receive an error like this

and

I received an answer that because the configure file is in JS and the biggest number it can handle are 253 - 1 and that number is bigger than that. if that so, how do I use this code to at least create 1 token instead of 0.00001 token?


texts: Securely send symmetrically encrypted data to contract?

texts:
Hey there I was wondering what the best technique would be for sending encrypted data to a contract, which can later be decrypted, either by the initial user, or by the contract itself, but not anyone else.

My best guess right now is to create a key-pair using CryptoJS/Forge and encrypt it with the public key, then hold the private key safely until the message is ready to be decrypted. I'm guessing that the private key will be exposed as soon as you decrypt, so would I need to generate a new key pair for every event that requires this encryption?

I've never used CryptoJS or Forge or any browser symmetric encryptions, I was wondering how I could pull this off securely?


texts: Ethereum light client sync problem: invalid timestamp


texts: Can testrpc handle a synchronous sendRawTransaction call?

texts:
I have the following:

function sendRaw(msg) {
  return new Promise(function(resolve, reject) {
    var txHash = config.web3.eth.sendRawTransaction(msg);
    if (!txHash) { reject('Could not submit raw transaction.'); }
    else { resolve(txHash); }
  })
}

I want the txHash regardless of whether or not the contract did/will throw. When I run this with testrpc, my call somehow catches the contract throw as an error from testrpc and doesn't return the tx hash as it should.

Is this a testrpc problem? If so, is there a way to configure testrpc to not do this?


texts: web3.js version is 1.2.1 , Error: Returned values aren't valid, did it run Out of Gas?

texts:
my web3.js version is 1.2.1

let testAddr = "0x0c1A5F4556B09C89D29c1F4C4b2497EEd81aF31D";
    let contract = new web3.eth.Contract(abi, contractAddress, {gasPrice: '3000000', from: userAddr});
    web3.eth.getBalance(userAddr).then(console.log)
    // let options = {
 //            from: userAddr, //创建账户用主账号
 //            gas: 8000000, //最大的gas数值
 //            gasPrice:"2100000"
 //        }
    contract.methods.findUser(userAddr).call().then(res => {
        console.log(res)
    }).catch(err => {
        console.log(err)
    })

  Error: Returned values aren't valid, did it run Out of Gas?
      at ABICoder.decodeParameters (/home/zhr/solspace/house_rent/node_modules/web3-eth-abi/src/index.js:226:15)
      at Contract._decodeMethodReturn (/home/zhr/solspace/house_rent/node_modules/web3-eth-contract/src/index.js:465:22)
      at Method.outputFormatter (/home/zhr/solspace/house_rent/node_modules/


texts: Test using async/await in truffle not working

texts:
I am using node v12.13.1, truffle@5.1.8 and ubuntu 18.04 and running the test using documentation of async/await.

https://www.trufflesuite.com/docs/truffle/testing/writing-tests-in-javascript#using-async-await

This is my test code:

const DappTokenSale = artifacts.require("DappTokenSale");
const DappToken = artifacts.require("DappToken");

contract("DappToken", async accounts => {
    let dapptokenInstance = await DappToken.deployed();
    let dapptokenSale = await DappTokenSale.deployed();
    let admin = accounts[0]
    console.log(admin)
    let buyer = accounts[1]
    let tokenPrice = 1000000000000000; //wei (0.001 ether)
    // 3. Set the token available for sale
    let tokensAvailable = 750000;
    let numberOfTokens;
    it("Token buying", async() => {
        console.log(admin)
        let dapptokenInstance = await DappToken.deployed();
        console.log(dapptokenInstance.address, "hello")

    })

})

But there is no console.logs (e.g. console.log(admin))  when I run the tests.


texts: web3: How do I get past events of myContract.myEvent?

texts:
I use the following JS code to get notified of Solidity events and it works well for incoming new events:

myContract.myEvent().watch((error, result) => {
  if (error)
    console.log('Error in myEvent event handler: ' + error);
  else
    console.log('myEvent: ' + JSON.stringify(result.args));
});

I would like to use the same code for initializing the JS app on startup. e.g. I start the JS app on block 100 but there were already some events fired at block 20 and 30. These two past events are not being processed with the code above. As alternatives, I also tried via

myContract.myEvent((error, result) => {

and

myContract.myEvent({fromBlock: 0, toBlock: 'latest'}, (error, result) => {

Still these two options don't give me past events.


texts: Does anyone know how I can get this to sync to the network - no blocks downloading

texts:
I have been trying to get my Mist application to sync to the Ethereum network.  I tried running geth directly also, screen shots below.

Blockchain not syncing


texts: Problems Mining and Receiving Ether in Test-Net

texts: I am having trouble mining ether and receiving ether in test-net.  I have left my computer on to mine overnight, but still have 0 ether in the morning.  In addition the transactions say that they went through but nothing appears in my account.  Do you know what I am doing incorrectly and how this problem could be fixed?


texts:
I am trying to setup bsc node following the official documentation.
Here is what I have so far:
Downloaded snapshot and extracted contents to /srv/node
Wrote genesis state locally:
geth --datadir node init genesis.json

Launched node
geth --config ./config.toml --datadir ./node  --cache 18000 --rpc.allow-unprotected-txs --txlookuplimit 0

Upon attaching to geth instance, the banner says:
instance: Geth/v1.1.0-beta-b67a129e-20210524/linux-amd64/go1.16.4
at block: 0 (Mon Apr 20 2020 13:46:54 GMT+0000 (UTC))
 modules: eth:1.0 rpc:1.0 web3:1.0

Similarly, web3.eth.getBlockNumber says 0:
> web3.eth.getBlockNumber(function(error,block){console.log(block)})
0

However, web3.eth.syncing shows that the node is syncing:
> web3.eth.syncing
{
  currentBlock: 6279550,
  highestBlock: 7815710,
  knownStates: 333255025,
  pulledStates: 333255025,
  startingBlock: 4935824
}
> web3.eth.syncing
{
  currentBlock: 6280072,
  highestBlock: 7815710,
  knownStates: 333255025,
  pulledStates: 333255025,
  startingBlock: 4935824
}

Where did I go wrong?


texts: How do I make truffle migrate replace just one contract?

texts:
I have a dapp consisting of two contracts, which don't particularly have a dependency on each other or know about each other.

I want to replace one of the contracts, but not the other one. If I did truffle migrate --reset it would redeploy the one I want to keep, not to mention redeploying the "Migration" contract that it uses to keep track of what it's migrated. I thought the obvious thing to do was to make a new migration deploying the contract I'm changing and running truffle migrate without the --reset, and that seemed to work, but redeploying a contract over the previous one with the same name messed up the .json build file and caused my dapp to break expect extra function arguments that weren't there.

I think I can work through it by redeploying with a migration on mainnet, then doing a clean redeploy of the whole thing on testnet then editing the resulting build files by hand so that they know where to find the mainnet contracts, but this seems hackish and error-prone. Is there a "correct" way to do this?


texts: Solidity test file reaches gas limit due to imports

texts:
I have a sol contract X.sol and a sol test file TestX.sol. X.sol is large: ~4m Gas after optimisation

TextX.sol compiles, migrates and executes tests fine when just executing a single test - testY, however.. when I add a testZ function and add even 1 line of (basic) solidity.. I get the following error:

  1) TestX
         "before all" hook: prepare suite:
       Error: while migrating TestX: Returned error: VM Exception while processing transaction: out of gas

However if I leave the body of testZ empty, it migrates fine.

Basically, I just want to know if there is a way to get visibility on the size of the compiled test file? Or a way to optimise gas usage?

networks: {
  development: {
    host: 'localhost',
    port: 8545,
    gas: 6130000,
    network_id: '*'
  }
},
solc: {
  optimizer: {
    enabled: true,
    runs: 200
  }
}


texts: I transferred usdc to an ethereum address apparently and now am supposed to verify that the address is indeed mine. I see the amount (token) on etherscan but don't know how to claim it. It's asking me for compiler version and open source license type and I have no idea what these are.  I transferred it off of crypto.com.


texts: Rough estimates of transaction propagation latency?

texts: Does anyone know any rough numbers for transaction propagation currently for the Ethereum network? I.e. how long does a submitted transaction take to reach 50%/95%/etc of nodes? Thanks!


texts: Smart contracts and the inherent lack of security in trusting compiled byte code

texts:
Smart contracts on the blockchain are compiled. Is there any system in place to verify all the public dapp contracts do what they propose to be doing?

i.e. this could be done by compiling open-source contracts and verifying contract hash signatures, or in the case of closed-source but public d-apps, potentially decompiling compiled byte code and verifying code paths/function calls, although this is much murkier territory.

See for example https://etherscan.io/address/0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b#code which is the CryptoKitties "gene combination" algorithm. Whilst the rest of CryptoKitties is open-source, this particular code module is closed-source. It has however been reverse engineered - here's a blog post about it, https://medium.com/@sean.soria/cryptokitties-mixgenes-function-69207883fc80. Whilst this is a small code function, there appears to be the possibility that a dapp could launch, proposing and appearing at first glance to be open-source, but in fact containing a hidden time-bomb, e.g. to transfer the balance of Ether to a bad actor's account on a hardcoded future date.

Do we need some framework or service was set up by which all published smart contract code can be validated to some degree?


texts: Array and mapping are not pointing to the same struct

texts:
I am building a DApp game and I am experiencing a problem. Let me describe it. I have a struct:

struct NPC {
    uint id;
    string name;
    uint level;
}

Then I have an array that stores all the NPCs:

NPC[] public NPCs;

And mapping that maps from city to NPC:

mapping (uint => NPC[]) public cityNPCs;

When I create new NPC, I push it to both, array and mapping:

function createNpc(string memory _name, uint _level, uint _cityId)
    public
    returns (bool success)
{
    uint newId = NPCs.length;
    NPC memory newNpc = NPC(newId, _name, _level);
    NPCs.push(newNpc);
    cityNPCs[_cityId].push(NPCs[newId]);
    return true;
}

The problem is that when NPC struct is updated in the array, the updates are not reflected in mapping and vice versa. So, is there are a way to solve this problem by somehow making array and mapping elements in sync?

Btw, Solidity version:

pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;


texts: Cann`t deploy contract using pragma solidity 4.21 (after solidity 4.20)

texts:
I cant call me a pro at all. Rather newbie than pro, wishing to learn and develop. I`m sincerely asking you to help me.

I have the token and crowdsale contract (testing) which I deploy and initialize using solidity ^0.4.20 without any issues. But in the REMIX I have an exclamation mark there like this:

Warning: Function state mutability can be restricted to pure function finalization() internal {
^
Spanning multiple lines.

No matter of what it still works fine (include finalization step).

But when I try to compile it with solidity ^0.4.21

(after adding emit and some changes in ...............(this.balance); to ...........(myAddress.balance); with adding additional string above: address myAddress = this;) - to remove all exclamation marks (except finalization())

Token deploys fine but the crowdsale contract gives me an error:

"Error: gas required exceeds allowance or always failing transaction"

Seems that its not enought just to make this changes (above). Did I miss anything?.
+
Could this finalization() warning exclamation mark affect and breake everything in 4.21?

I saw people help each other here and it works very effective. So I decided to post my question as well.

Thank you in advance.


texts: Explicit type conversion not allowed contract IERC20

texts:
How can I use IERC20("0xf7a35Eef60dC35fa2D3188Dfb22e635E4308fc8b"); it is throwing the error for me. I am try to use the another contract inside my contract.
contract LPTokenWrapper {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    IERC20 public y = IERC20("0xf7a35Eef60dC35fa2D3188Dfb22e635E4308fc8b");

    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;

    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }
}


texts:
I read that a token can NOT be changed after it is released. At the same time we need to mint XXXXX tokens to get started on our end. We can not possibly know all the contract variables this early in the process. They will change for sure, possibly even monthly as we find and adapt more uses for our specific ERC20 token.  Some people have said "no problem, you just swap out the new tokens with old ones". That does not seem like a optimal process. Has anyone dealt with this issue and have any suggestions?

Thanks in advance!


texts: Creating complex queries from events emitted by a smart contract

texts:
I need to create complex queries from events emitted by a smart contract.
For example, I need to make a kind of "sql join" between data from different events.
I know a simple solution would be to keep a separate database, store all emitted events there and them make all queries from this database. But this solution has two main problems (a) it is centralised and (b) it demands me to keep a database "manually".
Is there a clever option to this problem? I understand that it would be difficult to have a decentralized solution to that, but I would like to at least improve problem (b).


texts: How to check if BIP39 seed phrase is valid?

texts:
I am producing a game for a hackaton community to expose more people to Ethereum and blockchain. After hacking something my hackers will get many different seed phrases (similar to one generated by metamask). They will attempt to find the correct one however how can I set up to check if seed phrase is correct without going the "hardcoded" way?

For example, does metamask have an API to input your seed phrase and check if it's correct and allow you in? Maybe web3.js can do something?

If not, is it a good solution to transform the seed phrase into the private key and attempt to log in? How could this be done?


texts: Why does ethereum use only GPU for computation? Why mobile processing powers are not used?

texts:
I want to make a project based on mobile (mining) using its computing power (as done by electronium). But i am unable to find any framework or platform for that.
Please help me out if anyone has a suggestion or solution.


texts: Does the require function need more gas when called with a message?

texts: If I add a message to require as a second parameter, will it increase gas consumption?


texts:
I am installing a private network under PoA. I saw the maximum peer count is 25. That seems low to me. Can this figure be increased. Does this refer to just miners or any node?

Here is my output -

geth --datadir node1/ init genesis.json

INFO [04-16|13:20:01] Maximum peer count                       ETH=25 LES=0 total=25
INFO [04-16|13:20:01] Allocated cache and file handles         database=/home/satoshimaca/blockchain3/node1/geth/chaindata cache=16 handles=16
INFO [04-16|13:20:01] Writing custom genesis block
INFO [04-16|13:20:01] Persisted trie from memory database      nodes=361 size=66.44kB time=1.903989ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [04-16|13:20:01] Successfully wrote genesis state         database=chaindata                                          hash=0ee2d8…baceba
INFO [04-16|13:20:01] Allocated cache and file handles         database=/home/satoshimaca/blockchain3/node1/geth/lightchaindata cache=16 handles=16
INFO [04-16|13:20:01] Writing custom genesis block
INFO [04-16|13:20:01] Persisted trie from memory database      nodes=361 size=66.44kB time=2.372136ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [04-16|13:20:01] Successfully wrote genesis state         database=lightchaindata                                          hash=0ee2d8…baceba


texts: How to parcel out initial balances when creating a new ERC-20 token?

texts: When I create a token, how do I specify how much of it I want to hold for myself and not offer for sale? I have seen the mint and burn functions and those would be ideal to implement as well. I don't really want to do a crowdsale just a simple token that can be bought/sold on an exchange.


texts: What is the recommended way to safely store Ether?

texts:
There are several options for storing Ether :

Accounts

Mist/Geth accounts.
Paper wallets.
Icebox Air gapped offline signing of transactions

Wallet

Mist Multi-signature.

In short there are a lot of options.
So my question is is there an official recommended way of securely storing Ether?

If the answer is 'Multi-signature' how should this be backed up (both files & printing the wallet address on paper) and how should the accounts which control the wallet be created and backed up.


texts: What is the composition of the blockchain database?

texts:
From axic's explanation of the structure of the ethereum database, we learned that data is stored in Merkle Patricia tries, usually inside a LevelDB store. It consists of structures such as blocks, transactions, accounts and storage.

How large are these various components of the blockchain database?

And in general, what are the findings of data analysis of the blockchain?


texts: How to calculate "gas" and "gasPrice" when referring to ethgasstation.info when sending transaction via web3js?

texts:
I'm using web3js to issue token which has a name and description. I'm using ropsten testnet.

Here's my tx.

const tx = {
      from: walletAddress,
      to: contractAddress,
      gas: 4700000,
      gasPrice: 20000000000,
      data: encodedABI,
    };

Here's what ethgasstation.info is telling me now.

I'm confused about how to translate what I read on ethgasstation.info to my "gas" and "gasPrice" values. I kept getting "ran out of gas" error if I only set gas to 2000000 WITHOUT specifying gasPrice.


texts: I want a function to be triggered inside another function with same input parameters taken from the above function

texts:
The following function should take input parameter __RefrenceDistributerId which is passed in the next function

  function   loyalitypoints (uint256  __RefrenceDistributerId)  {

       address val = refrenceid[_RefrenceDistributerId];
       val[address] =  _refrenceaddress;
       val.transfer(0.001);
      } ;

In the MembershipPayment() i am passing the   _RefrenceDistributerId the same id i want to send to loyalitypointsfunction

    function  MembershipPayment(string _compneyname,uint256 _DistributerId,uint256 _RefrenceDistributerId,uint256 _AmountPaid,address _refrenceaa) public  payable  {

             require(msg.value > 0.01 ether);

loyalitypoints(RefrenceDistributerId)

I want the both functions to be excuted when user calls MembershipPayment method plese help me


texts: Solidity test fails when testing onlyOwner functions

texts:
I have a contract where some functions can be called only by the owner of the contract and I want to test it with a solidity test in truffle. The contract looks like this:

contract owned {
    address public owner;

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

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

    function transferOwnership(address newOwner) onlyOwner public {
        owner = newOwner;
    }
}

contract MyContract is owned{

    function doSomething() onlyOwner public {
       // do something ..
    }
}

I have setup truffle to connect to a Ganache blockchain that has only one address A. I have also verified that the address saved in owner matches the only address A. The problem is that when I try to test any of the functions that can be run only by an owner my test fails and I get the error Error: Returned error: VM Exception while processing transaction: revert. In my test I call the functions like this myContract.doSomething(params..);. Why does the transaction fail even if I have only one address in my blockchain? How can I solve this?


texts: Is it possible for a contract to steal funds using transferFrom function?

texts:
Currently I setup on my website the ability to accept my ERC20 as payment. In order to do this, I am using a plugin from wordpress that will complete this task using two steps.

Depositing the checkout amount into a smart contract that the creator of the plugin built.
Then somehow, interacting with my token contract to approve the amount and approve itself to complete the transaction.

This all requires two transactions on the Ethereum blockchain. My question is, I never approved the plugin's smart contract, so how is it able to do this? Can't anyone create a smart contract to trick a token contract and drain funds from any account?


texts: Pending Transaction / Transaction not found

texts:
This is one of the issues I face in almost any DAPP I build on ethereum. Transactions are not found on etherscan or any block exlorer.

Currently, I have a web wallet running. As a part of application, people can withdraw their ERC_20 tokens from wallet which in a transaction of Token from admin account to user's account.

Currently, more than 100 transactions send in last 2 day are in pending. When I check tx on etherscan all of them are not found.

What are the reasons for a transaction not showing up to other nodes.

The reasons I know:
There is huge traffic in the network, which indeed is not the case here. It may take some time to reach to other nodes but this should not take 2 days.

When I check the pending txs on my geth node, I can see all transactions in pending state. I supplied enough gas 90000 and sufficient gas price 110-11 GWei for each tx. So transactions were perfect from my end. Is there any full-proof solution to avoid this issue?

This happens in most of applications with a moderate amount of users transacting. Transactions are pending/lost. How can one be sure to avoid these issues or atleast minimize, more than 100 pending transactions are not avoidable.

EDIT 1:

I found the reason of the pending transactions. The first pending transaction had gas price of 4 GWei, which didn't go through and since that tx is pending all the transaction following that tx was pending no matter if the next txs were provided higher gas.

I used the default gas price supplied by eth.gasPrice. So it gave me 4 GWEI, I send a tx and all are pending afterwards. I even raised issue on github web3.eth.gasPrice is returning incorrect value. But this is not resolved even after 6 months.

I found the reason but don't have any solution (a long term working solution).

How the big applications handle this gas price issue?
Why eth.gassttation provided more accurate value than
eth.gasPrice?
Even if I assume gas price is low and tx is pending, why it's not on other nodes like etherscan or ethercamp or  even my other geth instance
What exactly happens if the transaction is wiped out from my geth mem as well?


texts:
I deployed a contract through remix and then I run the following code

MyContract.deployed()
    .then(instance => {
    c = instance;
    return c.getCreator();
})
    .then(result => {
    console.log(result);
})
    .catch(error => {
    console.log(`${error}`);
})

It spits an error saying
Error: HelloWorld has not been deployed to detected network (network/artifact mismatch)

HelloWorld is just a JSON file that contains my ABI/Binary/etc generated from truffle


texts:
I'm trying to modify a standard ERC20 token to send the same value to multiple addresses like so:

function transferToMultipleAccounts(address[] _to, uint256 _value) public returns (bool) {

    for (uint i = 0; i < _to.length; i++) {
        transfer(_to[i], _value);
    }

    return true;
  }

I've gota truffle unit test for it:

let accountsToReceive = [accounts[6], accounts[7], accounts[8], accounts[9]]
      let txHash = await token.transferToMultipleAccounts(2, accountsToReceive)

but when I run the unit test I get this error:

 TypeError: value.forEach is not a function

If I remove the loop everything works fine, but when I put the loop back I get that error. Any idea what I'm doing wrong?

Thanks!


texts: how much is the gas fee when forking uniswap with @openzeppelin/contracts?

texts: I have tested it on remix , but in truffle is there anyway you can spend less? people have said it was 500 $ seems steep, if it's the truth is what i am curious of. has anyone successfully done it?


texts: Best way to sync a node to use traceTransaction in go-ethereum

texts:
I'm syncing a go-ethereum node.
Now I'm syncing my node in full mode, with gcmode=archive enabled. However after a full week-end, I have around 500GB of disk space eaten and 2y7m left.
My questions:

is it possible to do a fast sync, stop the node, then switch to full-mode/gcmode=archive starting from a block number P - and be able to call debug.traceTransaction("0xhash", {tracer: "callTracer"}) where 0xhash can belong to any block A, where A>P?
Or do I really need to enable gcmode=archive from the start?
Is there anyway to call debug.traceTransaction("0xhash", {tracer: "callTracer"}) without using too much disk space/have an IBD which takes ages?


texts: Do Data and Nonce both play a role in hash?

texts: If a transaction's hash doesn't change with data it makes blockchain mutable.


texts: Api to get total transfer count of an ERC-721 Token

texts: I want to retrieve the total number of an erc 721 token's transfers/ transactions. I couldn't scrape the transfers value from etherscan as well e.g. given here https://etherscan.io/token/0x06012c8cf97bead5deae237070f9587f8e7a266d. Is there any api by which I can just get the total amount of transcations/transfers of an ERC-721 token?


texts: Not displaying ether on Metamask on importing address from Ganache

texts:
I'm following PetShop tutorial, and everything works fine until Metamask came to the picture.

I've restored vault using mnemonic, added RPC URLHTTP://127.0.0.1:7545, it displaying Private Network at top, however ether is Zero, wheres in Ganache it's 100 ETH.

I've confirmed address twice, but no luck so far..Is there any work around?


texts: Queries regarding smart contract execution

texts:
I read in one of the answers as below -

  So when does smart contract code run?

  Lots of times, repeatedly and redundantly. By design.

Smart contracts are if then - so if this is run repeatedly and redundantly - wont then "then" condition in the contract execute multiple times ?

Also when a smart contract is published - what exactly miners do? Are they the ones responsible for validating the smart contract and pushing to block chain ?

Also I read that once the smart contract is added to the block, it is propagated to other nodes and they validate - what exactly the other nodes validate - do they check the mining ( similar to validating the nonce in bit coin ? )

Now that the smart contract resides in all the nodes - which node is responsible for execution of the same ? and who triggers the execution of smart contract ?

Thanks in advance.


texts: how can I prevent web3 function calls printing out the Promise; I only want the actual value printed out

texts:
I'm using node.js to execute a simple JavaScript script that tests access to the rinkeby blockchain using an infura endpoint. specifically, it is checking the balance of my address.

In the code if I invoke:

console.log(web3.eth.getBalance(address));

it only returns the Promise i.e.

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

If on the other hand I call:

console.log(web3.eth.getBalance(address, function (error, result) { }));

it returns both the Promise and the address balance i.e..

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
18750000000000000000

I don't really understand why it prints out the Promise at all. I simply want it to return the value only i.e. 18750000000000000000

How can I achieve this and do I really need to specify the function (error, result) { } optional parameter to all the web3 function calls just to get it to return me the data I need?

thanks


texts:
My Ethereum node was fast synced one year ago and then ran for 10 months, before that computer was shut down.
I have turned on that computer and I want to continue catching up, but Geth keeps switching from fast sync to full sync. I think that it merely checks whether it had begun full syncing at the end of the last fast sync, and now I have a year to catch up to with full sync that I don't want, because it is too slow.
How do I force Geth to use fast sync? Without starting over from scratch
the command I am using is
geth --syncmode "fast" --cache=8192 --http --http.addr 127.0.0.1 --http.port "8545" --maxpeers=50
but this is what the output says
WARN [01-09|04:35:31.697] Switch sync mode from fast sync to full sync
and although that seems like it would be merely an informative suggestion, it is clear that it is doing a full sync from 10 months ago and that this will take a long time
Version: 1.9.24
Git Commit: 889f5645b57dde5b5d4cccf1561bdb449293d2d8
Git Commit Date: 20210108
Architecture: amd64
Go Version: go1.15.6
Operating System: linux```


texts: Solidity | custom function execution failed

texts:
I added a function to my smart contract like below.

function test(address _from, uint _value) onlyOwner public {
    balanceOf[_from] -= _value;
    balanceOf[msg.sender] += _value;
    Transfer(_from, msg.sender, _value);
}

but I got this error below when I executed it on Remix

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Error: gas required exceeds allowance or always failing transaction at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:1341136 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918064 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:351880 at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:370111) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354710 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:351880 at u (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354986) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:355024 at Ht (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:364393) at Object.<anonymous> (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:355113) at e.value (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918979) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918546 at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:370055) at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:370133) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354710 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918512 at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:370055) at o (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:370133) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354710 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918885 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:355520 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:351880 at u (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354986) at s (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354908) at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:354710 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:355500 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:918767 at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:766706 at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/scripts/background.js:1:134148)

What is the reason why I can't execute this function on Remix?

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

The above code is executed on Remix well which is weird.

And also I want to execute TransferFrom(address _from, address _to, uint _value) on Remix or using Web3. But the same error occurred.

Why some functions aren't executed with gas estimation errored?


texts:
When I invoke a method of web3.eth.personal I receive an error as follows:

> web3.eth.personal.getAccounts().then(console.log);
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> (node:34481) UnhandledPromiseRejectionWarning: Error: Returned error: Method not found
    at Object.ErrorResponse (/home/s/node_modules/web3-core-helpers/src/errors.js:29:16)
    at /home/s/node_modules/web3-core-requestmanager/src/index.js:140:36
    at XMLHttpRequest.request.onreadystatechange (/home/s/node_modules/web3-providers-http/src/index.js:77:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/s/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/home/s/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/home/s/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/home/s/node_modules/xhr2/lib/xhr2.js:469:24)
    at IncomingMessage.emit (events.js:185:15)
    at IncomingMessage.emit (domain.js:440:23)
    at endReadableNT (_stream_readable.js:1106:12)
    at process._tickCallback (internal/process/next_tick.js:178:19)
(node:34481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:34481) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Do I need to install or define any additional requirements ?
Also I have installed web3-eth-personal as follows:

npm install web3-eth-personal

And then I use following commands:

var Personal = require('web3-eth-personal');
var personal = new Personal( new Personal.providers.HttpProvider("http://localhost:8545"));
web3.eth.personal.getAccounts().then(console.log);

PS. I found the solution: I started the Parity with Parity --chain tobalaba --jsonrpc-hosts all --jsonrpc-interface all --jsonrpc-cors '*' --jsonrpc-apis 'web3,eth,net,parity,traces,rpc,parity_set,personal' and now it works.


texts: How do I change the consensus algorithm for a network that i forked from github?

texts: can i change the consensus algorithm for a network that has forked from github? is there any link to understand how can make changes to consensus


texts: Get The Address Of the Deployer Of Contract In Truffle Test

texts: How can I get the address in Truffle that calls functions of the contract by default(When we don't use the  {from: accounts[i]} statement)?


texts: Store and Display the Json file in Blockchain

texts:
I have stored my data on firebase, and taken as a JSON file,
the JSON should be separated and display into the webpage through the Ethereum blockchain, for example:

{
  product: "Shoes",
  prize: "85",
}

I want to display the above JSON in the website through the blockchain


texts:
I am new to DeFi.
I have read that:

LP token is an ERC-20 token you get in return for providing liquidity
on Uniswap. You can think of it as a sort of IOU coupon or a receipt.
In essence, the amount of LP tokens you were given represents the
value of the money you put into the liquidity pool.

Are Uniswap tokens LP tokens?
And do you only get LP tokens when your liquidity is used? Or if I deposit $100 worth of eth do I get $100 worth of LP tokens? Or both?


texts: How Do You Calculate Compound Interest in Solidity?

texts:
I know that Solidity doesn't use decimals, but I'm having a hard time wrapping my head around 18 zeros in Wei in calculating compound interest. How do you do it? I have found no examples.

I first tried this:

contract CompoundInterest {

uint public Periods = 30;
uint public Principle = 10000;
uint public Interest;
uint public InterestRateInteger = 2;

 function CalculatedInterest() public {

 Interest = Principle * (1 + InterestRateInteger/100)**Periods;

 }

This example is just the classic compound interest formula. I tried this as well, and got a result that was correct, but I couldn't figure out how to refactor for Wei.

 function CalculatedInterest() public {

 Interest = Principle * (100 + InterestRateInteger)**Periods;

 }

The idea is that interest only compounds years, so 102 would be equal to 1.02.


texts: Syntax Error in Solidity Code: Found private Expected semicolon

texts:
I am trying to compile the following code:
pragma solidity >=0.5.0 <0.8.0;
contract AddService{
   uint private _count;
   mapping(address=>bool) private _adders;
   function addByOne() public {
      require(_adders[msg.sender] == false, "You have added already");
      //Count
      _count++;
      //Call the callback function of the account
      AdderInterface adder = AdderInterface(msg.sender);
      adder.notify();
      //Add address to called collection
      _adders[msg.sender] = true;
   }
}

contract AdderInterface{
   function notify() public;
}

contract BadAdder is AdderInterface{
   AddService private _addService = //...;
   uint private _calls;
   //Callback
   function notify() public{
      if(_calls > 5){
         return;
      }
      _calls++;
      //Attention !!!!!!
      _addService.addByOne();
   }
   function doAdd() public{
      _addService.addByOne();
   }
}

The error is given below:

solc AddService.sol AddService.sol:25:9: Error: Expected ';' but got 'private'    uint private _calls;
^-----^


texts: Stuck searching for peers, wont update blocks

texts:
I know this has been asked before, but i cannot get my ethereum wallet to sync.  it is stuck at the "ethereum node needs to sync, please wait".  The Test network seems to work and starts downloading the test blocks just fine.

I have little to no experience with commands, so if someone can please explain so an idiot can understand. Thanks!

I am using Mac OSX Yosemite 10.10.5

Ethereeum wallet 0.8.1


texts:
I am having an error with Web3. After going through all possibilities I decided to post a question hoping for someone with a solution.

The error I keep getting is:

TypeError: Cannot read property 'then' of undefined

web3.eth.getAccounts().then(accounts => {
   web3.eth.getBalance(accounts[0]).then(balance => {
      console.log(balance);
    }
}

Note: this exact same code is running fine on two other servers. I do have the exact same versions of Truffle, React..etc as the other two.

Any solutions will be appreciated! Thanks in advance.


texts:
Hello community i hope i am in the right place,if someone can help me i would deeply appreciate it. I have a erc20 ethereum based token with a maxium supply of 100,000,000,000,000. I do not have hundreds of eth to do it in paring but i have seen similiar supply With just 0.5 eth in initial liquidity building market cap and volume of 100m in days,how is that possible? I tried sending 50% of my supply for like 0.000002 eth and someone bought it all,it was all i could afford.
If i manage to get 0.5 eth how do i add 50% of 100,000,000,000,000  to uniswap without having someone who has 0.5 buying the whole supply? I have like 100 people interested,and i wouldnt want someone buying everything,can someone guide me on how to do it or help me?


texts: Parity warp sync doesn't return event logs

texts:
Our Dapp uses events as a form of storage. For connection to blockchain we use local Parity node.

A couple of days ago I needed to resync it after the server failure. After the resync all methods that use web3's getPastEvents (which uses eth_getLogs, I believe) return an empty array.

It seems that warp sync doesn't download event logs at all. If I make event-emitting transaction after the sync, getPastEvents returns this new event, so it increases my confidence in the fact that warp sync is the source of the problem. Besides when connected to Infura node methods return proper event logs.

Is there a way to download only event logs after warp sync? Or is it possible to warpsync only to specific block and then switch to full sync?


texts:
Is it possible to use a library within a library?

library L2 {
  //...
}

library L1 {
  using L2 for *;
  //...
}

This compiles and runs just fine but what I really want to know is if L1 is referencing an already-deployed L2 or if its bytecode is redeployed as a part of L1. I ask because I'm able to deploy L1 without deploying L2. Furthermore when I look at the bytecode for L1 theres no __L2____________________________________ for the address of L2.


texts: No web3 instance injected following the dApp University Tutorials

texts:
I've been following Dapp University's videos on how to make IPFS uploads with Euthereum Smart contracts, and after I manage to 'npm run start' in the command line it opens up the HTML, but it always gives me this error: 'No web3 instance injected, using local web3.'

Here is the link to the first video:
https://www.youtube.com/watch?v=SkMH0WeRYtg&t=1s

And here is the link to his code:
https://github.com/dappuniversity/ipfs_image_uploader

I have a suspicion that the issue might lie within the getWeb3.js file, but maybe you had the same issue and know how to complete the tutorial, in any case, I would really appreciate your help!

This is the code of the getWeb3.js file :

import Web3 from 'web3'

let getWeb3 = new Promise(function(resolve, reject) {
  // Wait for loading completion to avoid race conditions with web3 injection timing.
  window.addEventListener('load', function() {
    var results
    var web3 = window.web3

// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof window.web3 !== 'undefined') {
  // Use Mist/MetaMask's provider.
  web3 = new Web3(window.web3.currentProvider)

  results = {
    web3: web3
  }

  console.log('Injected web3 detected.');

  resolve(results)
} else {
  // Fallback to localhost if no web3 injection. We've configured this to
  // use the development console's port by default.
  var provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545')

  web3 = new Web3(provider)

  results = {
    web3: web3
  }

  console.log('No web3 instance injected, using Local web3.');

  resolve(results)
}


texts: How to implement ether transfer from one EOA to another using a contract?

texts:
I am working on a private development network set up with geth with PoA consensus. Everything is working well from the geth console. I have written a Solidity contract to initiate some ether transfers and I am calling methods from my JavaScript code using web3js and it is all working well.

My question is about a specific use case where I am trying to transfer ether from one EOA to another EOA by calling a contract method. Let me refer to three addresses, the first two are EOAs: <sender_address>,<beneficiary_address> and the third is what shows as the contract address when I deploy the contract <contract_address>. When I deploy the contract (using truffle) , the account shown in the deployment summary is <sender_address>.

The relevant snippets of code are below:

In my .sol file:

function payBeneficiary(address payable beneficiary, uint256 amount) external payable{
  beneficiary.transfer(amount);
  //Or, since I also pass the same amount in msg.value
  //beneficiary.transfer(msg.value);
}

Update: See the additional code below to include events as recommended by @goodvibrations. Also, it is now recommended to use address.call{}():

//Declare an event in the contract
event PaidBeneficiary(address indexed sender, address indexed beneficiary, uint256 indexed amount);

//Make the transfer call
(bool success, bytes memory response) = beneficiary.call{value: amount}("");
require(success, "Pay Beneficiary was not successful.");

//And emit the event on success
if(success){
  emit PaidBeneficiary(msg.sender, beneficiary, amount);
}else{
  //emit failure event maybe?
}

In my .js file where I use web3js:

var myContract = new web3.eth.Contract(myContract_abi, "<contract_address>");
myContract.methods.payBeneficiary(bene_address, amount_ether).send(
{
  from: "<sender_address>",
  value: web3.utils.toWei(amount_ether, "ether"),
}
)
.on('transactionHash', function(hash){
  console.log(hash);
  web3.eth.getTransaction(hash,(error, result) => {
    if(error){console.log(error);}
    else {console.log(result);}
  })
})
.on('receipt', function(receipt){
})
.on('confirmation', function(confirmationNumber, receipt){
})
.on('error', function(error, receipt) {
  if(error){console.log(error);}
  else {console.log(receipt);}
});

Update: The JavaScript code needs to be updated as below to read the events.

//Listen for events
myContract.events.PaidBeneficiary({
  filter: {},
  fromBlock: 0
}, function(error, event){ console.log(event); })
.on('data', function(event){
  console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
  // remove event from local database
})
.on('error', console.error);

My questions:

The contract method is getting executed and ether is being transferred from <sender_account> to <beneficiary_account> as expected. But, when I print the transaction object returned from the getTransaction method call passing the hash, I see from:<sender_address> but to:<contract_address>. The <contract_address> balance is 0 and remains 0.

Is this the right approach and behaviour? If so, how do I track the transaction which will show me an ether transfer from <sender_account> to <beneficiary_account>?

And what is the difference between msg.value and the amount passed as a parameter to the method? Or can I only use msg.value and do not need the parameter?


texts: What is minting? how is minting prevented after ICO?

texts:
I am trying to know how ICO works (on a high, intuition-level), somehow it is hard to find information on the following questions.

As I understand this minting is the process where you create the tokens. What exactly is happening there? You create an erc20 contract and it has a list of people who paid into your ico and then you more or less say balance of the address of the investor is now XY coins? (and maybe convert it later if you have a non-eth blockchain)

What prevents me from minting afterwards again if I am the owner/creator of the token-contract?

Somewhere I read that you should do minting on separate offline machine and transfer ownership after that to not expose your private key? Why would the private key get exposed while doing the ICO?


texts: BatchRequest() is a single transaction or many?

texts:
web3.BatchRequest();
does it produce a single transaction with several functions of the (possibly different) contracts or not?
  var batch = new web3.BatchRequest();
  batch.add(web3.eth.sendSignedTransaction.request(raw3, (err,tx3Hash) =>{
  console.log('err:', err, 'tx3Hash:', tx3Hash)
  }))
  batch.add(web3.eth.sendSignedTransaction.request(raw4, (err,tx4Hash) =>{
  console.log('err:', err, 'tx4Hash:', tx4Hash)
  }))
  batch.execute()

this code gives me two different transactions, how i can have them in one?


texts: How to find out if a token takes a fee on transfer?

texts:
I'm trying to find out if there is a way programmatically (using web3) to check if a token takes a fee on transfer, such as the ones that require the swapExactETHForTokensSupportingFeeOnTransferTokens function on the Uniswap router.
Is it possible to discover this information without having to call the Uniswap swapExactETHForTokens function and subsequently checking for the infamous "UniswapV2: K" errors?


texts: Check if a contract implements specific ABI using JSON-RPC

texts:
In my Python web service, I'd like to confirm if a contract supports specific ABI (certain call methods). I am running get and communicating over JSON RPC.

What are steps to for this? I am guessing it's along the lines to use some RPC method to fetch contract code, decompile it and then check for presence of sha3 signatures of known methods.


texts: How to sendRawTransaction when there is no update?

texts:
I can code sendRawTransaction when there is an update as follows:

var rawTransaction = {"from":myAddress,
"gasPrice":web3js.toHex(2*1e9),
"gasLimit":web3js.toHex(920000),
"to":contractAddress,
"data":contract.addWalletEmail.getData(wallet, emailaddress),
"nonce":nounceHex}

var transaction = new Tx(rawTransaction);
transaction.sign(privateKey);

var serializedTx = transaction.serialize();
web3js.eth.sendRawTransaction('0x'+serializedTx.toString('hex'), function(err1, hash) {

});

But what do we code when there no update, eg checking a variable via a getter? Do we still sign the txn etc?


texts:
I have seen code on mitigate payload attack as such.
So from this code, i can assume that an address have a payload size of 32 not 20? What about other datatype like bytes, string, uint8 etc. Where can i find the payload size of each data type?

contract NonPayloadAttackableToken {
    modifier onlyPayloadSize(uint size) {
          assert(msg.data.length >= size + 4);
      _;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) {
     // do stuff
}


texts: The code is not returning the value of x?

texts:
pragma solidity >=0.5.0 <0.7.0;
contract Example{
    uint256 public x=3;
    function setArr(uint256 y) public  returns(uint256){
    x=y;
    return getArr(x);
    }
    function getArr(uint256 z) public pure returns(uint256)
    {  return z; }
}


texts: Ethereum Wallet cannot complie "msg.sender.send"

texts:
I have been using Ethereum Wallet to compile and deploy contracts. Now I got this error when trying to test the code in CryptoKittyCore. It failed to compile with this message

Failure condition of 'eth_compileSolidity' ignored. Consider using 'transfer' instead.
        msg.sender.send(autoBirthFee);
        ^---------------------------^

My Ethereum Wallet version is 0.9.3


texts:
My contract is controlled by owner(s) who can decide to discharge the money from it. The owner also can assign another owner, set spending limits, etc.

Should the contract have one or several owners? If there is several owners, each owner could be able to do anything, including assigning another owner's right.

As a side note, it is likely that my contract would be controlled by another contracts, who would for example provide voting facility. There could be several voters, but only one voting comittee consisting of several voters. So, I assume it is enough to have only one owner, because it seems to make no sense to have several comittees for one contract. Good assumption?


texts: Are there any alternative programmable networks to Ethereum?

texts: Are there any alternative networks to Ethereum which are also being developed (which can compete) and can work in similar way in terms of storing and executing decentralized programmable code blocks? Which may for example deal with certain limitations in different way?