texts: deployment of a functioning contract (testrpc) to ropsten with truffle/geth

texts:
I've developed a smart contract using truffle and testrpc, which can be found on GitHub here.

At this point I want to deploy it to ropsten, but I can't figure out how to do that.

After consulting this question/answer, I attempted to concoct a deployment for my smart contract as follows:

module.exports = {
  networks: {
    localhost: {
      host: "localhost",
      port: 8546, // for ropsten expose this one
      //port: 8545, // expose this one for testrpc
      network_id: "*" // Match any network id
    },
// for ropsten uncomment all of this
// for testrpc comment it all out
    ropsten: {
      host: "localhost",
      port: 8545,
      network_id: "3"
    }
  }
};

and here's how I tried to execute the deployment:

> truffle migrate --network ropsten

Using network 'ropsten'.

Running migration: 1_initial_migration.js
    Deploying Migrations...
    ... undefined
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: exceeds block gas limit

This is a screenshot of the full terminal output:

My question is, how can I deploy this simple contract to ropsten?

EDIT:

Found this:

but it didn't seem to help, i.e. still getting an error:


texts: How to instantiate an array of struct inside a struct

texts:
Collection[] public collections;

struct Book {
    string name;
    address writer;
    bytes32 proof;
}

struct Collection {
    Book[] books;
    address collectionCreator;
}

// Question: how to push a new collection?
function newCollection() public {
    collections.append(Collection({
        collectionCreator: msg.sender,
        // ISSUE HERE
        books: <HELP>
    }))
}

How to instantiate this new array of a struct inside a struct?


texts: Can I send ether when a contract creates a new contract?

texts:
Is it possible to do something like

    registry = new assetRegistry.value(1 ether)();

?

This is particularly useful when the constructor function of assetRegistry calls the ethereum alarm service, because the alarm service takes a fee


texts: Solidity | Wallet.transfer(amount) on Smart contract

texts:
I want to transfer ether to account on my Smart Contract like below.

function withdrawEther(uint amount, address sendTo) external {
    sendTo.transfer(amount);
    EtherWithdraw(amount, sendTo);
}

And I also want to test on Ropsten testnet working with REMIX IDE.
What I want to know is that how the transfer works on smart contract? Who send the ether to sendToaddress?
Can smart contract hold ether or erc20 token? so that the smart contract transfer ether to other account?


texts:
I'm getting these errors while executing

npm install web3

How could i fix this?


texts: Mix: In the sample project, where is the "contracts" JS global defined?

texts:
So I trying out the Mix IDE (1.03), and looking at the .html file from the sample project, there is a "contracts" global. Where is it defined?

function get() {
  var param = document.getElementById('query').value;
  var res = contracts['Sample'].contract.get();
  document.getElementById('queryres').innerText = res;
}

function set() {
  var key = document.getElementById('key').value;
  var res = contracts['Sample'].contract.set(key);
}


texts: Calling smart contract on private Geth network using Esp32/arduino

texts: I'm trying to call smart contract deployed on private geth blockchain. I couldn't find relevant library on ESP32/Arduino to interact with smart contract. What should I do?


texts: Call a function with an address attached (Solidity React)

texts:
I'm trying to make a frontend of calling a function with an address attached:

function getAvailableAllocation(address _addr)
  constant
  returns (uint ethAvailableAllocation)
{
  return investorActions.getAvailableAllocation(_addr);
}

Here is onSubmit function:

onSubmit = async event => {
  event.preventDefault();

  const accounts = await web3.eth.getAccounts();

  await fund.methods.getAvailableAllocation(this.state.value).call({
    from: accounts[0],
    address: this.state.value
  }).then(console.log);

Here is onSubmit form

<form onSubmit={this.onSubmit}>

Available allocation

Get the remaining available amount in Ether that an investor can subscribe for

    Your ethereum address
    <input
      value={this.state.address}
      onChange={event => this.setState({ address: event.target.value })}
    />

    <button>Get available allocation</button>
</form>

When I use an address passed it consolelog the right result. Like so: fund.methods.getAvailableAllocation('0xbe4B62ac6C98bf755dBf217e24FA502A00eC9cf3').call

What I'm doing wrong?


texts:
If I try to compile the following example code in Mix it doesn't work. As soon as I change the name from Coin to Coins it starts working as supposed? Is this a bug or a feature?

contract Coin {
    // The keyword "public" makes those variables
    // readable from outside.
    address public minter;
    mapping (address => uint) public balances;

    // Events allow light clients to react on
    // changes efficiently.
    event Sent(address from, address to, uint amount);

    // This is the constructor whose code is
    // run only when the contract is created.
    function Coin() {
        minter = msg.sender;
    }
    function mint(address receiver, uint amount) {
        if (msg.sender != minter) return;
        balances[receiver] += amount;
    }
    function send(address receiver, uint amount) {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Sent(msg.sender, receiver, amount);
    }
}


texts:
I am doing the Ethereum and Solidity: The Complete Developer's Guide and I am unable to resolve this error.
The code is expected to do a transaction via
await factory.methods
.createCampaign(this.state.minimumContribution)
.send({
    from: accounts[0]
});

But it is not behaving properly and giving me the following error:
index.js?fccc903:155 Uncaught (in promise) Error: Provider does not have a request or send method to use.
    at RequestManager.module.exports.RequestManager.send (index.js?fccc903:155)
    at sendRequest (index.js?5b050cb:617)
    at Eth.send [as getAccounts] (index.js?5b050cb:644)
    at CampaignNew._callee$ (new.js?edc8855:17)
    at tryCatch (runtime.js?0e76910:62)
    at Generator.invoke [as _invoke] (runtime.js?0e76910:296)
    at Generator.prototype.<computed> [as next] (runtime.js?0e76910:114)
    at step (asyncToGenerator.js?ae4f0b1:17)
    at asyncToGenerator.js?ae4f0b1:35
    at new Promise (<anonymous>)

I remember the code was working fine, a few moments before, but now I am unsure why the error is occurring and the metamask window is not appearing.
Please give your suggestions.
The new.js file for the code is:
import React, { Component } from 'react'
import { Container, Button, Form, Input } from 'semantic-ui-react'
import Layout from '../../components/Layouts'

import factory from '../../eth/factory'
import web3 from '../../eth/web3'

class CampaignNew extends Component {
    state = {
        minimumContribution: ''
    };

    onSubmit = async (event)=>{
        event.preventDefault();

        const accounts = await web3.eth.getAccounts();
        await factory.methods
        .createCampaign(this.state.minimumContribution)
        .send({
            from: accounts[0]
        });
    }

    render() {
        return (
            <Container>
                <Layout>

Create a new Campaign page

                    <Form onSubmit={this.onSubmit}>
                        <Form.Field>
                            Minimum contribution
                            <Input
                                labelPosition='right'
                                label='wei'
                                placeholder='0'

                                value={this.state.minimumContribution}
                                onChange={event => this.setState({minimumContribution: event.target.value})}
                            />

                        </Form.Field>

                        <Button primary>Create</Button>
                    </Form>
                </Layout>

            </Container>
        );
    }
};

export default CampaignNew;


texts:
As I understand, everyone who invested in The Dao recieves tokens which enable to propose and vote in the DAO. And anyone holding tokens could anytime withdraw the Ether invested if he is not satisfied with the organization anymore.

But how to sell the tokens and withdraw Ether from The DAO? Is this easily possible through Mist or MyEtherWallet?


texts: How can I create a multisignature address on Ethereum?

texts: I want to store my ether in a form that requires more than one digital signature in order to authorise spends.  How do I do on that on Ethereum?


texts:
Looking here in the docs it mentions I need to have the provider attached to estimate gas. But for formatting a transaction offline, I dont have access to the provider. Is there a way to estimate the gas when you dont have access to the provider? I tried sending the transaction without gasPrice and it worked... however, should I provide this price in my formatted offline transaction? Here is how I am formatting my transaction without provider:

const iface = new ethers.utils.Interface(abi);
const func = iface.functions.setValues.encode([name, value]);
const nonce = await NonceManager.requestNonce(wallet);
const txs = {
  gasLimit: 1000001,
  data: func,
  to: address,
  nonce: nonce,
}
const iSign = await wallet.sign(txs);

The iSign is my transaction to send when needed. But is there a way to estimate gase without provider?


texts: Sending multiple transactions in the same block with incremented nonces

texts:
I need to send 0.1 ETH to 10 unique addresses from the same address at the same time. I am manually incrementing each transaction's nonce, and the transactions are sent successfully.

However, each transaction is entered into a new block. For example, transaction A in block 1, B in 2, C in 3, and so on. The problem is that this isn't scalable across n transactions, because I'd have to wait for n blocks to confirm.

Is there a proper way to batch-send ETH so that the collective of transactions confirms as quickly as possible?

Edit: This has only been tested on Kovan. Even with Kovan's 4 second block time, shouldn't transactions sent at the exact same time be included in the same block?


texts:
I am using geth for running my blockchain node.
I wrote my contract in the console itself and it got deployed and mined perfectly.
I could invoke the functions of the contract in the terminal.
I want to know in which directory on my computer would such a file be saved or where to create a .sol file to deploy contracts to my private blockchain ?


texts: Truffle console - How can I get and print the value returned by a contract function?

texts:
This is an absolute newbie question. Given this simple Hello World contract:

pragma solidity ^0.4.4;

contract Greeter {

    function Greeter() {}

    function sayHello() returns(string) {
        return "hello";
    }
}

I deploy it and try to get the value from the sayHello() function:

$ truffle compile
$ truffle deploy
$ Greeter.deployed().then(function(instance){ return instance.sayHello()}).then(function(result){console.log(result);});

I was expecting to see "hello" in the output of the above statement but this is what I actually get:

{ tx: '0xa4333e052b00fdf00d9ad944862b592d091cfb4ff68d610e297cb52cfbf5ebfd',
  receipt:
   { transactionHash: '0xa4333e052b00fdf00d9ad944862b592d091cfb4ff68d610e297cb52cfbf5ebfd',
     transactionIndex: 0,
     blockHash: '0x40aca77673267ca149fe34a62c95b2869285d7819d21279d59fc0714c702314c',
     blockNumber: 64,
     gasUsed: 21867,
     cumulativeGasUsed: 21867,
     contractAddress: null,
     logs: [] },
  logs: [] }
undefined

That is to say, result is an object of this information instead of the "hello" string. Is there a way I can get the actual result of the function?


texts: Is the requirement for signature of more than 2/3 of validators, weighted by deposit, a solution for the data availability problem?

texts: The data availability problem is known to be one of the main problems in blockchain systems. So in case of a proof of stake scheme which requires a block to collect signatures of at least 2/3 of validators, weighted by deposit, does this problem exist anymore?


texts: How to execute a time based transaction? Here's my sample contract

texts:
pragma solidity ^0.4.0;
contract Test {
uint[] timestamp;

function setTime(uint _timeToset) public returns(bool) {
    timestamp.push(now + _timeToset);
   return true;
}

function deleteEntriesBasedOnTime() public returns(bool) {
    for (uint i=0; i<timestamp.length;i++) {
        if (now == timestamp[i]) {
            delete timestamp[i];
            return true;
        }
    }
    return false;
}
}


texts: Use payable modifier for function that creates new contract?

texts: The users are going to use a function that costs gas, but requires no Ether otherwise. Should I use the payable modifier in this case?


texts: How to send ERC20 Tokens to multiple addresses?

texts:
I've been 2 days trying to do it, with no success.
I need to send Tokens to 1300 addresses that participated in the Bounty/Airdrop and I can't send manually one by one, that would take a lot of time and money.

I've deployed that on the testnet using MetaMask and Solidity Compiler:

  contract ERC20 {
      function transfer(address _recipient, uint256 amount) public; }        contract MultiTransfer {
      function multiTransfer(ERC20 token, address[] _addresses, uint256 amount) public {
          for (uint256 i = 0; i < _addresses.length; i++) {
              token.transfer(_addresses[i], amount);
          }
      } }

Later I sent 1000 ERC20 Tokens to it and tried to call the multisend function in MyEtherWallet. Then I put the PrivateKey from my wallet and press "Write", but nothing happens


texts:
Is it possible to hide the name in an ENS auction?

If so, how do I go about doing this?


texts: What happens if I call .at() with an invalid address?

texts:
Imagine that I have obtained the contract ABI, but I'm not sure if I got the right address it was deployed.

If I do:

var contract = web3.eth.contrat(abi);
var deployed = contract.at('<invalid address');

I still get the contract object.

How can I be sure I'm using the "correct" version that was deployed?

Edit

By "correct" I mean a contract that is acknowledged by the network.


texts: Am I Generating Random Numbers In A Non-Mallable Fashion?

texts:
Would this be a non-malleable way to generate numbers for my particular use case?
Let me explain: I allow people to register for a lottery-type event.
If a winning seed belongs to their ticket set, they win selection to participate in a future activity.
 OBS: I'm aware that multiple winning seeds can be associated with the same registrant but this is out of scope for this question.

Here's an example.

    pragma solidity ^0.5.0;

    contract ExampleRNG {

        //@seedTrigger: number which triggers generation of a winning seed.
        uint public seedTrigger;

        //@registrantCounter: counter which resets everytime a winning seed is generated.
        uint public registrantCounter;

        //@winningSeeds: array which stores the generated winning seeds.
        //let's assume that this is a low number to avoid infinite loop discussions.
        uint[] internal winningSeeds;

        //@winningThreshold: number which if reached, restricts further seeding/registration activity.
        uint public winningThreshold;

        //@latestSeed: the latest seed generated from a new registration.
        bytes32 public latestSeed;

        //@stakes: total amount of stakes from registrations.
        uint public stakes;

        //@Tickets: struct to keep track of each registrant's ticket set (interval).
        struct Tickets {
            uint lower;
            uint upper;
        }

        //@ticketsets: storage of each registrant's ticket sets.
        mapping(address => Tickets) public ticketsets;

        constructor(uint _seedTrigger, uint _winningThreshold) public {
            seedTrigger = _seedTrigger;
            winningThreshold = _winningThreshold;
        }

        //@dev register to a lottery-type event.
        //@param stake: think of this as a weighted interest/probability for being selected as a winning seed.
        function register(uint stake) external {
            require(winningSeeds.length <= winningThreshold, "[!] the registration activity has been closed");

            ticketsets[msg.sender].lower = stakes;
            ticketsets[msg.sender].upper = stakes + stake;

            latestSeed = keccak256(abi.encodePacked(latestSeed, stake));

            stakes = stakes + stake;

            registrantCounter++;

            if (registrantCounter == seedTrigger) {
                uint winningSeed = uint(latestSeed) % stakes;
                winningSeeds.push(winningSeed);
                registrantCounter = 0;
            }
        }

        function revealWinningSeeds() external view returns(uint[] memory) {
            return(winningSeeds);
        }
    }


texts:
I have an extension node here:

Key:
000b17906abb9f83c5e190bc3d0bed212e66bf44d99997c53c2071e1413194b6
Value:
[
3866a6d45a815576000da23c1a017179233e9d6437806aef7c2264588739d0,
f84d80890159f20bed00f00000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470,
]

This extension nodes second value can be decoded using RLP into this

Value:
[
"",
0159f20bed00f00000,
56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421,
c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470,
]

What is the shared nibble of this extension node? Where is the prefix? This is all discussed in the yellow paper and I was hoping to have some clarification on where to find these values when actually decoding the byte[].


texts:
I've been trying to run the following piece of code:

myContractToken.methods.balanceOf(App.account).call((err, res) => {
      console.log(res);

However, for some reason App.account does not seem to return the account address I stored in the previous function getAccount().

I tried console logging App.account and they all seem to show my initial stored value 0x0, except for the code I'm trying to get to work. For some other reason, App.account does seem to work for web3.eth.sendTransaction.

Anyone who could explain what exactly is going on would be of great help!

App = {
  web3Provider: null,
  myContractSale: null,
  myContractToken: null,
  account: "0x0",

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    // TODO: refactor conditional
    if (typeof web3 !== 'undefined') {
      // If a web3 instance is already provided by Meta Mask.
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // Specify default instance if no web3 instance provided
      App.web3Provider = new Web3.providers.HttpProvider("http://localhost:7545");
      web3 = new Web3(App.web3Provider);
    }
    return App.initContract();
  },

  initContract: function() {
    myContractSale = new web3.eth.Contract(crowdsaleABI, "0x10a7aec323cf84752bc594ad7c9bc28e002e5fb9");
    myContractToken = new web3.eth.Contract(tokenABI, "0x6b13b17c259710679a315c5a9a3d57ed348d0e54");
    return App.tokenPrice();
  },

  tokenPrice: function() {
    myContractSale.methods.tokenPrice().call((err, res) => {result = web3.utils.fromWei(res, "ether")});
    $("#tokenPrice").click(function() {
      $("#showTokenPrice").html("The token price of a DillyCoin is: " + result + " Ether");
    });
    return App.getAccount();
  },

  getAccount: function(){
    web3.eth.getCoinbase((err, res) => {
      if (err === null) {
        App.account = res;
        $("#account").html("Your account: " + res);
      }
    });
    console.log(App.account); //doesn't work, shows 0x0

    return App.balanceOf();
  },

  balanceOf: function() {
    console.log(App.account); //doesn't work, shows 0x0

    myContractToken.methods.balanceOf(App.account).call((err, res) => {
      console.log(res); //doesn't work, shows 0
    });
    return App.sendEther();
  },

  sendEther: function() {
    console.log(App.account); //doesn't work, shows 0x0

    $("#sendEther").click(function() {
      let amount = $("#amount").val();
      web3.eth.sendTransaction({
        from: App.account,
        to: "0x10a7aec323cf84752bc594ad7c9bc28e002e5fb9",
        value: web3.utils.toWei(amount, "ether")
      })
    });

    console.log(App.account); //doesn't work, shows 0x0
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});


texts:
I was trying to send eth through metamask and it ended up sending my ETH to this address called 'Contract Creation' can anyone please help me with this?

Thanks in advance.

https://etherscan.io/tx/0xab8565481d5edcd162da315bf194b349451b37efbe10e068c601a8cfa84728ca


texts: How do I access data in another contract/node?

texts:
I have two contracts - Data.sol and Buy.sol. Data.sol contains information on products, etc.
I want to use Buy.sol to get and update data in Data.sol, somewhat like having a database. I know this can be done externally on an Oracle if I'm not wrong, but I want the data to be transparent on the blockchain, if that makes sense.
Here's a snippet of what I've tried: Buy.sol has a function to update the buyers in Data.sol as well as to the get the data back. I deployed Data.sol on one wallet A, and Buy.sol on another wallet B. I run the buy function on wallet B and I want to get the buyers when I run the getBuyers function on wallet A. But right now, buy function affects the buyers mapping in wallet B but not A.
I have a feeling I'm doing something wrong or deploying something wrong especially since this is my first solidity contract, so do advise! Thank you!
Data.sol
contract Data {

    // Create Product Object
    struct Product {
        string name;
        uint price;
        uint discount_factor;
    }

    uint numProducts;

    // Create Product Hashmap that maps product ID to Product
    mapping (uint => Product) public ProductsList;

    // Create Hashmap of Product Id to List of wallet addresses belonging to buyers of the product
    mapping (uint => address payable[]) public buyers;

    function getProductPrice(uint prodId) public returns (uint) {
        return ProductsList[prodId].price;
    }

    function updateProduct(uint prodId, address payable b) public {
        buyers[prodId].push(b);

        Product storage product = ProductsList[prodId];
        uint numBuyers = buyers[prodId].length;

        product.price = product.price - numBuyers * product.discount_factor;
    }

}

Buy.sol
import "./Data.sol"
contract Buy {
    Data d = Data(0xddaA.....76a75482d);

    // Buy item by adding buyer address to hashMap with key product Id
    function buy(uint prodId, address payable add) payable public  {
        d.updateProduct(prodId, msg.sender);
    }

    function getBuyers(uint prodId) public view returns (address payable[] memory) {
        return d.getBuyers(prodId);
    }
}

If it helps, I'm using pragma solidity ^0.6.0


texts:
Again i have a new question.
this is the full erorr.
TypeError: Indexed expression has to be a type, mapping or array (is function (address) view returns (uint256)) --> Untitleded.sol:39:17: | 39 | require(balanceOf[msg.sender] >= _value); | ^^^^^^^^^
Im using solidity 0.8.3.
Im making a ETRC 20 token(I copied some code from someone with an older version of solidity and fixed some other bugs)
Iv seen another post with this erorr but i dint understand it and they where using another version that i was not.
pragma solidity 0.8.3;

abstract contract zylus {

    mapping (address => uint256) public _balances;

    mapping (address => mapping (address => uint256)) public _allowances;

    uint256 public _totalSupply = 1000000000000000;

    string public _name = 'Zylus';
    string public _symbol = 'zyl';
    uint8  public _decimals = 6;

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

    function name() public view returns (string memory){
        return _name;
    }

    function symbol() public view returns (string memory){
        return _symbol;
    }

    function decimals() public view returns (uint8){
        return _decimals;
    }

    function totalSupply() public view returns (uint256){
        return _totalSupply;
    }
    function balanceOf(address _owner) public view returns (uint256 balance){
        return _balances[_owner];
    }
    function transfer(address _to, uint256 _value)view public returns (bool success){
        require(balanceOf[msg.sender] >= _value);
        require(balanceOf[_to] + _value >= balanceOf[_to]);
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        emit transfer(msg.sender, _to, _value);
        return true;
    }
    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
    function approve(address _spender, uint256 _value) public returns (bool success);
    function allowance(address _owner, address _spender) public view returns (uint256 remaining);

}

Thanks for the help.


texts: Gas estimation failed when calling the play function

texts:
I am trying to deploy this contract on the test network and am able to do so successfully but when i try to call the play function i get gas estimation error and can do nothing further.
I am using remix connected to Ropsten.
To works fine in javascript vm.
Can anyone tell me whats wrong?
ps: i didnt forget to send ether when i called the play function

pragma solidity ^0.5.8;

contract test1 {

uint256 count =0;
address payable owner;
address[] public players;

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

 }

function play() payable public {
            require (msg.value >= 100000000000000000);
            players[count]=msg.sender;
    count++;
 }
}


texts:
With the newest version of Parity (1.7.2beta), I cannot finish the warp sync process for Ropsten testnet. After getting nearly all the snapshots, getting this error:

2017-09-23 21:17:09  Syncing snapshot 264/272        #0    9/25 peers   8 KiB chain 111 KiB db 0 bytes queue 10 KiB sync  RPC:  1 conn,  1 req/s,  44 µs
2017-09-23 21:17:14  Encountered error during block restoration: RlpIsTooShort

After that, a no-wrap sync is started. Any ideas?

Running command is: parity --geth --chain ropsten --force-ui


texts: How can know which is library's bytecode?

texts:
When I compile solidity file that has more then two contracts, Solc gives me some binaries.
That binaries include bytecode of library.
How can I know which one is library's bytecode if I don't have any information about contracts such as contract's name?

like this image(blue box is just file path)
if i only have those bytecodes, how can I know which is library? (In this picture Ownable is Library)
plus, if I want to deploy this contracts, do I have to deploy all of them?


texts: Byte32 error, even after converting string to hex

texts:
I looked everywhere for people with similar problems, but I couldn't find anything.

I am confused why I keep getting this error (yes, I know others have had this error too, but not for the same reason as I):

>Error: invalid bytes32 value (arg=&quot;_orgName&quot;, coderType=&quot;bytes32&quot;, value=&quot;0x7b22436f6e74656e742d54797065223a226170706c69636174696f6e2f782d7777772d666f726d2d75726c656e636f646564222c224e616d65223a22546573742075736572227d&quot;)

1) The information the node server is passing to the contract is a payload from a webpage.

2) Essentially here is what is happening:

Node takes form payload which is a json object and converts it into hex
Send hex to the contract with the 3 fields orgName,helloId,fctChain.

I know I am passing in the right data, but I keep getting an error return. When i did a typeof convertToHex i got a string.

Any guidance is helpful.

Thank you,

Here's what my code looks like:

function sendToContract(req, res, next) {

  let convertToHex = web3.utils.toHex(JSON.stringify(req.body));

  ACF.methods.registerNewAsset(convertToHex, convertToHex, fctAddress).send()
    .then(results => {
      res.send(results)
    })
    .catch(err => {
      // console.log(err)
    })
  res.send(results);
}

Here's what the contract looks like:

function registerNewAsset(bytes32 _orgName, uint _hellId, bytes32 _fctChain) external onlyOwner {

        NewAsset storage asset = hercIdToAsset[_hercId];

        asset.orgName = _orgName;
        asset.helloId = _helloId;
        asset.fctChain = _fctChain;

        addressToAssetArray[msg.sender].push(asset);

    }

My goal was to implement the send transaction based on this documentation: https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send

I'm using web3js + node + solidity.


texts: truffle migration fails, but initial migration was mined

texts:
I am trying to deploy this contract on a private permissioned Quorum network. The migration fails on the 1_initial_migration process. If I try to repeat the process with:

sudo truffle migrate --network development --reset

I don't get any output on the console at all. When I try to deploy another contract with other network configurations I also get no output to the console.
Without a console output it is hard to find out what is wrong.

Is this normal behaviour of truffle?

Here is the first migration process, which failed. The eth.blockNumber was increased after this, even if it failed.

What does the error stand for: Error: Number can only safely store up to 53 bits
?

Starting migrations...
======================
> Network name:    'development'
> Network id:      1337
> Block gas limit: 3758096384

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

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0xd56cfd9d7bfa56b2s30138bb9a348069e40e92c2b41da87a081f2070560075
   > Blocks: 0            Seconds: 0
   > contract address:    0x17D3233DD54d2491b68c62b534Da313c29456A39
   > account:             0xC58A28d310c76e8298FA456381E6F2da9F046V54
   > balance:             1000000000
   > gas used:            245462
   > gas price:           0 gwei
   > value sent:          0 ETH
   > total cost:          0 ETH

   ⠋ Saving migration to chain.Error: Number can only safely store up to 53 bits

EDIT:
My truffle-config.js looks as follows:

   development: {
        //provider: () => new HDWalletProvider("privateKey", "http://127.0.0.1"),
        host: "127.0.0.1",
        port: 22000,
        network_id: "*",
        from: "0xC58A28d310c76e8298FA456381E6F2da9F046V54",
        gasPrice: 0,
        gas: 4500000
    },


texts: SafeMath in ERC20 tokens: throw vs return false

texts:
On the one hand, protecting from over- and underflow is a must, and a widely used SafeMath library can help with that. SafeMath throws in case of error.

On the other hand, ERC20 token functions are expected to return false on failure, not throw. This presentation advises against throwing in transfer and other ERC20 functions that return bool(success).

What is the proper way of protecting against integer errors in tokens while conforming to the API?


texts:
I have the following function in my contract:

 function AcceptOffer() public payable
    {
        if ( msg.sender != InstanceOwner )
        {
            revert("You are not the owner of this contract and cannot accept the offer");
        }
        if (State != StateType.OfferPlaced) {
            revert("You can only accept valid offers");
        }
        InstanceOwner.transfer(Change)
        InstanceBuyer.transfer(OfferPrice);
        State = StateType.Accepted;
    }

But executing it gives a function payable error. If I remove one of the transfer lines, it works. Are multiple transfers in a single contract not possible? InstanceOwner and InstanceBuyer are two different addresses.

EDIT:

Change is calculated from the diff between AskingPrice and OfferPrice. So if AskingPrice is 5 and OfferPrice is 7 then Change is 2. When I debug the transaction, it shows the variables with their expected values. Therefore I expect the transfer to be successful. The line InstanceOwner.transfer(change) is acting like there's no balance in the variable but there is when I inspect it.


texts: Should I use Infura with Web3j for Event filter?

texts: I'm using Web3j with Infura for smart contract deployment, calling contract method and transactions. Now I want to use Filter contract event from log. Should I use Infura for this? Is Web3j filter works fine with Infura? Or I use a synced geth node to filter events?


texts: How do I move the geth file to my external drive?

texts:
I was in the process of downloading the ethereum blockchain into my computer so i can make it function as a node on the system. I used brew to install geth. After a few hours passed the file ended up taking all the space on my computer with it only partially downloaded. I have an external SSD/ Samsung X5 connected to the computer. How do i move the whole file from my computers ssd to the external ssd. I can't seem to find where the file is saved.
i figured out how to move it but now i'm having trouble making the terminal understand where it is. i have tried the --datadir F:/Ethereum flag but that just creates a new folder with the name of my external drive plus a /


texts: What would cause me not to be able to send my newly created token?

texts:
I've created a new token on the Ropsten test network and I can see the token under my account in MetaMask. When I click on send in MetaMask, from the account that created it with, I can only send ether but not my token?

What could cause this?


texts:
I just set up a Block Explorer to interact with my private blockchain.

The private Blockchain runs in a VM. The host system connects to the Block explorer (also on VM).

When I have meta mask installed in my Browser the request fails. See image.

When I uninstall Meta Mask the application can get the Blocks from the Blockchain.

VM - Ubuntu 18.04

HOST - Windows 10

This is a very strange behaviour. What exactly is causing this problem? Especially because I dont even interact with meta mask.

EDIT 1: Although it makes no sense I deactived Privacy Mode on Metamask. However it is still NOT working.

EDIT 2: Same behaviour on firefox.

EDIT 3: Steps to reproduce:

Set up a private blockchain.
Configure the explorer on the chains RPC-Port.
Start Blockchain & Explorer.
Now it works.
Install MetaMask.
Now it doesn't work.

EDIT 4: Code line that are most likely to cause the problem with metamask

In app.js:

var web3 = new Web3();
var eth_node_url = 'http://xxx.xxx.xxx.xxx:22000';
web3.setProvider(new web3.providers.HttpProvider(eth_node_url));

However the programm keeps running and crashes at:

var blockNum = $scope.blockNum = parseInt(web3.eth.blockNumber, 10);

Does MetaMask override the web3 instance I created?


texts: Do we need to sign transaction for totalSupply also?

texts: I am using web3 and want to sign transactions made with ERC20 contract.


texts: Truffle Test AssertionError: error message must contain revert

texts:
I can't figure out why this error occurs
Here my test js code:
var YarockToken = artifacts.require("./YarockToken.sol");

contract('YarockToken', function(accounts) {
  var tokenInstance;

  it('initializes the contract with the correct values', function() {
    return YarockToken.deployed().then(function(instance) {
      tokenInstance = instance;
      return tokenInstance.name();
    }).then(function(name) {
      assert.equal(name, 'Yarock Token', 'has the correct name');
      return tokenInstance.symbol();
    }).then(function(symbol) {
      assert.equal(symbol, 'YAROCK', 'has the correct symbol');
      return tokenInstance.standard();
    }).then(function(standard) {
      assert.equal(standard, 'Yarock Token v1.0', 'has the correct standard');
    });
  })

  it('allocates the initial supply upon deployment', function() {
    return YarockToken.deployed().then(function(instance) {
      tokenInstance = instance;
      return tokenInstance.totalSupply();
    }).then(function(totalSupply) {
      assert.equal(totalSupply.toNumber(), 1000000, 'sets the total supply to 1,000,000');
      return tokenInstance.balanceOf(accounts[0]);
    }).then(function(adminBalance) {
      assert.equal(adminBalance.toNumber(), 1000000, 'it allocates the initial supply to the admin account');
    });
  });

  it('transfers token ownership', function() {
    return YarockToken.deployed().then(function(instance) {
      tokenInstance = instance;
      // Test `require` statement first by transferring something larger than the sender's balance
      return tokenInstance.transfer.call(accounts[1], 99999999999999999999999);
    }).then(assert.fail).catch(function(error) {
      assert(error.message.indexOf('revert') >= 0, 'error message must contain revert');

 })
    })
});

and here my contract code:
pragma solidity ^0.5.16;
contract YarockToken {
    string  public name = "Yarock Token";
    string  public symbol = "YAROCK";
    string  public standard = "Yarock Token v1.0";
    uint256 public totalSupply;

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

    event Approval(
        address indexed _owner,
        address indexed _spender,
        uint256 _value
    );

    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    constructor(uint256 _initialSupply) public {
        balanceOf[msg.sender] = _initialSupply;
        totalSupply = _initialSupply;
    }

 function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balanceOf[msg.sender] >= _value);

        balanceOf[msg.sender] -= _value;

    }

}

and this is the error I am getting
      Contract: YarockToken
    ✓ initializes the contract with the correct values (238ms)
    ✓ allocates the initial supply upon deployment (123ms)
    1) transfers token ownership
    > No events were emitted

  2 passing (541ms)
  1 failing

  1) Contract: YarockToken
       transfers token ownership:
     AssertionError: error message must contain revert
      at /Users/Kantemirovs/token_sale/test/YarockToken.js:39:7
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

Can someone please enlighten me about this ??


texts:
I've started mining on Ubuntu 16.04 using AMD-GPU PRO driver and this miner:

https://github.com/ethereum/cpp-ethereum/

Video card is a RX480 with 8GB stock.

I'm getting a lot of bad shares, like 10% to 20% are bad shares, on Minergate pool.

A quick search on internet says that this is caused by a corrupted DAG file, and says it is under $(HOME)/.ethash/ and removing it will solve the problem.

But this folder does not exist. I've checked both on root and my user, there's no such folder. I've even tried using a find to check if this folder is anywhere in the system, but it does not exist at all.

Does this miner stores DAG file on other folder?

Thanks in advance.


texts: Web3 and Metamask : how to get signed data?

texts:
I'm trying to sign data with web3 + metamask and get that signed data to my server.
I ask to sign data, metamask prompt pop, I accept but then nothing happens?
Html :
<button class="button is-warning is-rounded" onclick="signData('Hello World')">SignIt</button>

Js :
    async function signData(index) {
        const account = await getCurrentAccount();
        let dataSign = await web3.eth.sign(index, account).then(console.log);
    }

How to retrieve signed hash so I can work with it ?


texts:
i still waiting from 4h for my transaction. I know de gwei is low but what you think it will be processed.
0xb69c181d38bcd157d07a623b5c1b620e6694644626bc1ed48e984ed089933e86


texts:
I've been able to create a private networking using the command line Geth tools, so I have been trying to recreate it using the Android light client Geth.

On the command line Geth, I made sure the two nodes had the same Genesis file and network ID number. Then I used the enode string of one node to connect the second one to it.

I downloaded the .aar package from the geth.ethereum.org site. I've tried multiple versions, such as 1.5.0,1.5.9, and1.6.0`. I imported it into an Android Studio project. There is little to no documentation on the classes, so I had to guess based off other people's questions and looking at the Go source code on the Ethereum Github. I believe I am able to successfully create a Node, and initialize it with the proper networking settings, and supply it with another node's enode string. However, when I check the Android app node's list of peers, it is always empty.

How can I connect the Android light client node to another node? (could be another light client or a command line client on a computer)

Thank you!


texts: Does function order also matter when writing upgradeable smart contracts?

texts: The ZeppelinOS docs clearly explain the importance of state variable order when upgrading smart contracts, but say little on whether the same rules apply to functions.


texts: Why would a contract throw after it has executed the last line of code?

texts:
I'm debugging a contract function with Truffle.  It always throws the following error:

Error: VM Exception while processing transaction: revert

However, I'm certain that the function has reached the last line, since on the last line I'm emitting an event and Truffle reports that the event has been emitted.

How is it possible that the function reaches the last line which is evident by the fact that the event was successfully emitted, and yet I'm still getting the error above?


texts: Racing condition when replacing transactions

texts:
I'm writing a bot that monitors a DeFi protocol for liquidation opportunities. The bot behaves like in the pseudo-code below:
let pending_txs: [];

for every_new_block in Ethereum {
  // Check the state of pending txs.
  for pending_tx in pending_txs {
    let receipt = get_receipt(pending_tx);

    if receipt != null {
      // If we got a receipt from Ethereum, clear the tx from the local state.
      delete_tx_from_array(pending_tx);
    } else {
      // Otherwise, replace the tx and update it in the array.
      let new_gas_price = bump_gas_price(pending_tx.gas_price);
      let tx = send_tx(new_gas_price);
      update_tx_in_array(tx);
    }
  }

  ...

  // Search for new liquidation opportunities.
  if liquidation_opportunity and if !pending_tx_for_liquidation_opportunity {
    let tx = send_tx(initial_gas_price);
    add_tx_in_array(tx);
  }
}

The above works well most of the times, but there it an exception:

Submit tx 0x123
Wait 15 seconds, check if we got a receipt from Ethereum.
If we didn't, re-calculate the gas price and send a replacement tx 0xabc.
By the time the replacement tx 0xabc is broadcast to the Ethereum network, the 0x123 gets mined.
The bot will attempt to replace the 0xabc tx forever, because the receipt is always null for 0xabc.

When I update the tx in the array, I also override the previous tx hash (this makes the implementation simple). In other words, the script ceases to be aware of past tx hashes once it broadcasts a replacement tx, which causes an infinite regress when a racing condition occurs.
The question is whether there is any way to avoid this situation? I've only run my bot on Rinkeby, against an Infura node. Maybe it's something that happens frequently on testnets, but rarely on mainnet?
I know that one solution is to modify the code to track multiple tx hashes per liquidation opportunity, but that would greatly increase the complexity of the implementation (I'm using Rust).


texts:
Is it possible to view what tokens and the amount of tokens somebody is holding?
If you know his or her Ethereum address? thanks in advance.


texts:
I was reading about past attacks on Ethereum network and I pictured the following hypothetical scenario: there is a tool or automated, machine learning based anomalous monitor to check out constantly account's behavior, considering some factors such as account's level of activity, gas spent/received and so on.

Given this scenario, I would like to post the following question: who would benefit at most of being aware of what could be considered anomalous activity accounts? Who would be interested to know about any report generated by this hypothetic monitor?


texts: How to get data from earlier blocks in ethereum BC via web3.py?

texts:
I am trying to get data from earlier blocks/transactions.
I have created events and emitted them.
I can see the logs in the Remix IDE.
However, I cannot get the logs in web3.py. It only returns empty.
Is there any function that can return all of the logs generated by an event?
Here is my Smart Contract
pragma solidity 0.8.0;

contract UserRep {
    mapping(uint256 => User) users;
    uint256[] userIDList;

    struct User {
        uint256 id;
        //other attributes
       // string[] data;
        bool isMalicious;
        uint256 rep_value;

    }

    event reputationOfUser(uint256 userId, uint256 repVal );

    // Create a new user.
    function newUser(uint256 _id) public {
        // In a mapping, all elements are defined. They're just empty by default
        // So, just setting the id will create a new user;
        users[_id].id = _id;
        users[_id].rep_value = 50;

        userIDList.push(users[_id].id);
    }

    // Add reputation value of a user
    function increaseReputation(uint256 _id, uint256 _addRep) public {
        users[_id].rep_value = users[_id].rep_value + _addRep;

        emit reputationOfUser(users[_id].id, users[_id].rep_value);
    }

    // Decrease the reputation value of a vehicle
    function decreaseReputation (uint256 _id, uint256 _decRep) public{
        if (users[_id].rep_value < 10){
            users[_id].isMalicious = true;
        }
        users[_id].rep_value = users[_id].rep_value - _decRep;
       // emit reputationOfUser(users[_id], users[_id].rep_value);
    }

    function getUserReputation(uint256 _id) public view returns (uint256){
        return users[_id].rep_value;
    }

    function isUserMal(uint256 _id) public view returns (bool){
        if (users[_id].rep_value < 10){
            return true;
        }
        else{
            return false;
        }
    }

    function getAllUserIDs() public view returns  (uint256[] memory){
        return userIDList;
    }

    function noOfUsers() public view returns  (uint256){
        return userIDList.length;
    }

}


texts: ParserError: Expected primary expression - address payable - payable()

texts:
I'm trying to get myself familiarized with ethereum. So I was going through a repo, and tried to rum the code :

function transferFundOnResolve(uint cid) private {
        // Could also be used: complainMap[cid]._status == Status.Resolved &&
        if(complainMap[cid]._reward > 0) {
            if(policeAccounts[complainSolver[cid]] != true) {
                complainSolver[cid].transfer( complainMap[cid]._reward );
                complainMap[cid]._reward = 0;
            }
            else {
                for(uint i=0; i<complainMap[cid]._contributors.length; i++) {
                    complainMap[cid]._contributors[i].transfer( complainMap[cid]._contAmount[i] );
                }
                complainMap[cid]._reward = 0;

            }
        }
    }

As it says TypeError: "send" and "transfer" are only available for objects of type "address payable", not "address".

So I modified and added payable() like :

function transferFundOnResolve(uint cid) private {
        // Could also be used: complainMap[cid]._status == Status.Resolved &&
        if(complainMap[cid]._reward > 0) {
            if(policeAccounts[complainSolver[cid]] != true) {
                complainSolver[cid].transfer( payable(complainMap[cid]._reward) );
                complainMap[cid]._reward = 0;
            }
            else {
                for(uint i=0; i<complainMap[cid]._contributors.length; i++) {
                    complainMap[cid]._contributors[i].transfer( payable(complainMap[cid]._contAmount[i]) );
                }
                complainMap[cid]._reward = 0;

            }
        }
    }

Now it says : ParserError: Expected primary expression.

How should I resolve this ?

I have pragma solidity ^0.5.16;


texts: How to replicate pushing and deleting from an array of structs from Solidity in Vyper?

texts:
I'm trying to re-create a Solidity contract in Vyper for a demonstration and am trying to figure out the best way to replicate adding/removing from an array of structs... As far as I can tell I'd have to use a hashmap of [uint256, mystruct] and then keep track of the index with a separate variable... is that the correct way to do this?  What about for removing or zeroing a struct from the hashmap?
Solidity Code:
struct MyStruct {
    string name;
    uint age;
}
MyStruct[] public myStructs;

uint256 structCount;

// add
myStructs.push("Alice", 22);
structCount += 1;

// remove
delete myStructs[0];
structCount -= 1;

Work-in-progress Vyper Code:
struct MyStruct:
    name: String[64]
    age: uint256

myStructs: public(HashMap[uint256, MyStruct])

structIndex: uint256
structCount: uint256

# add
self.myStructs[self.structIndex] = MyStruct({name: "Alice", age: 22})
self.structIndex += 1
self.structCount += 1

# remove
thisStruct: MyStruct = self.myStructs[0]

# is this the only way to do this?
thisStruct.name = ""
thisStruct.age = 0

self.structCount -= 1


texts: Finding values within an Array/Mapping based off min and max values

texts:
I want a user to be able to place a bet on some number, between a range of numbers.
So the user wants to place a bet on the numbers 50-500. Then there is a function that sees if the number has been bet on - such as hasBet(uint256 number_to_check)
Lets say the user places a bet for the range of 50-500. Then someone wants to check that number 79 has a bet.
How would you store this data such that you can check (without a loop since the ranges could be from 0 to 2^255)?
Here is what I have:
Lets say 3 users have placed bets from 0-50, 51-320, 321-500.
So the value 79 would be bet on in the second bet - ranging from 51-320.
What type of structures/arrays/mappings would be useful to store the index of bets, and the values, such that you can find that 79 was stored. The key is to not use a loop, as the numbers could range into the millions or above.
Also, we know the min and max, so we know each batch is under 500 numbers and over 50. Also each bet would need to be consecutive, so if someone bet 0-50, next bet needs to be greater than 50.
So I feel this is helpful in finding the info. You can assume if the number was 7900, you know it couldn't be within the first X amount of bets, as its greater than 500.
The main operation after finding the struct containing the bet is a simple - "is 79 within the start and end values".
But the main question is how do you find that structure containing that bet, without having to do a loop?
edit:
One way I think would work, but not sure how to implement is storing the range of values in a mapping or array.
Such that an index would return the set value, ie:  batchBets[1] returns [0, 50] and then the index would be stored in a separate mapping based off the max value or something similar?
Not really too sure.


texts: ERC20 Token support for metamask website payment

texts:
I have the following code working in my site to accept ethereum payments in my website via metamask....

<!DOCTYPE html>

    <button class="pay-button">Pay</button>

Now I would like to know what do I have to modify in order to accept any erc20 token payment via metamask in my site

Thanks for the help...


texts: How can I extract only the transaction input data value of geth in web3.js?

texts:
var tto_count = document.getElementById("to_count");
   //var transaction = web3.eth.getTransactionFromBlock(1865, 0).input;
   //var transaction = web3.eth.getTransactionFromBlock(1865, 0).then(console.log);
   var transaction = web3.eth.getTransactionFromBlock(1865, 0);
   //tto_count.value = web3.eth.toString(transaction);
   tto_count.value = JSON.stringify(transaction);

This is the source code I've failed so far.


texts: How to update react component state with Drizzle

texts: I'm using react and drizzle and want to update the classes state based on data returned from a call to a contract. I'm using the standard pattern from the drizzle box and here (https://itnext.io/how-to-use-drizzle-truffle-and-react-to-make-the-best-front-end-for-your-ethereum-dapp-ee09c8e94eae) and all of these only get the result of the contract call inside render(), but I'm wanting to use it to update the state, the view may need to change based on transactions sent by others. Updating the state inside render seems wrong even if it's only done when it changes, how can I get a different callback using drizzle which gets the results of the call outside of render?


texts: I have a certain amount of ERC20 Tokens. How can I Create a crowdsale contract that allows me to send them to it to be sold?

texts:
I have created previous contracts where the token is created by the crowdsale and then the constructor allocates an amount of those to be transferred to other addresses and the remainder are for sale.

But how do I implement logic that allows me to set an already created token as the token to be used in the crowdsale and then send those tokens to the contract and have them for sale?

Thanks for any help.


texts:
Let's suppose I have a simple delegatecall based relay contract. It looks up the contract implementation from a registry and passes the call to the upgradeable implementation:

contract Relay {

    address public registrarAddr;
    string public name;

    function Relay(address _registrarAddr, string _name) {
        registrarAddr = _registrarAddr;
        name = _name;
    }

    function getImplAddr() constant returns (address) {
        Registrar registrar = Registrar(registrarAddr);
        return registrar.addr(name);
    }

    function() {
        address currentVersion = this.getImplAddr();
        if(!currentVersion.delegatecall(msg.data)) throw;
    }
}

As you see the current function() {} has a special check for delegatecall return values, as this is based on an example code.

The question is, how delegatecall handle return values? Can I modify this delegatecall hook to perform normal web3 contract.call().balanceOf(addr) style functions for reading public values from the implementation contract? Or if I set up a relay contract do I need to have special logic in place to read the data from the contract what I would normally do with call()? Are there any examples of such arrangements?


texts: Metamask Failed transaction when sending out BAT tokens

texts:
I've been trying to send some BAT tokens out of my metamask wallet for quite awhile and it keeps eating up all my eth gas fees. I even increased the gwei fee to 100 and paid .50 USD as the fee. And it still failed.

What am I doing wrong? It would be nice, if it gave the correct amount of gas I need in order to send it instead of guess. This is kinda ridiculous that I lose out on my fees.

Also do different tokens charge different gas fees? I see that BNB gas fees are $1-$10 when I try to send it.


texts: Is there any way to get a notification(PN, Email etc.) when one receives ETH or tokens issued on ethereum?


texts:
I'm having trouble getting into my Mist wallet as of a few days ago.

Error starting protocol stack: missing block number for head header hash.Having trouble with Ethereum's mist wallet. I have the latest: Version 0.9.3.

Thoughts? Thank you everyone.


texts: I have a modifier for a few functions that check if a mapping exists, for one function I need the modifier to verify the mapping doesn't exists, is there any way to !modifier as you would a function you wanted a negative response for?


texts: which address do i send my eos tokens to on metamask? contract address or ethereum address?

texts: I recently created an ethereum account using metamask and registered a public/private eos key pair on it. I bought some eos on an exchange and i am not sure which address to send my eos to. Do i send it to the contract address or ethereum address of my account?


texts: Is it possible to create this with Ethereum?

texts:
I am building a mobile application and I want to create a cryptocurrency around it. My problem is that I am new to crypto and to be honest I am not even sure if it’s possible what I want to do.

To simplify things, let’s say that my app it’s just a button. When the user tap it, it will generate a word. I want to reward the user for pushing that button by giving them a portion of a coin. Also the reward will be valid only if the generated word hasn't come up in previous attempts.

Is this doable using the ethereum network? If yes, can you point me to the right direction where to begin with? If no, are there any  other crypto networks that can help me?


texts: Out of Gas, Bad Jump, Other errors trying to send

texts:
I have always used the metamask default settings, however it is not working when I am simply trying to send ether from my etherdelta smart contract back to my ether wallet, so I checked www.ethgasstation.info and manually set above the safe range. but nothing I do seems to work, my transaction either sits for 24 hours and gets cancelled, or my gas is used up within minutes and it says error out of gas.

Currently while waiting for over 2 hours for transaction approval I saw the warning "error there was an error upon resubmitting" so I clicked the link to increase my gas, only to immediately receive the same message "warning there was an error upon resubmitting" and my transaction again has been awaiting approval for over another hour.


texts: Smart Contracts - Where is contract in it?

texts:
I am new to Smart Contracts. When I saw some example of Smart Contracts, I realize that they are just some piece of code, not exactly contracts.

For example function sendCoin(address receiver, uint amount) is a method defined in smart contract which takes receiver address and amount to send Coins to receiver.

But the contract is not about how to send coins, but how much to send. For Example, if the material is delivered on time, make full payment else charge penalty of 10% for every week's delay.

As per my understanding, the invocation - where these if-then rules are written (Representing contract) - is outside smart contract.

Is my understanding correct? Is the term 'Smart Contract' misleading?

Are real contracts are still coded outside the block-chain in application triggering these functions? If yes, then why smart contracts can't be manipulated, the applications can still compromise the contract - For Example. by not paying as per contract terms.


texts: Is chain link a stand alone blockchain or is it a series of smart contracts on the ethereum blockchain?


texts: Truffle compiles and migrates the wrong contract

texts:
I have an initial folder with an extension of the tutorial, and I'm now working in a new folder:

new-project
 |
 +- build
 +- contracts
 |         +- NewContract.sol
 |
 +- migrations
 +- ...

truffle-test
 |
 +-pet-shop-tutorial
 +-old-project
 |         +- build
 |         +- contracts
 |                   +- oldContract.sol

I made the new_project as a copy of old-project, but now when I'm in the new-project folder and I run truffle compile or truffle migrate what I see is:

Compiling .\..\truffle-test\old-project\contracts\OldContract.sol...
Writing artifacts to .\build\contracts
[...]

And truffle actually writes the artifacts of the old contract in the new folder!

I'm left with this:

new-project
 |
 +- build
 |         +- OldContract.JSON
 |         +- NewContract.JSON
 +- contracts
 |         +- NewContract.sol

And the new contract doesn't seem to be deployed. I edited 1_initial_migration.js to mention the new contract, and it's still not deployed.

What should I do? Did I forget something? How do I prevent truffle from compiling from other folders?


texts: Help to find this vanished ETH in failed transfer?

texts:
at a total loss as to how to track down where this ETH went.

I was sending from a wallet to another address.
The wallet itself shows 'completed' and viewing the transaction makes it look like the ETH has arrived at the new location.

The receiving address never got it, never showed pending, and looking at the ID on etherscan shows a fail.

However, it never returned to my original wallet (none of it, not the original amount minus the gas, none at all). I am sure the # of ETH did not change back to what it was. The transactions section of the wallet shows that ETH going out and that's all.

So I can't access it through my original wallet and it's not on the new location. It must be 'somewhere', right?

Luckily we are not talking a huge amount of money but still on principle this bothers me and want to know how this works if possible.

Here is the transaction id: https://etherscan.io/tx/0x15b08e781e4b33313e00ae33155189e9c090458d14dce5b9cfdc87349405fec3

Thank you for any advice.


texts:
Spending months of studying and testing my code. It is now time to deploy to the mainnet. But unfortunately my Ethereum node takes ages to sync :(

May I know if there is any alternative way for me to upload my contract? I need to get it uploaded by tonight.


texts: Get address of internal transaction using Ganache

texts:
I am deploying a Crowdsale contract locally, using truffle and ganache.

The problem is, that the MintableToken is created during the deployment of the Crowdsale contract, using the createTokenContract() function.

Having just the 4 transactions in Ganache (see image below), it's not clear to me which address the Token Address is - I assume none of them, because it is an internal transaction?!

However, when I use the test network (Ropsten) I can inspect the internal transactions using etherscan, and find the MintableToken address.

How can I do this locally with ganache? If that's not possible with Ganache, is there another way to circumvent this locally/ inspect the internal transactions/ print them? Any other solution besides of decoupling createTokenContract from the Contact creation?


texts: How can I change the 12 word phrase in my trust wallet?

texts: I created a ETH trust wallet on my phone for someone and he has now imported the trust wallet to his phone.  Is there any way to change the 12 word phrase or somehow give the sole control to the wallet to him?  He is concerned about security as the wallet still shows on my phone and I have the 12 word phrase.


texts: What are existing alternatives to metamask with that works online inside existing browsers, that don't require installing a browser extension? What are some of the tradeoffs between them?


texts: Why does fallback cause exception when expecting return value?

texts:
I want to understand, what happens under the hoods in this (very unsafe, but educative) example.

contract Actual {
      function () external { }
}

interface Expected {
     function g() external returns (uint256);
}

contract MyContract {
    function g(address a) public returns (uint256 x) {
          // fails at run-time
          x = Expected(a).g();
    }
 }

Let us suppose I have create an instance of MyContract i_MC and an Instance of Actual i_A. Now I call function i_MC.g() with i_A's address as input. The call results in a revert.

The high-level explanation is very simple: i_MC expect to call the g() function of an instance of type Expected, but it actually invoked the fallback function of i_A, which does not return anything.

Is that the case, because the caller is looking for an unallocated portion of memory (after the \mu_i in the yellow paper), because the fallback function did not execute the RETURN opcode, which also expands the memory?


texts:
All Ethereum blocks contain a stateRoot field - That is, the root hash of the world state trie. I have two questions about that.

From what I've understood through all the reading I've done on Casper CBC, there will be state changes occuring in parallel (that of each shard) so no one shard will have a correct global state (with regards to other shards) and be able to have a merkle proof of that state self-contained within the shard.

By this I mean, if I perform a state change in shard A, from block x - 1 to block x, and at the same time a state change occurs in shard b from block x - 1 to block x, the global state hashes of both shards would not match.

As such, does that mean cross-shard transactions are going to have to fit under the current tps rate? Considering they'd have to occur under a block that affects all shards, which would require every shard to temporarily join the main chain and then split back off?


texts:
I followed a guide and got ethminer on 1 single 2070 super
I'm not mining anything watsoever, I believe.
https://ibb.co/MCVKcZ9


texts:
I have main address: const fromAddress

There is also an array of addresses and their keys:foreth/keys

I need to send all erc20 tokens from: foreth array to the: fromAddress

Tokens are sent only from the first address of the foreth array, a hash is generated for all subsequent addresses, which is not on etherscan with error: Sorry, We are unable to locate this TxnHash

It is necessary to make sure that tokens are sent from all addresses that are in the array foreth

let tokenAddress = "erc20_contract_addr";
let fromAddress = 'main_addr'
let privateKey = Buffer.from('key_main_addr', 'hex')

const contractInstance = new web3.eth.Contract(minABI, tokenAddress)
let foreth = ["addr1", "addr2", "addr3", "addr4"];
let keys = ['addr1_key', 'addr2_key', 'addr3_key', 'addr4_key']

function nonce_addr(address) {
    return web3.eth.getTransactionCount(address)
}

foreth.forEach(async function(recipient, i) {

    const balance = await contractInstance.methods.balanceOf(recipient).call(function(err, result) {
        let contract = new web3.eth.Contract(minABI, tokenAddress, {
            from: recipient
        })

        if (result < 0) return
        web3.eth.getTransactionCount(fromAddress)
            .then((count) => {
                let rawTransaction = {
                    'from': fromAddress,
                    'gasPrice': web3.utils.toHex(20 * 1e9),
                    'gasLimit': web3.utils.toHex(21000),
                    'to': recipient,
                    'value': web3.utils.toHex(web3.utils.toWei("0.0008")),
                    'nonce': web3.utils.toHex(count + i)
                }
                let transaction = new Tx(rawTransaction)
                transaction.sign(privateKey)
                return new Promise((resolve, reject) => {
                    web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
                        .on('transactionHash', console.log)
                        .on('receipt', resolve)
                        .on('error', reject)
                })
            }).then(receipt => {
                console.log("eth was send")

                keys.forEach(async function(keys) {
                    let nonce = await web3.eth.getTransactionCount(recipient, 'pending');

                    let rawTransaction = {
                        'from': recipient,
                        'gasPrice': web3.utils.toHex(20 * 1e9),
                        'gasLimit': web3.utils.toHex(100000),
                        'to': tokenAddress,
                        'value': 0x0,
                        'data': contract.methods.transfer(fromAddress, web3.utils.toHex(result)).encodeABI(),
                        'nonce': web3.utils.toHex(nonce)
                    }
                    nonce++
                    let transaction = new Tx(rawTransaction)
                    transaction.sign(Buffer.from(keys, 'hex'))
                    let serializedTx = '0x' + transaction.serialize().toString('hex')
                    return new Promise(resolve => {
                        web3.eth.sendSignedTransaction(serializedTx)
                            .on('transactionHash', console.log)

                    })
                })

            })
    })

})


texts: Newbie question. On every contract I made, I have ability to create token, which will become 'the money' exchange in my smart contract. What I don't understand is, how to specify exchange rate of my token to Ether? When people want to buy my token, how to specify the amount of ether or money?


texts:
I really like whats going on in the space, and have an idea of my own for a blockchain. I am aware there are ERC20 tokens - which should help me build on top of Ethereum. The concept i have in mind has a different way of dealing with transaction fee on the network rather than gas and involves microtransactions, making it impossible for me to run it on Ethereum (Which was my first choice). I am following developments on Lightning Network and Plasma for micropayments, but then Plasama isn't deployed yet.

I do not have experience building blockchains in the past, but i have been following the research going on in this space.

I really want to know what is a good place to start thinking about a new blockchain - As a ethereum fork , ERC20 or otherwise.

I have written a first draft of a whitepaper that explains my idea, and will be ready to show others very soon. What's the best way to get feedback on the paper? What are the things i need to keep in mind before getting such feedback?

Any help on these lines, deeply appreciated! :)


texts: RPC provides http-rpc server.But what is the use of  IPC and ws?


texts: Get Contracts Deployed Count on Quorum Blockchain?

texts:
I have lost count of the number of smart contracts deployed on my quorum blockchain.

What are some negative impact/implications of forsaken smart contracts on a private blockchain such as Quorum? Other than taking up disk space on the individual nodes, are there any other negative impact?

Also, is there some way to get the number of Contracts Deployed Count on Quorum Blockchain?


texts: Sign data with private key inside a truffle test file

texts:
I've got a contract method that checks the signer of a message using the solidity ecrecover function. In my truffle test file I now want to check if this is done correctly. Therefore I need to sign a message within the testfile using a private key.

Using this

let signedMessage = await web3.personal.sign("data", accounts[0])

does not work with error "Method personal_sign not supported."

Any idea how to do this? Thanks for you help!


texts: How does EtherScan know I am sending to a Shapeshift/Poloniex wallet?

texts:
I have noticed many transactions on Etherscan that indicate one of the parties is a certain type of wallet (e.g. Poloniex or Shapeshift). Here is an example.

How does it identify the source? Do these exchanges publicly register their addresses (e.g. on IPFS or with an API)?

Edit: Clarification of my question with an example: Let's say Shapeshift does 10,000 transactions today. That would result in 10,000 addresses being generated. I would hope there is no way to control the format of these addresses (since they are SHA3 hashes), so we are left with 10,000 random address strings. How do these 10,000 individual addresses get registered with Etherscan? I have a hard time believing it is a manual process (this would constitute a full time job for multiple people) and I would guess there's some kind of public lookup table or that they are calling an Etherscan API, but I've never seen any documentation either way.


texts: How to get timestamp of an event log in emitted event from smart contract

texts:
I want to get the timestamp of an event.

How can I get time of event fired, if the event data does not contain any time value?


texts: How to generate solidity encode function signature from Javascript?

texts:
What I am trying to achieve is like , i should be able to call a set of solidity functions dynamically based on some criteria. i'm using call() method to achieve the same.
(bool success, bytes memory result) =APContract.call(abi.encodeWithSignature(string(data), "hello"));

data variable contain the function call string "testCall(string)".  instead of encoding from the contract I should be able to encode the same with javascript (because of some argument generation logic). so that i can call the function like APContract.call(data). Is there any method that help to achieve the same?


texts: Can I change my rewards into BTC/BUSD, The concept of the token is just hold the token and it will calculate the BNB rewards you can get daily

texts:
function calculateBNBReward(
uint256 _tTotal,
uint256 currentBalance,
uint256 currentBNBPool,
uint256 totalSupply,
address ofAddress
) public view returns (uint256) {
uint256 bnbPool = currentBNBPool;
    // calculate reward to send

    uint256 multiplier = 100;

    // now calculate reward
    uint256 reward = bnbPool.mul(multiplier).mul(currentBalance).div(100).div(totalSupply);

    return reward;
}

The full source is https://github.com/laronlineworld/RewardToken/blob/main/RewardToken.sol
"Can I change the rewards system by BNB into BTC or BUSD? The token tokenomics is Simply hold tokens in your wallet and you will get more token like RFI model. In addition to this, you will also earn daily rewards in $BNB." My question is how can I change the rewards BNB into BTC or other cryptocurrency?


texts: I am writing a smart contract as a fund for me and some friends to invest ETH in, allowing for investment proposals to be submitted and voted on. For example, 10 people each put in between 1 and 10 ether, and I propose to invest 5 ETH into Bitcoin from our fund. My solution to execute this trade if a proposal is approved is to transfer the proposed investment amount to one trusted member who will then invest it into the given destination. However, as you may understand, it would be nice if the smart contract could buy the Bitcoin itself without the need for a trusted member. Is there a way for my contract to exchange ETH for other cryptos?


texts: Would a minimal gas price tx ever be mined?

texts:
I want to mine and charge a minimal gas price (like the minimum required to prevent infinite loops and such), to enable many smaller transactions to be confirmed super cheaply and to lower the cost of EVM computation for a project I'm working on.

Is it possible to specify which miner I want to mine my transaction so my project can send transactions to a super-low-cost miner?

Is it correct to say that if I submit a transaction with a very low gas price and a miner has a very low gas price set, the transaction will eventually be routed to the low cost miner?

It would be nice to bypass the more expensive miners and just go straight to the low cost miner.  But now that I'm thinking this through, low-cost txs will never be mined if a small % of the hash-rate has a low gas price set.


texts:
I'm looking at liquidity pools (LPs), and the economics don't make sense given the APYs. How is this possible, or are exchanges simply taking a loss to establish market dominance? Please tell me if/what I'm missing.
The APYs are derived from the user swap fees from swapping tokens on a given platform, powered by an Automated Market Maker (AMM). Exchanges may also earn revenue on the price spread difference, the price difference confirmed by the user and the price at the time of execution.
Using 1inch.exchange as an example,

Sample user swap fees: 0.36%

Recent monthly trade volume: $6B

Monthly exchange revenue: $43.2M
a. Monthly swap fee revenue: $21.6M
b. Price spread revenue: $21.6M (Let's assume it's equal to the swap fee revenue to be generous)

Considering the total users' LP principal staked is $1K, given a pool like LDO-stETH (64.13% APY/5.34% monthly yield), the total user revenue is $53.44.

However, let's say the total user's LP principal staked is $1.5B. The users' revenue, $80M, is 2x the exchange's revenue, $43.2M for the month.

See the sample calculations.


texts:
I am trying to reward a user for typing a review:
function addReview(..., address payable _to) external payable {
    ... // code for adding a review including check for reentrency attacks
    payable(msg.sender).transfer(msg.value + 1);
}

This throws an "internal contract error". Using Ganache, MetaMask, Solidity 0.8.0.
What am I doing wrong?
Also, I want to transfer the funds from the smart contract's address.
Tried: using the Feeless library, using refundGasCost modifier (most of it was deprecated and failed when trying to fix).
EDIT:
This is my frontend code that calls this function:
App.js
addReview = (id, name, description, rating, codeToSubmit, timeAdded, account) => {
        this.setState({ loading: true })
        this.state.review.methods.addReview(id, name, description, rating, codeToSubmit, timeAdded, account).send({ from: this.state.account }).on('transactionHash', (hash) => {
            this.setState({ loading: false })
        })
    }


texts:
I wonder something about the usage of the metamask wallet for Dapp. I have implemented an Authentication mechanism to my Dapp with Keycloak, and I ask for blockchain wallet addresses of the users in the registration.
However, I need to be sure that when the user uses my Dapp, he/she uses the address they provided in the registration; otherwise, I need to revoke their request.
I use metamask as a wallet provider; thank you.


texts: Retrieve deposited number of Uniswap LP tokens from smart contract

texts:
I’m doing yield farming on a smart contract and I try to find out the total amount of my deposits. I know that I can follow the ERC20 tx on etherscan, but I would like to find an easier way. Under contract tab I found getBalanceOf function. The result is the following:

uint256  [ balanceOf(address) method Response ] uint256 :
988588442198945

I thought it’s wei, but after conversion it’s 0.0009 ether. I deposited way more so the function or the conversion doesn’t work as expected or the amount is not in wei.
What’s the best way to retrieve the deposits to a smart contract?


texts: generating raw trx and sending it to the network shows "invalid sender" error

texts:
I'm trying to make an ethereum raw transaction by php and these libraries:

https://github.com/simplito/elliptic-php

https://github.com/kornrunner/php-keccak

https://github.com/web3p/rlp

this is my code:

use Elliptic\EC;
use kornrunner\Keccak;
use Web3p\RLP\RLP;

$privateKeyHex = '.....'; // wallet private key
$toWallet = '118086be6247fBDa3BC64B4A11F07F3894aA1fAF';

$ec = new EC('secp256k1');
$key = $ec->keyFromPrivate($privateKeyHex );
$publicKeyHex = $key->getPublic('hex');
// $publicKeyHex => 0445e2caf0f227247dfa10440765812492e4d4c9df7b4e74d0d5cd3279fa80f5ef987a70e061ca20c06f09690957c9ba365cf06541181d1291e14c847d0d826583

$nonce= 0;
$gasPrice = 1e10;
$gasLimit = 21000;
$to = hex2bin($toWallet);
$value = 1e15-($gasLimit*$gasPrice)-1;
$inputData = 0;
//*********** EIP_155 *********
$chain_id = 1;
$r = 0;
$s = 0;
//*****************************

$SignData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$chain_id,$r,$s];
$SignRlpData = rlpEncode($SignData);
$signHash = Keccak::hash(hex2bin($SignRlpData), 256);

$signature = $ec->sign($signHash ,$key);
$r = $signature->r->toString('hex');
$s = $signature->s->toString('hex');
$v = $chain_id*2 + ($signature->recoveryParam +35);

$trxData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$v,hex2bin($r),hex2bin($s)];
$trxRlpData = rlpEncode($trxData );
// trxRlpData => f86b808502540be40082520894118086be6247fbda3bc64b4a11f07f3894aa1faf8702ce80355f5fff8026a0d879bd4319788f5e75fba039f879f7b38f25a80d1b6768f8c80d2e0dec7dc11aa0d952e26360e25f95821fc7f92d231925cd0cd1c412fc1d4b5bbdb439fbf0f19b

function rlpEncode($a){
    $rlp = new RLP;
    $encodedBuffer = $rlp->encode($a);
    return $encodedBuffer->toString('hex');
}

now after I send value of $trxRlpData to the ethereum network by https://etherscan.io/pushTx, show me this error message:

Error! Unable to broadcast Tx : {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"invalid sender"}}

but where is problem ?


texts: connecting geth to web3.js 1.0 via websockets or HTTP

texts:
I am building a minimal nodeJS application that should connect via web3.js to my geth node. I am following the official web3.js1.0 documentation and I am using web3 1.0.0-beta.29.

I do manage to connect via IPC but both HTTP and websockets fail - in both cases I get the same output from my JS script as if there was no geth running at all. Any help would be appreciated.

1) HTTP (not working)

geth:

geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"

index.js:

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545'); // same output as with option below
// var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
Error: Invalid JSON RPC response: ""

2) websockets (not working)

geth:

geth syncmode="fast" --cache=4096 --ws --wsport 8546 --wsorigins "*" console

index.js:

var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8546"); // same output as with option below
// var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
connection not open on send()
Error: connection not open

3) IPC (works)

geth: (same start as for HTTP)

geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"

index.js:

var net = require('net');
var Web3 = require('web3');
var web3 = new Web3('/Users/sebastian/Library/Ethereum/geth.ipc', net); // same output as with option below
// var web3 = new Web3(new Web3.providers.IpcProvider('/Users/sebastian/Library/Ethereum/geth.ipc', net));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
null [ '0x045a6A820FD596a4c1a49732af01E3EF1D6aEb8B' ]


texts:
There are about 2k ethereum addresses I'm supposed to send my ERC20 token to.
Doing this manually is a no no.
I've searched to and fro to no but most of the tutorials are not detailed enough.
So can someone show me a way to do this. Thanks


texts: Should I use contract Inheritance or Injection when separating code?

texts:
I am learning Solidity and contract development but I am a little confused about how to go about structuring the contracts. I know that I am going to divide the code instead of 1 large contract but I am unsure as to what approach to take.

I have been looking at inheritance but I am a little unsure as to what this entails for upgrades/updates. I was told that inheritance creates 1 large contract, would this mean that when I update 1 inherited contract they all get updated and thus lose the state/data?

Another approach that I quite like is injection, I am guessing that this approach will reduce transaction costs as I can update contracts independently of others, is this correct?

Obviously this would require managing the address locations. See below for an example I found here

pragma solidity ^0.4.6;

contract Caller {
    function someAction(address addr) returns(uint) {
        Callee c = Callee(addr);
        return c.getValue(100);
    }

    function storeAction(address addr) returns(uint) {
        Callee c = Callee(addr);
        c.storeValue(100);
        return c.getValues();
    }

    function someUnsafeAction(address addr) {
        addr.call(bytes4(keccak256("storeValue(uint256)")), 100);
    }
}

contract Callee {
    function getValue(uint initialValue) returns(uint);
    function storeValue(uint value);
    function getValues() returns(uint);
}

Any advice on what approach to take would be great, thanks.


texts: When should we call( ), watch( ) or get ( ) an event?

texts:
I find this concept to be very confusing, when should I be using watch, call or get to listen to an event? how are they different and when should they be used?

var event1 = newInst.getSupplier({'OwnAdd': someaddr},{fromBlock:'latest, toBlock:'pending'}, function(error, result) {
    console.log("listening bro1");
    if (!error)
        console.log(result.args);
});

How will the output differ when I change the call or watch or get?


texts:
NOTE: I'm aware of another question, but, it's related to 'fast' syncmode, and mine is of 'light' syncmode.

I'm running light node client for rinkeby using command:

geth --rinkeby --rpc --rpcapi personal,db,net,eth,web3 --syncmode=light

There was a break of more than 7 hours and after the restart, the current state of 'sync':

> eth.syncing
{
  currentBlock: 504738,
  highestBlock: 2408225,
  knownStates: 1149444,
  pulledStates: 1142442,
  startingBlock: 482170
}

I've two personal accounts, on rinkeby and they both have some ether:

0xf5120faca20afab4628c0270cff819348f612d6e has 18.589374 Ether
0xde51c26902f78a69bc3a5143d19e9dcff8607520  has 3.1605 Ether

But, in my local console the balance is shown as 0, why?

> eth.accounts
["0xf5120faca20afab4628c0270cff819348f612d6e", "0xde51c26902f78a69bc3a5143d19e9dcff8607520"]
> web3.eth.getBalance('0xf5120faca20afab4628c0270cff819348f612d6e')
0
> web3.eth.getBalance('0xde51c26902f78a69bc3a5143d19e9dcff8607520')
0

Should I wait for sync to be 'finished' in 'syncmode=light' before I could check account balance OR transact using the account?

NOTE: I'm aware of this question, but, it's related to 'fast' syncmode, and mine is of 'light' syncmode.


texts: Is it possible to attach an extension to a native code in an Ethereum node?

texts:
I need to execute some functions that are really difficult to write in Solidity, but there are plenty of libs already ready to use (computation of crypto algorithms).
Is it possible to create a kind of extension point in a smart contract asking the EVM to call a "native" code that is not in Solidity/Vyper (but in Java, for example)? The idea is that all the  nodes of a permissioned ethereum network have this code. Also, this native code does not depend on any external information.


texts: Could not find __Truffle__NotFound.sol from any sources

texts:
This is the file I'm trying to compile.

I've been using truffle for a few years and I remember that we used to be able to compile files with different names than the contracts inside.

I'm using truffle 5.0.35. Is this no longer the case?


texts: How to get require message in a test case? Truffle test

texts:
For instance I'm running testcase for a smart contract and it's test function has required validation.

function test(uint _id) public pure returns(bool){
    require(_id == 0 ,"not valid!");
    return true;
}

But when I execute the test case it throwing an error

  AssertionError: Error: VM Exception while processing transaction:
  revert

Test cases:

it("Adding test into blockchain", async () => {

    const result = await Instance.test(1);

    expect(result).to.be.not.equal('null');
});

it("Adding zero Id test into blockchain", async () => {

    const result = await Instance.test(0);

    //TODO: get error message
});


texts: How to detect the block number within solidity contract

texts: Is it possible to detect the block number that the transaction included within solidity? For example somebody transfer me some eth or token, can I know the block number of the transaction?


texts: How to start running a private blockchain with a custom genesis.json file on http://localhost:8545?

texts:
I have ran the following command:

> geth --rpc --nat none --dev --ipcpath "geth.ipc" init genesis.json

My genesis.json file looks like this (taken from the docs at https://github.com/ethereum/go-ethereum/wiki/Private-network):

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

How do I get this blockchain then running on http://localhost:8545?


texts: An ERC-1151 with two kinds of tokens, how to number them?

texts:
I have a potentially infinite set of each of the two kinds of tokens:

seller tokens corresponding to Ethereum addresses;
merchandise tokens corresponding to small uint256 values (item IDs).

What is the best way to represent both as tokens of a single ERC-1155 contract?
I would just convert the Ethereum addresses to uint256 and use the uint256 values as the token IDs, but that's insecure: If somebody uses a small number as his wallet address, he could gain access to a merchandise token he should have no access to.
So how to represent token IDs?
It is desirable to easily extract either a seller addresses or an item ID from the token ID.


texts: Cost of returning values through calls (Explanation of callvalue gas fee)

texts: As per the Ethereum yellow paper, it says that calls are 700 gas, however callvalue is 9000 gas. Does this mean that each word returned from a call is 9000 gas? Or even worse, each returned value?


texts: Golang Equivalent to list accounts on node - web3.eth.Accounts()

texts:
Does anyone know if its possible to get a list of the accounts on a node using golang, after Dialing to the node, basic PoC would be assuming the accounts are already unlocked via the CLI

Basically looking for the same functionality as web3.eth.Accounts() or to list the account addresses on a remote geth node that are already unlocked via the CLI


texts: Externally Owned Account use Contrast account to transfer ether

texts: can I use a Externally Owned Account to call contract account function to transfer ether to other Externally Owned Accounts, and the ether is from contract account.


texts: I came across the term memory-hard while ready about ETH POW algorithm. What does it mean when someone says that POW is memory hard?


texts: solidity interaction with a struct mapping of a deployed smart contract

texts:
I have followed the below code as follows on remix and it works fine but i have an issue when i try to access one of the struct value of a key.The last line of the code doesnt work.

pragma solidity ^0.4.6;
contract Product{
  struct ProductStruct {
    bytes32 name;
    bool status;
  }
  mapping(uint => ProductStruct) public productStructs;

  function updateProduct(bytes32 name, uint ID) returns(bool success) {
    productStructs[ID].name = name;
    productStructs[ID].status = true;
    return true;
  }
}

contract External {
  Product p;
  function External(address addr) {
    p = Product(addr);
  }

//below function works
 function readProduct(uint u) constant returns(bytes32 name, bool status) {
      p.productStructs(u);
    return(p.productStructs(u)); // works fine  @Rob Hitchens
  }

// below function doesnt work
  function readProduct(uint u) constant returns(bytes32 name) {
    return (p.productStructs(u).name); // It doesnt work
  }
}


texts: Are there networks that doesn't require ether to be spend to run?

texts:
When you deploy smart contract and then alter it's state in Ethereum networks (at least master and Rinkeby) you need to spend some gas = ether.

Can there be networks that don't need gas to run?


texts:
Noticed this wierd contract someone keeps creating, looks like some sort of scam, how does it work?
https://etherscan.io/address/0x4fa738cf30036505d106b22f60e64bf52e64aa77/advanced#code:
/**
 *Submitted for verification at Etherscan.io on 2020-08-16
*/

contract a1_quiz
{
    function Try(string _response) external payable
    {
        require(msg.sender == tx.origin);

        if(responseHash == keccak256(_response) && msg.value > 1 ether)
        {
            msg.sender.transfer(this.balance);
        }
    }

    string public question;

    bytes32 responseHash;

    mapping (bytes32=>bool) admin;

    function Start(string _question, string _response) public payable isAdmin{
        if(responseHash==0x0){
            responseHash = keccak256(_response);
            question = _question;
        }
    }

    function Stop() public payable isAdmin {
        msg.sender.transfer(this.balance);
    }

    function New(string _question, bytes32 _responseHash) public payable isAdmin {
        question = _question;
        responseHash = _responseHash;
    }

    constructor(bytes32[] admins) public{
        for(uint256 i=0; i< admins.length; i++){
            admin[admins[i]] = true;
        }
    }

    modifier isAdmin(){
        require(admin[keccak256(msg.sender)]);
        _;
    }

    function() public payable{}
}


texts: If I buy a mining rig of 6 x Radeon RX 580 8GB cards and start using it 24 hours a day, 365 days a year with the temperature below 70 degrees Celsius. How much will the rig depreciate in value every year?


texts: Calling transfer returns true but doesn't perform the transfer

texts:
I have the following simple transfer method in my contract to transfer my erc20 token to another account:

function transfer(address to, uint tokens) public returns (bool success) {
    balances[msg.sender] = safeSub(balances[msg.sender], tokens);
    balances[to] = safeAdd(balances[to], tokens);
    Transfer(msg.sender, to, tokens);
    return true;
}

When I call this from angular through web3 doing the following it returns true as the result but nothing seems to be updated on the ropsten network. Is there anything that im missing here.

 tokenContract.transfer.call(_transferTo, window.web3.toWei(_amount),{ from: _transferFrom }, function(err, status){
    if(status) {
      return resolve({status:true});
    }
});


texts: Unlinkability between transactions to a smart contract

texts:
I am trying to develop an application using Ethereum and it needs to have transactions which are not linkable.

I read an article by Vitalik Buterin, which speaks about it. He speaks about something called "internally contained private key"
 in the smart contract. What does he mean by that? Is there any way in which transactions to the smart contract could be encrypted?


texts: Solidity Test - which are the variables and keywords over here

texts:
Can anyone help me in understanding what is happening over here? I understand that the contract name is TestAdoption, but after that - what is the first word "Adoption"? The second word "adoption".  I do acknowledge and note that my contract has been defined as "Adoption" - so the first word should be that contract. But then what is the variable being equated (set) to?

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

Here is the link, which I have been studying: http://truffleframework.com/tutorials/pet-shop


texts: I need help writing a working ERC 721 contract

texts: I have been unable to write a working ERC 721 contract.Can someone help me with a sample ERC 721 contract that works? I have been learning for about a week now and I haven't made much progress.


texts: BUYING BUNNY WITH ETH.... Etherscan showing "dropped?" Don't know what to do

texts:
To preface, I'm crypto dumb except for buying /selling BTC. I don't mess with Alt coins much... and this issue is why!!!! HELP!!!
So I tried to acquire some BUNNY with ETH on Uniswap. I checked it this morning and the status says "dropped." What do I do?
https://etherscan.io/tx/0xda57edfc9e5e69b219763b5194dfe255aa1d3b62da88a87a5a9303bfb29538e7


texts:
Hi I have been trying to deploy a contract from geth console to the testnet, I established a connection and also mined to make sure its all working... one thing I couldn't do for some reason is use solc in my geth console, whenever I try to compile inside the console I get the error:

  solc: exit status 1
  Must provide a file

I couldn't figure it out so if anyone may have solved it or encountered it I would be greatful!

Another thing is that when I try to deploy a compiled solidity contract (compiled in an online service) i keep getting the same result

console.log('Contract mined! address: ' + contract.address +
    ' transactionHash: ' + contract.transactionHash);

Why is there no address here? and no transaction hash?

Anyway thanks for anyone who may help!


texts:
I've seen some example's, where the contract deploys other contract (e.g. this one), but is it possible to do so using binary of the contract? something like:

function deployContract(bytes contractsBin) { ... }

As far as I know there is no way to send transaction via contract, so RPC way is not an option.


texts: How to transfer tokens from metamask to myetherwallet

texts: Can't seem to find a "send tokens" button on metamask. Does anyone know how to do it?


texts: What are the critiques of Ethereum made by Bitcoin experts? And which ones do not apply to Bitcoin?

texts: Ethereum has been discussed by Bitcoin experts, for example on IRC such as #bitcoin-wizards. What are the critiques of Ethereum made by Bitcoin experts? Which ones apply and do not apply to Bitcoin?


texts: can't use the crypto money I earn working for gitcoin.com

texts:
Recently I resolved a public GitHub issue and was paid 125 units.
I was told its worth about 125 dollars.

I've installed the chrome metamask plugin.
I also purchased 5 dollars worth of ETH from coinabase,
which I see in my metamask plugin.

I also see the 125 I earned doing the work.

Why is these two shown separately like this?
What do the two icons mean?
I'm trying to send 125 to
  a) a person or
  b) a checking account
  c) or back to gitcoin.com to fund another GitHub issue as a funder this time

But metamask won't let me send the 125, I am only able to send the $2.xx
which I believe is the leftover from the $5 purchase from 'coinbase'

help


texts:
i added this code to my contract

    function withdraw() public onlyOwner{
        msg.sender.transfer(address(this).balance);
    }

    receive() external payable {msg.value}

    fallback() external payable {msg.value}

also i tried this way
  constructor() public payable {

    function withdraw() public onlyOwner{
        msg.sender.transfer(address(this).balance);
    }

    receive() external payable {msg.value}

    fallback() external payable {msg.value}

    }

and tried to use
contract AAA  is Ownable payable {
...

}

instead of
contract AAA  is Ownable {
...

}

the problem is that i cannot send ether to the contract even from the contract owner wallet address. what i do wrong?  solidity ^0.6.12
the error is Error Message: execution reverted
to send ether i use metamask and rinkeby testnet


texts: I am attempting to create a smart contract counter. Can I use the data returned by web3.eth.getTransaction() to determine if the transaction created a smart contract?