texts: How to display the value of a variable using remix debugger and emit

texts:
pragma solidity ^0.5.1;

contract test {
    event test_value(uint256 indexed value1);
    uint256 value_test;

     function test_f() public {

        //value_test processing
        emit test_value(value_test); // log the current value
    }
}

Can some body please guide me how to display the value of "value_test" using Remix debugger or emit?


texts:
I'd like to estimate the gas of a simple ERC20 transfer between two addresses. The web3.js docs on estimateGas are admittedly confusing:

// using the callback
myContract.methods.myMethod(123).estimateGas({gas: 5000000}, function(error, gasAmount){
    if(gasAmount == 5000000)
        console.log('Method ran out of gas');
});

The myMethod(123) is what I find confusing. What is that for? The following is what I'm currently thinking, but I'm getting TypeError: contract.methods.send is not a function. What should I substitute for myMethod(123)?

contract.methods
   .send("0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe")
   .estimateGas({ gas: 60000 }, (error, gasAmount) => {
      return gasAmount;
});


texts:
I have a test code on Remix and have been getting ParseError: Expected Primary Expression. The error happens in function Enquiry -- at event definition - line.

ParserError: Expected primary expression. event itemsListDisplay (bytes32 itemId, bytes32 itemDescription, bytes32 auctionStatus);
^

My reason for using event is to display a listing when the function is called by an approved participant. Each listing of items would be in a new line.

Any other suggestion for improved code style will also help.

Thanks. Below is the test code.

contract Request is MasterContract,
ApprovedParticipantsContract, ApprovedItemsContract {

    function Enquiry (address _address) returns (bool flag) {

    event itemsListDisplay (bytes32 itemId, bytes32 itemDescription, bytes32 auctionStatus);

    if (approvedParticipantsList[_address].isValue) {

        uint len = itemsList.keys.length;

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

            bytes32 myItemId = itemsList.keys[i].itemId;
            bytes32 myItemDescription = itemsList.keys[i].itemDescription;
            bytes32 myAuctionStatus = itemsList.keys[i].auctionStatus;

            itemsListDisplay(myItemId, myItemDescription, myAuctionStatus);

        }

        return true;

    }

    return false;

    }

}


texts: TypeError: Data location must be "memory" for return parameter public view returns (address[16]){

texts:
I know that is question has been answered in one form. However, I could not find an answer for my specific case.

Here is my code:

pragma solidity ^0.5.0;

contract Adoption {
 address[16] adopters;

//Adopting a Pet
function adopt(uint petId) public returns (uint){
  require(petId >= 0 && petId <= 15);
  adopters[petId] = msg.sender;
  return petId;
}

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

 }
 }

Right now this is throwing a

  TypeError: Data location must be "memory" for return parameter in
  function

but none was given error and the error is originating from

function getAdopters() public view returns (***address[16]***){

From my understanding, memory is just a key word that creates a temporary variable. Do I need to use a storage variable for the public address array?

I am going based off of this tutorial: https://truffleframework.com/tutorials/pet-shop


texts: Error - Gas required exceeds allowance or always failing transaction

texts:
I'm just starting to program in solidity and deploy smart contracts in a local created blockchain.

I'm trying to deploy a simple smart contract using remix and web3 provider and this error is killing me all time.

Here is my code. I'm simply trying to parse a json file to save it as structs. If you know a better way to do it, it would be great! I'm now using a library from github that I think is usefull for my use case, but I need some help with the code.

pragma solidity ^0.4.21;

import 'github.com/chrisdotn/jsmnSol/contracts/JsmnSolLib.sol';

contract MusicalContract {

    struct parameters {
        string name;
        string mr_share;
        string pr_share;
        string sr_share;
        string country;
        string walletDir;
    }

    //event debugStr(string str);
    //event debugInt(uint i);

    parameters[] public params;

    string public json = '[{"name":"Martin","pr_share":"2","mr_share":"2","sr_share":"2","country":"2101","walletDir":"12345"},{"name":"Ahoj","share":"","walletDir":"2589","pr_share":"2","mr_share":"2","sr_share":"2","country":"36"},{"name":"Cus","share":"","walletDir":"12345","pr_share":"2","mr_share":"3","sr_share":"1","country":"2100"}]';

    /*
    function MusicalContract(string json) {

    }
    */

    function MusCo() public {
        uint returnValue;
        uint actualNum;
        JsmnSolLib.Token[] memory tokens;
        string memory jsonElement;
        JsmnSolLib.Token memory t;

        (returnValue, tokens, actualNum) = JsmnSolLib.parse(json, 200);

        for(uint ielement=0; ielement < actualNum-1; ielement++) {
            t = tokens[ielement];
            jsonElement = JsmnSolLib.getBytes(json, t.start, t.end);
            //emit debugStr(jsonElement);
            //emit debugInt(ielement);
            if(compareStrings(jsonElement, "name")) {
                t = tokens[ielement+1];
                params[ielement].name = JsmnSolLib.getBytes(json, t.start, t.end);
            } else if(compareStrings(jsonElement, "pr_share")) {
                t = tokens[ielement+1];
                params[ielement].pr_share = JsmnSolLib.getBytes(json, t.start, t.end);
            } else if(compareStrings(jsonElement, "mr_share")) {
                t = tokens[ielement+1];
                params[ielement].mr_share = JsmnSolLib.getBytes(json, t.start, t.end);
            } else if(compareStrings(jsonElement, "sr_share")) {
                t = tokens[ielement+1];
                params[ielement].sr_share = JsmnSolLib.getBytes(json, t.start, t.end);
            } else if(compareStrings(jsonElement, "country")) {
                t = tokens[ielement+1];
                params[ielement].country = JsmnSolLib.getBytes(json, t.start, t.end);
            } else if(compareStrings(jsonElement, "walletDir")) {
                t = tokens[ielement+1];
                params[ielement].walletDir = JsmnSolLib.getBytes(json, t.start, t.end);
            }
        }
    }

    function compareStrings (string a, string b) view returns (bool){
       return keccak256(a) == keccak256(b);    }

    function getContractAddress() public view returns (address) {
        return this;
    } }


texts:
I failed to load a script into a private blockchain setup using puppeth. I have used puppeth to configure a private blockchain (PoA) with a few sealers on different vms. Could someone help?

I now need to load a script. I tried using:

geth --preload "/path/to/hello.js"

with the error: Error starting protocol stack: datadir already used by another process
since the vm has the sealer nodes running in a docker. The proof is here after running ps aux:    geth --networkid <...>--cache <>--port <...>--maxpeers <....>--ethstats <...> --bootnodes ....

I tried loading the script directly through the console by doing this:

docker exec -it <container ID> geth  attach ipc:/root/.ethereum/geth.ipc

and in the console type:
loadScript('hello.js')   where hello.js is in the directory where I typed the geth attach command above. Also tried loadScript('path to hello')

All of the following links state that the path to the javascript is incorrect
but I ensured that the file path is where it should or is where I ran geth attach. My goal is to have script running even if I need to stop the docker container and restart geth. But the issue is that I cannot pass the --preload argument because I am using puppeth, I think :)

How can access to a external file using loadScript?
loadScript() returns false error


texts: Sending Ether between two contracts not working

texts:
I am trying to transfer some Ether between two contracts but it is just not working for me. Here is my code:
pragma solidity ^0.6.0;

contract ContractA {
    uint public tips;

    /**
     * Function to collect the tips.
     */
    function collectTips(address payable _recipient) public {
        require(_recipient.send(tips));
        tips = 0;
    }

    /**
     * Receive function in order to receive tips. No calldata is set
     */
    receive () external payable {
        tips += msg.value;
    }
}

contract ContractB {
    uint256 public tips;

    /**
     * Receive function in order to receive tips. No calldata is set
     */
    receive() external payable {
        tips += msg.value;
    }
}

Whenever I send a transaction to collectTips, giving the contract address of ContractB I get the following error in remix
transact to ContractA.collectTips errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

I was referring to these docs: https://docs.soliditylang.org/en/v0.6.0/contracts.html#receive-ether-function
I am clueless. Anyone an idea what I am doing wrong?
I found also sort of the same question around here, but nothing helped. Either the Solidity version is too old or just not working for me :/
Best and thanks in advance


texts: Transfer ether between two addressrd using call

texts:
I have this code:
function regAgent(uint[] memory _preferences) notOwner onlyBeforeEnd public {
    require(msg.sender.balance - fee >= 0, "You can't pay the fee.");
    require(!registered[msg.sender], "Agent is already registered.");
    Agent memory newAgent = Agent(agents.length, msg.sender, _preferences);
    agents.push(newAgent);
    registered[msg.sender] = true;
    (bool success, ) = owner.call.value(100)("");
    // the agent must pay the fee to participate
    // owner must recieve that fee
}

It is assumed that a participant calls that function, pays a fee, and that fee is paid to the address of the owner (the person who deployed the SC). But there is something that is not clear to me... If I add this line (bool success, ) = owner.call.value(100)(""); the owner is supposed to receive 100 (gwei, ethers?). But who gives it to him? How do I get the participant to transfer his ether to the owner?
Could anyone show me an example? Any info is welcome too. Thanks a lot.


texts: Interacting with Already deployed Ethereum Contract and recording response

texts:
I understand this topic has been discussed before, but my question is specific to web3.py. How can I interact with function of already deployed ethereum contracts on Ropsten TestNet. my code runs with out any error but their is no indication on blockchain that its really worked? Please help me.
I am calling function is following way:

response = contract_data.contructor(args)
response = contract_data.functions.my_function_name(args).call()


texts: Trying to compile running: 'node compile.js', but get error: "assert.js:350 throw err;" [Udemy 'Complete Developers Guide' Course]

texts:
This is the first contract with this Udemy course.

Trying to compile by running: "node compile.js" but get the following error:

iii@iii:~/inbox$ node compile.js

assert.js:350
throw err; ^

AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (/home/iii/Digital Ledger/inbox/node_modules/solc/wrapper.js:97:7)
at compileStandard (/home/iii/Digital Ledger/inbox/node_modules/solc/wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (/home/iii/Digital Ledger/inbox/node_modules/solc/wrapper.js:214:14)
at Object.<anonymous> (/home/iii/Digital Ledger/inbox/compile.js:9:6)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)

This is my "compile.js" code:

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');

module.exports = solc.compile(source, 1);

And the simple contract:

pragma solidity ^0.4.17;

contract Inbox {
    string public message;

    function Inbox(string iniMess) public {
        message = iniMess;
    }

    function setMess(string newMess) public {
        message = newMess;
    }
}

And this is the file structure:

-inbox
    -node_modules
    -contracts
        -inbox.sol
        -package.json
        -package-lock.json
    -compile.js

Thank you for any help :)


texts: Scam: Sent ETH to HEX Contract - Where is it?

texts: I sent ETH to the HEX contract, waited for 24 hours to transform and was ready to click "exit" at the end but it just disappeared?


texts:
I have a contract with a bunch of functions that don't involve ethers or any kind of funds at all. Basically all I want is to have a html page with forms that allow people to use those functions.

All transactions would be done from the same ethereum address, using ether only as gas. Users would need an account to avoid anyone draining all my gas, account that I only give to certified people, and with a limited number of transaction per day or per hour.

Basically, users don't even have to know they're using a blockchain.

Currently my contract is running fine on Ethereum Wallet, what would I need to deploy an app ? Tutorials I find seem overcomplicated.

What is the most simple way to call contract functions from a web page ?


texts:
The Clique consensus seems to be always sealing a new block at fixed intervals of period seconds, where period is the setting in the genesis block (config.clique.period).

That seems wasteful, indeed Parity's Aura only signs empty blocks when a transaction is recorded or a transfer to another node takes place (normally every 120 seconds, see --reseal-on-txs and --reseal-min-period args).

Is it possible to get geth to work like that? I don't care about immediate resealing, but it would be really nice to skip empty blocks, even if not completely.


texts:
According this documentation

  types shorter than 32 bytes are neither zero padded nor sign extended
  and

When I use abi.encodePacked(address, uint, uint, address) I am getting a result with lot of zeros.
For example:

address addr = "0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C";
uint x = 123;

abi.encodePacked(addr , x , x , addr)
0x14723a09acff6d2a60dcdf7aa4aff308fddc160c000000000000000000000000000000000000000000000000000000000000007b000000000000000000000000000000000000000000000000000000000000007b14723a09acff6d2a60dcdf7aa4aff308fddc160c

Shouldn't it be without zeros.


texts: Infura authentication in truffle-config.js

texts:
I have create a project on infura.io website.
I have create a new truffle project.
Here is my truffle-config.js file:
const path = require("path");
const HDWalletProvider = require("@truffle/hdwallet-provider");

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    develop: {
      port: 8545
    },
    ropsten: {
      provider: function() { return new HDWalletProvider(`${process.env.MNEMONIC}`, `${process.env.INFURA_URL}`) },
      network_id: 3
    }
  },
  compilers: {
    solc: {
      version: "0.8.0"
    }
  }
};

I have set MNEMONC and INFURA_URL environment variables.
Everything works fine.
Infura allows me to enable a secret and/or jwt authentication.
I have read a lot of documentations/tutorials and i do not understand where i can specify this secret or jwt configuration in truffle-config.js
Do you have any idea ?
Thanks


texts:
I'm trying to authenticate users by comparing the hashes created by backend server and contract. Seems like "byte32" values cannot be coerced into strings. So, instead I'm converting it into uint256. But the function doesn't accept it.
On my backend (I'm using Remix IDE to manually test the smart contract)
let hash = web3.utils.soliditySha3(secret+nonce);
console.log(hash);

In my smart contract:
 function addUser(string calldata _name, uint256 _hash) external{
        require(_hash == uint256(keccak256(abi.encodePacked(secretkey, nonce))));
        lastfmAuth[_name] = msg.sender;
        nonce++;
 }

What is the right way to do this?
Somewhat similar question:
How to Keccak 256 hash in front end JavaScript before passing it to my smart contract


texts: Interacting with dapps using wrapper smart contract (and not personal accounts)

texts:
Metamask (or other browser plug-in) helps a lot the user to submit transactions using his personal account since it manages his private keys.

When interacting with an dapp front-end, web3 will create a transaction and the user can easily sign it and submit it with his personal account using metamask.

For example, the user can easily submit a transaction to breed kitties on cryptokitties if he owns them.

In this similar context of web3 creating a transaction to sign, what is the feasible way to submit the transaction using a wrapper smart contract as a relay to the user personal account? In other words, the personal account signs a transaction to a wrapper smart contract and this wrapper smart contract calls the dapp.

It could be useful to do this if this wrapper smart contract owns the kitties (and not the user personal account) for example. In this case, the personal account can be the owner of the smart contract.

The relay function of the wrapper contract could be a function like this.

function a (address to, uint256 valueInWei, bytes hexData)  {
   require( to.call.value(valueInWei)(hexData), "failed" );
}

hexdata in this case is composed by the name and arguments of the function-to-be-called.


texts: How much does it cost to send all tokens to a liquidity pool?

texts:
I'm creating a token, and will create a liquidity pool on pancakeswap with a BNB pairing. If I have 20 billion tokens, and send them all to the pool with a price of $0.0000001/token. How much would it cost me to create the liquidity pool? I am assuming I pay 10 billion x 0.0000001 =  $1 thousand dollars + gas fees.
Is this correct?
If it is. If somebody decided to purchase all 10 billion coins at once (irrational behaviour but let's just assume),

Would they get them all for $1 thousand dollars or would the value appreciate during the buy and the buy fail?
What's stopping them from doing this and completely ruining/dominating the coin?
Would pancakeswap allow for the mass purchase?
Would the coin appreciate in value?

I've done as much research as I can, but these specific questions are not yet answered.
Thanks for any insight


texts: How is the gasPrice generated in ethereum

texts:
while I execute eth.gasPrice via the geth console,it returns the current default gasPrice 20322509741, so

how is this default value generated
will it changes now and then according to the market
transaction creators hope the lower gasPrice while the miners opposite，how to reach an agreement
miners could start the geth with the parameter --ask to set the lowest gasPrice，will the setting changes during the runtime?


texts: Dynamically-sized byte array is value type?

texts:
In the doc, it says

bytes:
Dynamically-sized byte array, see Arrays. Not a value-type!

string:
Dynamically-sized UTF-8-encoded string, see Arrays. Not a value-type!

    Not a value-type!

If bytes/string are not value-types, why are these placed in Value Types section?


texts: Clarification on "password" argument for web3.eth.personal.sign

texts:
Context: I'm fairly new to web3, and as we all know it's developing quite regularly. I'm working towards a "sign in with Metamask"-type functionality using web3@1.0.0-beta.46.

Most of the docs/discussions online I've seen recommend using web3.eth.personal.sign over the other signing methods (at least for the purpose of signing a message to prove ownership of an address), but all examples I've seen online seem to ignore the third argument, password, which is described in the docs as "The password of the account to sign data with."

Up until 1.0.0-beta.38, the password argument could be left undefined, but with 38 now throws Invalid Arguments length: expected: 3, given: 2.

Looking at the docs, they provide an example:
https://web3js.readthedocs.io/en/1.0/web3-eth-personal.html#sign

web3.eth.personal.sign("Hello world", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!")
.then(console.log);

It seems silly to simply pass in a static string. There's gotta be something here I'm not getting.

Can someone clarify what the point of the password argument is? Is it to be used like a challenge or a salt? Should I pass in my nonce, instead of adding it to the message string?  Am I way off?

I'll keep digging, but could use some guidance. Thanks.

edit: changing the password value doesn't change the signature.


texts:
I'm struggling to integrate swapExactETHForTokens into remix but I fail since I don't have any kind of coding experience
It shouldn't be anything fancy just a simple code that would allow me to buy a token from the contract
I checked out the official docs https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
I'm trying this code but not sure if it's the right one How to use swapExactETHForTokens in smart contract?
I know what each of those function should be filled with but I don't know exactly what's the exact uint integer and where exactly I need to insert the wallet, contract, amount, and so on
Can anyone show me a full working example(like swap eth to usdt) that I can throw on remix and go from there?


texts:
My Event outputs an indexed parameter uint id.

Can I query the logs for the max value of id, without returning and searching through all log records?

I'm guessing not, since indexed values are stored as a hash so value comparisons would be impossible, but maybe I'm missing something.

How else could a single uint value be "cached" to the logs without having to retrieve all logs of that type?


texts:
Hi for a while now i have been testing ethereum capabilities and there is something i wanted to test and i cant figure how to do. When creating a contract of a custom token (using the code given in the ethereum official site) there is a sell price to set and a buy price for a token, in what way can i use this to give a token sell price of another token?

What I mean is, is there a way to give token A price in token B? essentialy making it possible to a user who have Token B to buy token A? and could a contract hold more than 1 kind of a token? like a contract that holds both token A and B? and maybe even more?


texts: Is it possible to build a private (permissioned) blockchain with Ethereum?

texts: Ethereum is a great blockchain, but for some services the transaction fee is prohibitively too expensive. Is there any project and/or guideline on making Ethereum so it works on permissioned blockchains - i.e., with the consensus algorithm and mining replaced by majority vote? Would a simple fork of the network work fine, or is there any reason this wouldn't work?


texts: What does the balance mean in EtherScan?

texts: For example, IDEX has 40,767.582633880607462483 Ether. But I use BalanceAt function and only get 15.884 Ether. Why? Should I traversal all the tokens and query balanceOf("0x2a0c0DBEcC7E4D658f48E01e3fA353F44050c208")?


texts: ALERT: Transaction Error. Exception thrown in contract code.(metamask)

texts:
i am working on truffle Pet-shop with react, i am using local blockchain ganache with metamask, The issue I'm encountering with my application is that when i am trying to call deleteAdopter function from UI, metamask opens and says

ALERT: Transaction Error. Exception thrown in contract code.

but if i call adopt function it executes successfully on contract and my UI changes and pet mark as adopted.
here is the code
Adoption.sol
pragma solidity ^0.5.0;

contract Adoption {
    address[16] public adopters;

    // Adopting a pet
    function adopt(uint petId) public returns (uint) {
        require(petId >= 0 && petId <= 15);
        require(adopters[petId] == address(0), "already adopted pet");
        adopters[petId] = msg.sender;

        return petId;
    }

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

    //Releasing a pet
    function deleteAdopter(uint petId) public returns(uint) {
        require(msg.sender == adopters[petId], "Only adopters can call this function");
        delete adopters[petId];
        return petId;
    }
}

// Releasing a pet
//  function release(uint petId) public returns (uint) {
//    require(petId >= 0 && petId <= 15);

//    if (adopters[petId] == msg.sender) {
//      adopters[petId] = address(0);
//    }

//    return petId;
//  }


texts: Ive installed Ethereum Wallet 8.10, and when I try to sign in it says to wait until my node has fully started. it says downloading blocks (5 peers) and 139,782 of 3,944,815. Does this usually take a long time? Did I miss a step?


texts: How can I get a private geth instance on Azure to interact with the public blockchain?

texts:
So I am referring to Microsoft Azure's new blockchain as a service Ubuntu geth instance. I've set this up no problem and have run through the tutorial, but I'm trying to think of how I would get this to interact with/broadcast to the public blockchain. What is the bridge? This private instance comes with it's own genesis block and private key and test ether, but I'm having trouble figuring out the next step for integration.

Can someone please help point me in the right direction?

I've been looking at Truffle and Embark too, but I guess my same question would apply about bridging this gap between the private and the public.


texts: Unable to deploy smart contract to rinkeby using ledger wallet?

texts:
I am trying to deploy smart contract using ledger wallet. But i keep getting the error cant subscribe to new header. However i get the transaction hash but cant receive the contract instance and receipt.

var myContract = new my_web3.eth.Contract(this.state.abi);
        myContract.deploy({
            from: this.state.defaultAddr,
            data:this.state.byteCode

        })
        .send({
            from: this.state.defaultAddr,
            gas: 1500000,
            gasPrice: '30000000'
        })
        .on('error',error=>{

            console.log(error)
            this.setState({
             errors:error
            ,infoHidden:true
            ,errorHidden:false
            })
        })
        .on('transactionHash', transactionHash=>{
         console.log(transactionHash) })
        .on('receipt',receipt=>{
           console.log(receipt) // contains the new contract address
        })
        .on('confirmation', function(confirmationNumber, receipt){
          console.log(confirmationNumber) })
        .then(newContractInstance=>{
            console.log(newContractInstance) // instance with the new
                 contract address

                this.setState({
                Contract:newContractInstance,
                infoHidden:false,
                errorHidden:true})
            console.log("Contract
            Address"+newContractInstance.options.address);
            this.props.history.push({
                pathname:'/save',
                state:{
                // ABI:response.data.data.abi,
                // byteCode:response.data.data.byteCode,
                ContractAddress:newContractInstance.options.address,
                ABI:this.state.abi,
                    }
                    })

        })

Connection Snippet

   var my_web3
    let account;
    const rpcUrl = "https://rinkeby.infura.io/";

   const use_ledger =localStorage.walletAccessMechanismType;
   console.log(use_ledger)
    if(use_ledger =="ledger")
    {
    const engine = new ProviderEngine();
    const getTransport = () => TransportU2F.create();
    const ledger = createLedgerSubprovider(getTransport, {
    networkId: 4, // 3 == Ropsten testnet
    });
    engine.addProvider(ledger);
    engine.addProvider(new RpcSubprovider({ rpcUrl }));
   engine.start();
   my_web3 = new Web3(engine);
  } else if(typeof(web3) === 'undefined') {
    my_web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl));
  } else {
     my_web3 = new Web3(window.web3.currentProvider);
    }


texts: Does saving pointer to array length update when length is updated?

texts:
While using truffle to write tests I had something similar to the following in my contract and was getting an invalid opcode error.

var length = myList.length; // 2
delete myList[1];
myList.length = length - 1;

When I updated the code to the following it worked:

delete myList[1]
myList.length = myList.length - 1;

Why does the second code work, but the first throws invalid opcode?


texts: i'm a beginner in using blockchain. Based on my knowledge, there are two ways blocks are created, mining and sending transactions. As there is an explanation to input additional data while sending a new transaction to other user in here: How do I send an arbitary message to an Ethereum address?. I wonder, is there a way to input the additional data while mining? I just want to store the data inside the blocks and not sending any transactions. Thank you


texts: How to remove byte code of deployed smart contract which was deployed using Ropsten Test Network?

texts:
I 've deployed my smart contract on Etherscan using Ropsten Test network. I can see there is bytecode for my deployed contract on ropsten etherscan. I want to hide or don't want to show the bytecode for my contract.
Is it possible? If Yes then What should I do?


texts: Do I Need to create my own Node and Sync it with the Main Network in order to create Accounts via Web3?

texts:
As my Question title states, I would like to know, If it's a requirement to run my own hosted Geth Node synched with the Main-Network in order to use web3.js (localhost Node?) to create accounts?

Or is it possible to "point" web3 with the Main Network as a provider? and with this reference, create accounts for example?

If the latter is possible, Could you please show me an example?

-Kind Regards,


texts: Flatten Truffle Solidity Contracts for Etherscan's `Verify Contract Code` Feature

texts:
Etherscan.io has a Verify Contract Code feature that takes the inputs Solidity Contract Code and Constructor Arguments ABI-encoded.

Question: Is there a tool to flatten your solidity contracts (written in conjunction with the use of Truffle), and maybe even generate the ABI-encoded constructor arguments, so as to speed up your use of Etherscan's contract verification feature?

Tried Blockcat's python script solidity-flattener but could never get it to work. Hoping to discover a new alternative method.


texts: Perform an automated transaction using 1inch API

texts:
To perform an automated 1 inch transaction I use these two functions.
It works well at first. Unfortunately, in the last few days I have always had the same errors:

Fail with error 'Return amount is not enough'

Warning! Error encountered during contract execution [Reverted]
def get_api_call_data(_from_coin,_to_coin):
    global api_data

    try:

      call_data = requests.get(
      f'https://api.1inch.exchange/v1.1/swap?fromTokenSymbol={_from_coin}&toTokenSymbol={_to_coin}&amount={_amount_to_exchange}&fromAddress={base_account}&slippage={slippage}&disableEstimate=true')

      api_data = call_data.json()

    except:
      logging.exception("get_api_call_data")

    return api_data

def one_inch_token_swap(_from_coin,_to_coin):
  global tx_hash

  web3 = Web3(Web3.HTTPProvider(eth_provider_url))
  nonce = web3.eth.getTransactionCount(base_account)
  json_data = get_api_call_data(_from_coin,_to_coin)
  data = json_data['data']
  to = json_data['to']
  value = _amount_to_exchange

  url_fees = 'https://ethgasstation.info/api/ethgasAPI.json?'
  r_fees = requests.get(url_fees)
  js_fees = json.loads(r_fees.content)
  Fastest = js_fees['fastest']

  tx = {
      'nonce': nonce,
      'to': to,
      'value': _amount_to_exchange,
      'gasPrice':(Fastest+100)*(100000000),
      'from': base_account,
      'data': data,
  }

  gas = web3.eth.estimateGas(tx)
  tx["gas"] = gas

  signed_tx = web3.eth.account.signTransaction(tx, private_key)
  tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)

what could be the cause of this error?


texts: How to verify whether a certain transaction is mined by the newest block programmatically?

texts:
What I thought I should do

I implemented this functionality with Bitcoin Core through zmq support.

Keep "my transactions" through zmq's rawtx topic.
When received zmq's rawblock, decode the raw block, get transaction ids from it, compare them with 1's transaction id, and confirm them if matched.

So I thought I should be doing

Find something like Bitcoin Core.
Find some TCP interface.
Do the above 1-2.

What I tried so far

So first of all I chose to use geth, which is one of the most popular Ethereum-implementing node, and looked for RPC-PUB-SUB docs. I found that its newPendingTransactions subscription corresponds to zmq's rawtx. But I couldn't seem to find what corresponds to zmq's rawblock. Of course there's a newHeads subscription, but for what the API returns, I don't see any hint to decode which transactions are mined by that block.

Some library like ethereumjs-block does seem to create a block from raw Buffer though.

What I'm trying to do

Be independent as much as possible from what geth's wallet system offers. The best thing is to only use that PUB-SUB functionality. (Get a raw block, decode it, get transactions, and so on.)

If I go one step back, I may do polling via, like, eth_blocknumber and eth_getBlockByNumber, but that's not what I want for now.

If there's other way around for this, please give me some rough idea. I don't mind using other Ethereum client.


texts: How to send Ethereum to smart contract address without using keyword "payable"?

texts:
I have tried to send Ethereum from my wallet to the smart contract address by using the below code:
pragma solidity >=0.6.10;

contract NoUsePayable {
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

contract selfDestruct {
    function kill(address payable addr) public payable{
        selfdestruct(addr);
    }
}

However, this way still uses the payable keyword. Can anyone help me solve this problem?


texts: Why geth switch to full node when starting

texts:
I start my geth with --syncmode "fast" but I get this warning:

WARN [01-21|14:47:59.148] Switch sync mode from fast sync to full sync

And my geth will start with full sync mode with this warning. Any solution for this?

OS version: CentOS Linux 7

Full command:

$ go-ethereum/build/bin/geth --syncmode "fast" --rpc --rpcapi db,eth,net,web3 --cache=16384 --rpcport 8545 --rpcaddr 0.0.0.0


texts: At what point does the synchronization end?

texts:
I am just trying to setup my old laptop to mine just to see how it will do and I downloaded the latest version of Geth and began the sync with

"geth --rpc --fast --cache=512"

It did its thing but it does not seem to end. I am referencing https://etherscan.io/ where is shows the number now at ~38007XX the sync is at this amount and just continues to go up and not complete as more blocks continue to be completed. Have I messed something up?


texts: What if a malicious party sends two transactions with same nonce?

texts:
It's said nonce is used to prevent reply/double-spending attack. But an adversary can send two transactions with the same nonce, and the rest of scenario will be the same as in Bitcoin.

Question 1: How does nonce really help to prevent double spending attack?

Question 2: Using nonce would relief us from 6 confirmations?

Edit: By nonce I mean the once included in each transaction in Ethereum.


texts: Simulate how a transaction will affect state before it is mined

texts: My program needs to know how the transactions in the mempool will affect the state when mined. Does anyone know of any tools to help with this? I know I can do it manually with ganache --fork, but I don't know a good way to automate it without starting from scratch


texts:
During an Audit I got a warning for this code lines:

https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
    // recommends that there are no checks for the approval double-spend attack
    // as this should be implemented in user interfaces

function approve(address spender, uint tokens) public returns (bool success) {
    allowed[msg.sender][spender] = tokens;
    emit Approval(msg.sender, spender, tokens);
    return true;

But the audit says I should use this below:

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

After reading the ECR-20 API it says this is a solution:

function approve(
  address _spender,
  uint256 _currentValue,
  uint256 _value)
returns (bool success)

What is the difference between the first 2?
Is this just a difference in Solidity langauge 4.5 vs. 5.0?

I noticed the EIP says that these issues should be handled by the interfece vs an actual check code.

Your thoughts?


texts:
Facing a weird issue on geth console on my private network.
So, I was trying to unlock an account so that my web3 can access it.
As soon as I unlocked, all my ethers just vanished in seconds.. I could see some Submitted Transactions. However a scan over my explorer didn't yield any result. Any idea or someone faced a similar situation ?


texts: This buying function in the tutorial never pays the contract, does it?

texts:
It doesn't look like the contract is ever paid here. Is this a miscode or am I reading it incorrectly? Where does the exchange of ether occur?

function buy() payable returns (uint amount){
    amount = msg.value / buyPrice;            // calculates the amount of token
    if (balanceOf[this] < amount) throw;      // checks if it has enough token to sell
    balanceOf[msg.sender] += amount;          // adds the amount of token to buyer's balance
    balanceOf[this] -= amount;                // subtracts the amount of token from seller's balance
    Transfer(this, msg.sender, amount);       // execute an event reflecting the change
    return amount;                            // ends function and returns
}


texts: Import contracts, compiling and deployment

texts:
quick question.

I have a set of contracts A,B,C.

A contains import 'B' and import 'C'.

Should I just compile A and then deploy it on the blockchain for the functions in B and C to be implemented or should I compile A,B,C and deploy A,B,C ?

Thanks!


texts: I want to create an etc 20 token that can be used to rais funds for projects and later distributes the revenue from the project to people who bought the token. How to do that ?


texts: Crowdsales: non-mintable tokens vs mintable tokens (with hard cap)

texts:
There are crowdsales where the initial supply is set upon deployment which is set to the defined total supply (so that number is as many tokens that there will be) and when someone buys tokens during the crowdsale they get transferred.

On the other hand, we have crowdsales where the tokens are mintable and the initial supply is set to 0. So, when someone buys tokens, they are minted and then transferred while the total supply is increased.
There's also (most times) a hard cap to set the maximum amount of tokens that will exist.
When the crowdsale ends, if the hard cap was not met, tokens will be minted up to the hard cap and be transferred to the team.

So, in both cases the end result is the same. Why use mintable tokens and add extra complexity to the code if (as far as I can tell) the end result is the same? (As long, of course, that there is a hard cap and that tokens can not be minted after the crowdsale ended)

//Update:

Here's an example to illustrate my point: https://github.com/bitclave/crowdsale/blob/057357fecbcc00c9a6cf96831d71d94fb7a13f03/contracts/CATCrowdsale.sol

There's a hard cap.
If the hard cap is not met, the missing tokens are minted and assigned to the crowdsale owner.
Minting is only available during crowdsale. When the crowdsale is finished, a flag is set so no more tokens can be minted, and there's no way to enable minting again.
There's no functions to burn tokens.

So, unless I'm missing something, in this case, for example, wouldn't it have been the same to make the token non-mintable with the same total supply as the hard cap? Or am I missing something?


texts:
So as far as I understand, Proof-of-stake works by all nodes voting on what they think the correct next block should be and then recieving a small reward out of thin air if they guess correctly and a small penalty if they guess incorrectly. Thereby all nodes are incentivized to believe the same thing.

This then means that there is no useless incrementing-a-nonce-and-trying-to-hash-and-come-up-with-a-value-below-some-limit puzzle, which means it should greatly reduce the work of processing blocks and save miners a lot of cost, which in turn means they can offer a lower gas price.

So what is "mining" in this context? Is it just running a load of transactions, putting a block together, and then convincing everyone else your candidate is the one they should vote for? Is there still a system where the miner of a new block gets a big payout as in bitcoin, or does everyone who votes for the right thing split the payout?

Buterin wrote about all this nearly two years ago. Has it made it in to the protocol yet?


texts: testrpc requires restart after each test

texts:
I'm testing Open Zepplins crowdsale code: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/test/CappedCrowdsale.test.js

After I compile and run truffle test it works fine, but then the second time I run truffle test (even without changing the code at all) I get this error:

Error: VM Exception while processing transaction: revert
at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43303:16)

I can resolve the problem by shutting down testrpc and truffle migrate --reset again, but its pretty annoying to have to do that before each test.

Any idea how I can fix this?
Thanks!


texts: Could someone explain to me the use of the FastRawTransactionManager class?

texts:
int pollingInterval = 3000;
FastRawTransactionManager fastRawTxMgr = new FastRawTransactionManager(web3j, credentials, new PollingTransactionReceiptProcessor(web3j, pollingInterval, 40));

From what I understood of the code is that those 3000 seconds are the polling intervals of the transaction generated, but I have my question for what is the number 40.


texts: Sending a transaction to the smart contract and execute its method

texts:
Suppose I am doing like this

myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, transactionHash){
    ...
});

Do I need to unlock the account 0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe to send the transaction ?
If yes then what is the process to unlock this account. with Web3 1.0
I found web3.personal.unlockAccount on a topic but didn't find any documentation about this in here


texts: I have a private network and am looking to disable Whisper's required Proof of Work when sending a message. This issue talks about how the source prevents this, but I'm wondering if there's another way aside from forking the code and allowing it. Is there a way to do it?


texts: what will other nodes exactly do in relaying transaction process?

texts:
this question confused me long time.
What will other nodes exactly do in relaying transaction process? I read some questions/answers, I know they will follow ethereum protocol, but what would this protocols do? for example it invoke a contract function in a transaction and change the contract state, does other nodes need run the contract and compare with anything got from the transaction ?
In bitcoin, I know other nodes will check the transaction inputs and output and so on. And If they got new block, they also will do similiar sanity check. But I don't know in ethereum, bcz it adds contract.
Or please could anyone point me where I can find answers in the source code.
Thank you.


texts: How to unmarshall an uint returned from a solidity contract?

texts:
I've compiled and deployed the following trivial smart contract:

pragma solidity ^0.4.7;
/// Trivial counter contract. Provides an external function which increments the counter
/// and replies the current value.
contract BasicCounter {
    uint private counter = 0;
    function incrementAndGet() external returns (uint) {
        counter++;
        return counter;
    }
}

In the node REPL I can instantiate a handle for the deployed smart contract:

let instance =
    web3.eth.contract(/* the contract abi */))
        .at(/* the contract address  */);

Using the instance, I can invoke the external function incrementAndGet:

let ret = instance.incrementAndGet();

The return value ret is a hex string, i.e.

0xa768b61d2892dda6495b6b1529e4c81252f333f4ca4ffa18ea7408580366292d

If I convert it to a BigNumberusing web3, i.e.

let value = web3.toBigNumber(ret);
console.log(`: <${value.toString(10)}>`)

I get the following value

current counter value: <75721254712088916818789556586747754611065627738232115122133311013811340585261>

This looks strange. The first invocation of incrementAndGet should rather return something like 00000......00001.

Any hint what is going wrong here? How to correctly unmarshal an uint value returned from a external function in a smart contract?


texts: Is the whole ethereum's source code stored in its clients?

texts:
I would like to edit the ethereum's source code and add it some improvements. I could find only ethereum clients source code (in java,cpp, python and go). is the whole ethereum's code stored in its clients?

Does it enable to create private ethereum network?


texts:
I have created this contract and sent ETH to it. Now I want to send the ETH back to my main account, I have these options:

removeOwner
isOwnder
m_numOwners
m_lastDay
version
resetSpentToday
m_spentToday
addOwner
m_required
confirm
setDailyLimit
execute
revoke
changeRequirements
hasConfirmed
kill
changeOwner
m_dailyLimit

Which option do I use to transfer credit?


texts:
Trying to understand how the following example - from Compound Finance - works, in case you are trying to store something of order 1x10^19.
From GitHub - https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol
“Exp is a struct which stores decimals with a fixed precision of 18 decimal places.

    Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:

    `Exp({mantissa: 5100000000000000000})`.”

By the logic above, does this mean that if you were trying to store, say, 10 or above, you wouldn’t be able to put it in Exp({mantissa}), since that’d have a length of 19?


texts: “state channel” v.s “micro-payment channel” : are they the same?

texts:
We use "micro-payment channels" such as "Bitcoin Lightning Network" or "Duplex Micro-Payment Channels" for saving transaction fee, accelerating payments, supporting better micro-payment and scaling blockchain.

Is there any difference between "state channel" v.s "micro-payment channel"? and if so, what are differences?


texts: "Migrations" hit an invalid opcode while deploying on deploy Migrations.sol with Truffle

texts:
An error occurs when truffle migrate try to deploy Migrations.sol contract, i don't understand why

pragma solidity >=0.4.21 <0.6.0;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

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

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

Migrations.sol

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

   Deploying 'Migrations'
   ----------------------
Error: Error: Error:  *** Deployment Failed ***

"Migrations" hit an invalid opcode while deploying. Try:
   * Verifying that your constructor params satisfy all assert conditions.
   * Verifying your constructor code doesn't access an array out of bounds.
   * Adding reason strings to your assert statements.

    at Object.run (C:\Users\Sim'S\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-migrate\index.js:92:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.0.21 (core: 5.0.21)
Node v10.15.3

Error message


texts: How to know weather ETH or some token like USDT is transfered in smart contract transaction


texts:
Is it possible to pay the miner who mines the block that executes a certain function? As in, it would coded into the function itself? If so, can it be done from Solidity or just byte code?

Bitcoin has a similar functionality when the output values are less than the input values.

It might sound strange to want to do, but I am considering a Dapp where I need incentive compatibility against miners who might not want to include certain functions in their block.


texts: How do I tell what account for Truffle to use when testing contracts?

texts:
I'm using Truffle together with Parity to test contracts.

How do I tell truffle what account to use with Parity when testing contracts? I have a total of 3 accounts in Parity currently.

The command I'm currently using is as follows:

truffle test --network kovan


texts: What's the simplest way to implement multisig ownership in Solidity?

texts: I have a list of owners in a smart contract and would like to require a minimum number of their approvals in order to execute some administrative functions. What's the simplest way to implement it? I am between using Gnosis Safe + Ownable but I would rather find a simpler and cheaper (in terms of gas costs) solution (preferable already audited). Do you know of any examples? Thanks!


texts: How can I deploy a contract with reference to a library contract without using a graphical user interface like Browser Solidity?

texts:
I am using Solidity Browser to deploy a contract due to from Library contract method failing #2831 issue. On this following answer https://ethereum.stackexchange.com/a/9181/4575 I have guided to use Solidity Browser as (Please note that this solution works.):

I connected Solidity Browser to my local private node by clicking on
the block icon and selecting Web3 Provider. I then clicked on Create
to deploy the contract above to the blockchain.

I am using Solidity Browser on my server, and it is difficult to do this process using a graphical user interface, due to my ssh connection.
[Q] Is it possible to deploy a contract without using graphical user interface via Solidity Browser? or is there any other solution?
Thank you for your valuable time and help.


texts: How do i reclaim OWNERSHIP of an ENS domain

texts:
new ENS user here.  I have one problem and one question.

Problem:
I transferred ownership of my ENS domain to a CROWDSALE contract address, by using setOwner().  The goal was to use "myname-eth" to resolve to the crowdsale address.  However, that didn't work.  The old address of which the original ENS domain was bought still resolved to "myname-eth".  So my question is....  how can I change ownership back to the original address?  When I try to do that with myetherwallet, it says "bad jump instruction" and fails.

Question:  How can I change the address which "myname-eth" resolves to?  I want to change that address to a crowdsale address.  So currently it points to 0x12345.  I want to change it to 0x55555, for example.

I'm currently stuck and have scourged the net to find answers but nothing that has helped so far.


texts: web3j version 4.5.16 is not generating payable function properly

texts:
I am using web3j 4.5.16 version to generate my wrapper.

For a payable function it is generating the following.

// With out input argument to enter weiValue

public RemoteFunctionCall<TransactionReceipt> enter() {
        final Function function = new Function(
                FUNC_ENTER,
                Arrays.<Type>asList(),
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }

If I change this to the following. I am able to execute this function with input ether.

public RemoteFunctionCall<TransactionReceipt> enter(BigInteger weiValue) {
    final Function function = new Function(
            FUNC_ENTER,
            Arrays.<Type>asList(),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function, weiValue);
}

Same web3 version was able to generate proper wrapper class with solidity version i.e. ^0.4.17.


texts: Learing to work with ethereum ERC-20 - How to issue new tokens? How to destroy tokens? How to split tokens?

texts:
I am learning to write ERC-20 contracts and I try to emulate common stocks.
I would like some tips on how to implement it.
How to issue new tokens? - Emulate issuing new stocks.
How to destroy tokens? - Emulate stock buyback.
How to split tokens? - Emulate stock split (every token becomes multiple of original tokens).


texts: Metamask injects one account in web3, but calls contracts using another account

texts:
Building a React app, MetaMask injects web3, I get accounts[0] from getAccounts(), then pass it to my contract functions together with other parameters. I want my modifiers to lock incoming function calls based on comparisons between 1) msg.sender 2) the account MetaMask injected in my web3 and 3) contract owner.

When debugging an uncaught "MetaMask - RPC Error: Internal JSON-RPC error." I noticed my checks to be extremely valuable: 1) and 2) did not match. Metamask is injecting the account I selected (Account 3 in the picture below) in web3, but calls the following Solidity function (modified for debugging) using Account 1 (the first one I setup in MetaMask, see picture below, and first one in Ganache) as the msg.sender. If I console.log the msg.sender and web3 addresses in JS I obtain two different values.

ethAddress: "0x478205E668883bba86cCa3eFB8C489A7c4d27cE7"
sender: "0x81eCa3fA3727BdC7B8774c26B57152bb62C0834D"

This behaviour could lead to unpredictable things if left uncontrolled. Any clue why? Is it a bug?

    function findMe(address _ethAddress) public view returns(address sender,address ethAddress) { //bool foundMe
            return (
                msg.sender,
                _ethAddress
            );
    //        require(msg.sender == _ethAddress);
    //        if (users[_ethAddress].found) {
    //            return true;
    //        } else {
    //            return false;
    //        }
        }


texts: Transaction has been reverted by EVM (Matic Mumbai Testnet)


texts: Official data about synchronization time

texts:
Are there in the literature or from the Ethereum community/foundation any official benchmark about geth (or any other client, e.g. parity) initial synchronization time (with both fast and normal sync)?

UPDATE

I noticed that this question contain some interesting data, but the geth versions are really old. I would like to have data for geth version > 1.8.x

UPDATE

The official Ethereum blog contains some benchmark on time needed for geth fast synchronization with geth 1.8.0 and geth 1.7.0


texts: Send tokens from ethereum address programmatically

texts:
I want to create a service to send tokens from different wallets. I already created the ethereum transactions, but I don't get tokens yet.

It seems I need the ABI, but I would like to avoid using it. I've seen that myetherwallet allows you to send tokens without asking anything other than the destination and the gas pretty much.

Some questions:

Should I use the private key of my ethereum address to sign this transaction? or its another private key like the contract one

If myetherwallet allows me to send tokens from one address to another, how come I can't do the same programatically? What am I missing?

Thank you


texts:
In the geth console contract compiled fine, but it giving an error like this when ever I am going to deploy, is there any dependencies there?

var greeterContract = web3.eth.contract(greeterCompiled.greeter.info.abiDefinition);

  Type Error: Cannot access member ‘info’ of undefined
   at :1:41

even though I changed greeterContract name also, I am getting same error like Type error: ...<>:1:23

  var greeter = greeterContract.new(_greeting,{from:web3.eth.accounts[0],data: greeterCompiled[":greeter"].code, gas: 1000000}, function(e, contract) {if (!e) {if (!contract.address) { console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");} else { console.log("Contract mined! Address: " + contract.address); console.log(contract);} }})

Type Error: Type Error: Cannot access member ‘new’ of undefined
 at :1:15


texts: Is it safe to assume that a smart contract can hold Ether for years if the withdrawal is not triggered?

texts:
Given that ethereum continues to run for few years, is it safe to assume that the smart contract will hold the ether that was deposited into it for years until its triggered to transfer/withdraw the amount ?
Also, Can it be triggered after a few years to withdraw the amount of ethers it holds ?


texts:
I have a Json Web Key that contains public key information and I'd like to derive ethereum address from it. I understand the process of getting the address by hashing using Keccak from the public key byte array, but I don't know how to obtain this byte array. My scenario is, generate EC key using Azure Key Vault API, retrieve the key (JWK format) and then find the address. The JWK has the following format.

{
  "kid": "https: //mykeyvault.vault.azure.net/keys/testeckey/8bad08aaae514efe981eaab4e590778d",
  "kty": "EC",
  "key_ops": [
    "sign",
    "verify"
  ],
  "crv": "P-256",
  "x": "YooqHyo7hlmcrBs5lDSSUsB0axzvorjxzNl6DBZLUf0",
  "y": "NM-JrV6NTbUgILY_sBm5VgYxt1zYccCOCFtSDicSfWM"
}

I'm using the Azure .NET SDK and I have the option to use Bouncy Castle for .NET or any JS library, since project can also run in a Node.js environment. How can I obtain the byte array of the public key?
Thank you


texts: How do I know how "confirmed" the result of calling getBalance API is?

texts:
Documentation for getBalance doesn't seem very clear to me. I would like to know the balance but want to know how many confirmations does the balance returned have.

I was assuming that passing the "pending" parameter would include the balance from all transactions (even the ones with no confirmations or very few), but if this is true, how to do the opposite? I want to know the balance with a high number of confirmations, and the alternative params to pass (instead of "pending") are "latest" and "earliest", whose documented meaning doesn't seem clear to me:

"earliest" - for the earliest/genesis block
"latest" - for the latest mined block
"pending" - for the pending state/transactions

Any ideas? Thanks!


texts: Make a GET Request over the Binance Smart Chain with a Chainlink Oracle

texts:
I am trying to call to an BSC Oracle to make an HTTP request according this ChainLink example. In my example I am goin to use the BSC mainnet 56 and a other JobID obviously:
My steps:

I created the contract with this zenAPIs get request contract and jobID over the BSC Mainnet:

I deployed the contract to the BSC Mainnet. There was an error, but the contract seems created.

The BSCScan transaction.

I funded the contract with ERC677 LINK and the BSC accepted it. (I used this Chainlink official swap for change the Binance sent links to my wallet: https://pegswap.surge.sh/)

I called the requestEthereumPrice() function and the BSC return OK.

I get the "currentPrice" var and REMIX return this error:

"Failed to decode output: Error: data out-of-bounds (length=0, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7)"
The contract:
/**
 * Network: Binance Smart Chain - Mainnet
 * ZenApis. Job: HTTP get:
 * https://market.link/nodes/fd5a3998-75bb-4705-9f34-b51f02ed5f0e?network=56
 * https://market.link/jobs/5ddd8a96-8840-4b55-9163-f07674c8c004/spec?network=56
 * Oracle: 0x074715cc07fC0Df9c617F22971Fb2Ff1b1f57278
 * Job ID: c734c40b377544f08a7324f36bda4940 //https://market.link/jobs/5ddd8a96-8840-4b55-9163-f07674c8c004/spec?network=56
 * Fee: 0.02 LINK
 * LINK Token Address: 0x404460c6a5ede2d891e8297795264fde62adbb75
 *
 * Video tutorial: https://www.youtube.com/watch?v=AtHp7me2Yks
 */

// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.6.0;

import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";

contract ChainlinkExample is ChainlinkClient {
  // Stores the answer from the Chainlink oracle
  uint256 public currentPrice;
  address public owner;

  address ORACLE_ADDRESS = 0x074715cc07fC0Df9c617F22971Fb2Ff1b1f57278;
  string constant JOBID = "c734c40b377544f08a7324f36bda4940";

  uint256 constant private ORACLE_PAYMENT = 20000000000000000;// 16 0s = 0.02 LINK

  constructor() public {
    // Set the address for the LINK token for the network
    setPublicChainlinkToken();
    owner = msg.sender;
  }

  // Creates a Chainlink request with the uint256 multiplier job
  function requestEthereumPrice() public onlyOwner{
    Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOBID), address(this), this.fulfill.selector);
    req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");//{"USD":1797.12}
    req.add("path", "USD");
    req.addInt("times", 100);
    sendChainlinkRequestTo(ORACLE_ADDRESS, req, ORACLE_PAYMENT);
  }

  // fulfill receives a uint256 data type
  function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { // Use recordChainlinkFulfillment to ensure only the requesting oracle can fulfill
    currentPrice = _price;
  }

  // cancelRequest allows the owner to cancel an unfulfilled request
  function cancelRequest(bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration) public onlyOwner {
    cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
  }

  // withdrawLink allows the owner to withdraw any extra LINK on the contract
  function withdrawLink() public onlyOwner{
    LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
    require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
  }

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

   // A helper funciton to make the string a bytes32
  function stringToBytes32(string memory source) private pure returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
      return 0x0;
    }
    assembly { // solhint-disable-line no-inline-assembly
      result := mload(add(source, 32))
    }
  }
}


texts: Upgradability Proxy ADMIN_SLOT assembly sstore does not update

texts:
I'm currently playing around with Proxy Upgradability, and noticed the use of assembly in terms of the new upgraded contract and the slot assigned.  Real implementation can be seen here.

I have broken this implementation down to understand what is happening:

pragma solidity ^0.5.0;

contract Base {

bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;

function _setImplementation(address newImplementation) public {
   bytes32 slot = IMPLEMENTATION_SLOT;

   assembly {
     sstore(slot, newImplementation)
   }
}

function _implementation() public view returns (address impl) {
   bytes32 slot = IMPLEMENTATION_SLOT;
   assembly {
     impl := sload(slot)
   }
}

function getSlot() public view returns(bytes32) {
    return IMPLEMENTATION_SLOT;
}
}

Then created tests to see the results, and see what is modified etc...

const Base = artifacts.require("Base")

contract('Base', function(account) {

beforeEach(async function () {
    this.base = await Base.new();
})
describe('...', function () {
    describe('...', function () {
        it('check slot', async function () {
            console.log(await this.base.getSlot());
        })

        it('check slot', async function () {
            console.log(await this.base._implementation());
        })

        it('change slot', async function () {
            console.log(account[0]);
            await this.base._setImplementation(account[0]);
        })

        it('check slot', async function () {
            console.log(await this.base.getSlot());
        })

        it('check slot', async function () {
            console.log(await this.base._implementation());
        })

    })
})
})

Which gives the result:

0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3
    ✓ check slot
0x0000000000000000000000000000000000000000
    ✓ check slot
0x627306090abaB3A6e1400e9345bC60c78a8BEf57
    ✓ change slot (69ms)
0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3
    ✓ check slot
0x0000000000000000000000000000000000000000
    ✓ check slot

Why does the slot variable not change, and if that is not meant to change, why does ADMIN_SLOT not change either?


texts: How to connect a web site to a geth node?

texts:
Before the DApp-browser Mist was available, this web3 library seems the way to go on building a bridge from contract to a frontend (web site).

But, I cannot get the very basic examples to work.

These sources lack a few major points:

What is the exact command to start geth to run the examples? I have used:

geth --rpc console 2

while mining etc.
This example has the line:

web3.setProvider(new web3.providers.HttpProvider());

Should it be localhost?

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

Is there anyway to hide web3.setProvider and other JavaScript code from the page source viewable for the user? If the geth node address is public, that could be a security problem.

Maybe I'm asking obvious questions here, but it shouldn't be too much trouble to add at least the geth starting argument to the tutorials. The best case scenario would be to have step by step guide with no assumptions left blank.


texts: Custom token display in case of geth testnet

texts:
From this, i found that
To add a token to watch, go to the contracts page and then click "Watch Token". A pop-up will appear and you only need to paste the contract address. The token name, symbol and decimal number should be automatically filled. How can i perform same thing in case of testnet. I mean how will a testnet user will see the tokens he possess.I am using GETH client and web3 to interact with node and pass related data to UI .


texts: How to estimate my contract code size? it is too big to deploy now

texts:
I think my contract is too big to deploy, because I got
Error encountered, bailing. Network state unknown. Review successful transactions manually. Error: oversized data when I am trying to deploy on ropsten network. (but it works fine on testrpc, because I set a very large number of gas limit)

So I want to estimate my code size to be deployed in truffle test. I know how to estimate gas to run a function in contract using estimateGas(), but I don't know how to estimate gas(or code size?).


texts: I am trying to connect to https://ropsten.infura.io/my key here with web3.js. I can read stuff off the block chain but cant write to it and have no idea why. Any help?


texts: Solidity: Function with same name but different parameter possible?

texts:
Will the contract auto detect wether I am calling the function with or without parameter?

pragma solidity 0.4.25;

contract A{
    function test() public{
        //do something
    }

    function test(uint256 param) public{
        //do something else
    }
}


texts:
I am trying to accomplish a role based access control withing the smart contract.

Often we see something like this to protect function within the smart contract:

 require(tx.origin == owner);

So make this check role based, I have thought of two options. What do you think, which one is better? Or do you know any other approach?

For every transaction contains a token with the users role. Similar how JWT works.
One dedicted smart contract is responsible for the roles. For every type of role, a list of addresses is stored. It provides one public function e.g. isAdmin(address adminAddress) return (bool)

What do you think?

Thanks a lot


texts: Why is there a CALL instruction in this contract?

texts:
This is a code snippet from a real contract. I wonder why the compiled code (can be obtained online from https://chriseth.github.io/browser-solidity) has several CALL instructions, although the contract does not make any call?

contract ReleaseOracle {
  // Votes is an internal data structure to count votes on a specific proposal
  struct Votes {
    address[] pass; // List of signers voting to pass a proposal
    address[] fail; // List of signers voting to fail a proposal
  }

  // Version is the version details of a particular Geth release
  struct Version {
    uint32  major;  // Major version component of the release
    uint32  minor;  // Minor version component of the release
    uint32  patch;  // Patch version component of the release
    bytes20 commit; // Git SHA1 commit hash of the release

    uint64  time;  // Timestamp of the release approval
    Votes   votes; // Votes that passed this release
  }

  Version   verProp;  // Currently proposed release being voted on
  Version[] releases; // All the positively voted releases

  // proposedVersion retrieves the semantic version, commit hash and the current
  // votes for the next proposed release.
  function proposedVersion() constant returns (uint32 major, uint32 minor, uint32 patch, bytes20 commit, address[] pass, address[] fail) {
    return (verProp.major, verProp.minor, verProp.patch, verProp.commit, verProp.votes.pass, verProp.votes.fail);
  }
}


texts: How to transfer tokens from Contract to Contract Creator?

texts:
FTF I'm a noob in Solidity! Has been created a contract sending the initial supply to the contract address. I would like to know if is it possible to send the tokens from the contract to the address (owner of the contract)?

Contract
https://ropsten.etherscan.io/address/0xec7b8dafd5494654a2ce801c7abe01bb6d3d4557#code

Contract Balance
https://ropsten.etherscan.io/token/0xec7b8dafd5494654a2ce801c7abe01bb6d3d4557#balances


texts: Where is ethereum and etc stored on my desktop when using Jaxx wallet?

texts:
There was an error when opening my jaxx wallet for windows 10 desptop (containing eth and etc), and my computer suggested to reinstall the application. Without thinking, I deleted the jaxx files (but not the app data), and reinstalled Jaxx (this time as an extention on chrome). I had to insert my back up phrase, but I did not save it.
I moved all Jaxx document from my recycle bin back to my documents. But, when opening the program, it gives two errors stating 'note.dll' and 'ffmpeg.dll' are missing on my pc.

How can I restore my coins? I think it can be done by either fixing the errors stated above, or by doing something (but what?) with the file where my jaxx wallet data is saved: C:\Users\\AppData\Roaming\Jaxx\Local Storage with the file name: file__0.localstorage

Does somebody knows how I can gain acces again to my Jaxx wallet and thus get back my ethereum and ethereum classic?


texts: How to deploy a solidity contract to the blockchain. myContract.new is not a function

texts:
I have a contract that compiles in browser solidity and solc. Using either the auto-generated deployment code in browser solidity or my own npm version, I end up with the error

  "myContract.new" is not a function.

This, as  I understood it, is a function intrinsic to the Contract type, since it's required for deployment. When I do console.log(myContract) I get

  [Function: bound Contract].

When I try to deploy,there is an extremely unhelpful error message / random code output as well:

 node_modules/solc/soljson.js:1 (function (exports, require, module,
 __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var
 key i
 Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var
 ENVIRONMENT_IS_WEB=typeof window==="object";var
 ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var
 ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof
 require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var
 ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function
 print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function
 printErr(x){process["stderr"].write(x+"\n")};var
 nodeFS=require("fs");var
 nodePath=require("path");Module["read"]=function
 read(filename,binary){filename=nodePath["normalize"](filename);var
 ret=nodeFS["readFileSync"](filename);if(!re


texts: Can not deploy source code (Flatter Solidity file which I copy from Etherscan) on Remix ! Any helps?

texts:
[The IPFS link to see source code] (http://dweb.link/ipfs/QmVcFrLDPrEY8sveEdXnib6etMtes8z12GsNo21vbfdtiv)
The error I got when try to deploy SAFEMARS contract : creation of SAFEMARS errored: Cannot convert undefined or null to object
Solidity version :  ^0.6.12


texts: remix not showing me any error but output 0

texts:
pragma solidity ^0.4.19;

    contract Bank{
    uint private value;

    function Bank(uint amount){
        value = amount;
    }
    function deposit(uint amount){
        value += amount;
    }
    function withdraw(uint amount){
        value -= amount;
    }
    function balance() returns (uint){
        return value;
    }
}

contract MyFirstContract is Bank(10)
{
    string private name;
    uint private age;

    function setName(string newName){
        name = newName;
    }
    function getName()returns(string){
        return name;
    }
    function setAge(uint newAge){
        age = newAge;
    }
    function getAge() returns (uint) {
        return age;
    }
}

I am executing my contract it compiles successfully. I have passed default value inside my bank constructor and then i get the balance but it is showing me blank.

Thanks in advance.


texts: how come the ethereum I bought with my bitcoins aren't appearing?

texts:
I am a complete newb,

I sent 6 ethereum worth of bitcoin to my etherbase wallet, I know they were sent correctly but they do not appear in my etherbase wallet. Where might they be? How do I get them to show up in my wallet? I had the bitcoins I tried to import them to my etheruem wallet in a popup window during the setup, within the program.


texts: Can I access last mined block if my node is not there yet?

texts:
This might be a stupid question, but I'll ask anyway...

I'm currently connected to Ropsten and when I execute eth.blockNumber it says 1853682 (I'm like 300000 blocks away from current last mined block).

Is there any way to access the information in a block that's still not downloaded to my copy of the blockchain? I think it's plain impossible, but maybe there's a way...

Edit: I want to access the last node programatically from my node, not just query the contents of that last block on an external website (maybe etherscan has an API to make such queries?...)

Thanks so much in advance! :)


texts: Unable to interface the contract while running test.js and how to get the abi while compiling using solc?

texts:
Solidity Contract: index.sol

pragma solidity ^0.5.0;

contract Inbox{
    string public message;

constructor(string memory IntialMessage) public{
    message = IntialMessage;
}

function setMessage(string memory newMessage) public{
    message = newMessage;
}
}

compile.js

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const inboxPath = path.resolve(__dirname,"contracts","index.sol");
const source = fs.readFileSync(inboxPath,"utf8");

var input = {
language: 'Solidity',
sources: {
    'index.sol': {
        content: source
    }
},
settings: {
    outputSelection: {
        '*': {
            '*': [ '*' ]
        }
    }
}
}

const buildPath = path.resolve(__dirname, 'build');
output=JSON.parse(solc.compile(JSON.stringify(input)));

if(output.errors) {
output.errors.forEach(err => {
    console.log(err.formattedMessage);
});
} else {
const contracts = output.contracts["index.sol"];
console.log("Bytecode Of the Contracts:\n");
for (let contractName in contracts) {
    const contract = contracts[contractName];
    module.exports=
          {"abi":contract.abi,"bytecode":contract.evm.bytecode.object};
    fs.writeFileSync(path.resolve(buildPath, `${contractName}.json`),
    JSON.stringify(contract.abi, null, 2), 'utf8');
    console.log(contractName+": "+contract.evm.bytecode.object+"\n");
}
}

index.test.js:

const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');  //Web3 is a constructor of the web3 module

const web3 = new Web3(ganache.provider()); //web3 is an instance of the web3 module
const {abi, bytecode} = require('../compile');
const inboxBuild = require('../build/Inbox.json');
const abiObj = require('solc/abi');

let newABI;
newABI = abiObj.update('0.3.6',inboxBuild);

let accounts;
let inbox;

beforeEach(async () => {
    accounts = await web3.eth.getAccounts();

    inbox = await new web3.eth.Contract(newABI)
        .deploy({data:bytecode,arguments:["Hi there!"]})
        .send({from:accounts[0], gas: '1000000'});
});

describe("Inbox",() => {
    it("deploys a contract", () => {
        console.log(inbox);
    });
});

I am getting the following error:

Inbox
    1) "before each" hook for "deploys a contract"

  0 passing (2s)
  1 failing

  1) "before each" hook for "deploys a contract":
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! inbox@1.0.0 test: `mocha`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the inbox@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Aashutosh Singh\AppData\Roaming\npm-cache\_logs\2019-09-24T04_11_07_715Z-debug.log

Thank you to whoever tries to solve the problem.


texts:
Is it possible to put a smart contract "behind" a restful API, i.e. expose my contract functions and properties through restuful API where I can make RPC to it?
Or does it work as an API already, but instead of GET/POST requests, there are .CALL()/.SEND() requests?


texts: Deploying Solidity Contract Using Web GUI and web3

texts: Any guide or step by step Tutorial for deploying a solidity smart using a GUI and accessing the meta mask account ? Please Help


texts:
related to question Best practices to solve the problem of a contract that is too large?, I am facing similar issue (contract too large to be deployed, compare to gasLimit of the blockchain) and before I launch a refactoring of my code I am seeking advise on the possible approach.

Here is my current design:

contract A {
    // some state variables but not so many
    function A(some params) {
       // initialize the contract
    }
    function newT(some params) {
       // create a new T instance and store it in A's state variable
    }
    // several other functions with business logic
}

contract T {
    // some state variables but not so many
    function T(A a, some params) {
       // test that it is only called by A, checking msg.sender
       // initialize the contract
    }
    function newU(some params) {
       // create a new U instance and store it in T's state variable
    }
    // some business logic as functions
}

contract U {
    // some state variables but not so many
    function U(T t, some params) {
       // test that it is only called by T, checking msg.sender
       // initialize the contract
    }
    // some business logic as functions
}

When creating the fist instance of A, the code is massive. Am I correct in understanding that the code of A will include the full code of A, T and U (so it is able to create new instance of T, respectively U)?

If so, does it mean that I am not using a valid factory pattern for Ethereum as the factory must contain the full code of its instantiated classes ?

What is therefore the best factory pattern when we have real business contract that do embed real business logic? (and still I am in a proof of concept at this stage :-( )


texts:
Just wrote and tested the following on http://remix.ethereum.org

Same happens on Ropsten network.

If I run without sending any value it works, but I can't deploy the Test contract if I put any value > 0 to send because it reverts, but why?

pragma solidity ^0.5.0;

contract Test
{
    uint public m_ReceivedWei;

    function()
        external payable
    {
        m_ReceivedWei += msg.value;
    }

}


texts:
I would like to write a simple Serpent function that involves string comparison, but even the simplest example I can think of does not work as I would like. This post gets me part of the way . . .

Here is an example (using an IDE like PyCharm, so no carats >) to compare two strings as input arguments:

import serpent
from ethereum import tester as t, abi

str_compare_code = '''
# What I want to do, check equality of strings
def str_compare(in_a:str, in_b:str):
    return(in_a == in_b)

# To show conversion of short strings to numbers in Serpent
def str_number(in:str):
    return(in)

# To make even clearer what is funny
def str_diff(in_a:str, in_b:str):
return(in_a != in_b)
'''

# Initialize tester and compile Serpent code
s = t.state()
c = s.abi_contract(str_compare_code)

I test the contract and get

In[35]: c.str_compare("a", "a")

('b1', 1000000000000000000000000L)
('b2', 999999999999999996858408L)
('b3', 1000000000000000000000000L, 1)
Out[35]: 0

I know that short strings get converted to ints, as seen here

In[36]: c.str_number("a")

('b1', 1000000000000000000000000L)
('b2', 999999999999999996858408L)
('b3', 1000000000000000000000000L, 1)
Out[36]: 352

To put salt in my wounds . . .

In[37]: c.str_diff("a", "a")

('b1', 1000000000000000000000000L)
('b2', 999999999999999996858408L)
('b3', 1000000000000000000000000L, 1)
Out[37]: 1

Is the problem how I handle the input strings in the function body? Thank you for any and all tips!


texts: "The field value must not have more 32 bytes" trying to create transaction from contract method call

texts:
I've already interacted with this contract instance using a local Geth node with my wallet loaded/unlocked, so I know there's nothing wrong with the contract.

Now I'm using an Infura RPC node instead to interact with contracts and therefore must sign transactions locally. So:

Get contract instance from ABI and address
Encode contract method call to raw ABI value
Create transaction to contract address with raw ABI value
Sign transaction
Broadcast signed transaction

Using web3js 1.0.0, docs and examples would suggest this:

const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
var web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/token...'));

var from_addr = "0xdeadbeef..."; // my wallet address
var privateKey = "deadbeef..."; // my wallet private key
var contract_abi = [...]; // Compiler output from Remix
var contract_addr = "0xdeadbeef..."; // I already deployed this contract using Remix

// get the contract instance
var contract = new web3.eth.Contract(contract_abi, contract_addr)

// call `myMethod` method on contract instance
var method_call_abi = contract.methods.myMethod(arg1, arg2, ...).encodeABI();

web3.eth.getTransactionCount(from_addr).then(txCount => { // get tx count of my wallet...

    // build transaction dict
    const txData = {
      nonce: web3.utils.toHex(txCount),
      gasLimit: web3.utils.toHex(25000),
      gasPrice: web3.utils.toHex(10e8), // 1 Gwei
      to: contract_addr,
      from: from_addr,
      value: method_call_abi,
    };

    // serialize and sign transaction
    var transaction = new Tx(txData); // ERROR IS HERE
    var privateKeyBuf = new Buffer(privateKey, 'hex');
    transaction.sign(privateKeyBuf);
    var serializedTx = transaction.serialize().toString('hex');

    // finally send
    web3.eth.sendSignedTransaction('0x' + serializedTx, cb).then(console.log);

});

And here's what I get:

Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> (node:23512) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The field value must not have more 32 bytes
    at Transaction.setter [as value] (/mnt/ethereum/ubuntu/node_modules/ethereumjs-util/dist/index.js:633:9)
    at /mnt/ethereum/ubuntu/node_modules/ethereumjs-util/dist/index.js:685:63
    at Array.forEach (<anonymous>)
    at Object.exports.defineProperties (/mnt/ethereum/ubuntu/node_modules/ethereumjs-util/dist/index.js:684:14)
    at new Transaction (/mnt/ethereum/ubuntu/node_modules/ethereumjs-tx/es5/index.js:112:13)
    at web3.eth.getTransactionCount.then.txCount (repl:13:23)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)

Stepping through, this error happens on the var transaction = new Tx(txData); line. What am I doing wrong here?

I also tried creating the transaction on remix.ethereum.org. The data it gives me is the exact same as what encodeABI() produces, so it's correct.


texts:
My question is very simple... I've watched some videos and read articles, but couldn't figure this.
It's said that on the internet

If the block has been finalized, it can't be reverted/changed in casper.

As we know in casper, we have checkpoints and every 100 blocks, we have epoch blocks. Epoch blocks are the ones that validators vote with prepare and commit. So we can sum up that epoch blocks are the ones that get finalized.
If we get back to sentence that is said on the internet, I have a question:

does this mean it's that epoch block that can't be reverted ?
or all the blocks that come before this epoch block (that has been finalized) can't be reverted/changed ?

If the answer is the second one, then in Hyprid POW+POS of casper(it still follows the longest chain principle), if I broadcast the longest chain, how will it not be accepted by other nodes and validators ?


texts: Request and compare API Reponses in Oraclize call

texts:
I want to send requests to 3 Weather APIs and compare their results like if the rainfall at a specific day were the same London to avoid the single point of failure.

I already learned how I can send multiple requests to APIs. What is the best way to compare their results in Solidity? Is there already a mechanism from oraclize itself?


texts: How to reference coin contract already onchain?

texts:
In this tutorial:
https://dappsforbeginners.wordpress.com/tutorials/interactions-between-contracts/

they talk about interactions between contracts. However, the metacoin contract appears to be in the same source file as the contract referencing it. What if I wanted to reference a contract that was already deployed?
What would the identifier be?

if we have

contract caller{
    metaCoin m = metaCoin(   ...address... )
}

then this will give a compiler error, since type metaCoin is unknown.
How do I do this? i.e. reference contracts already on chain


texts: Error: new BigNumber() not a base 16 number when use map

texts:
I am new to Solidity programming and writing smart contracts for one of the application. I test the contract on my private train:

contract Proof
{
    struct FileDetails
    {
        uint timestamp;
        string owner;  //owner name
    }

    mapping (string => FileDetails) files;

    event logFileAddedStatus(bool status, uint timestamp, string owner,string fileHash);

    function set(string owner, string fileHash)
    {
        if(files[fileHash].timestamp == 0)
        {
            files[fileHash] = FileDetails(block.timestamp, owner);
            logFileAddedStatus(true,block.timestamp, owner,fileHash);
        }else{
            logFileAddedStatus(false,block.timestamp, owner,fileHash);
        }
    }

    function get(string fileHash) returns (uint timestamp, string owner)
    {
        return (files[fileHash].timestamp,files[fileHash].owner);
    }
}

I used this function and mined.

>  proof.set.sendTransaction("bob","abcdefgh",{from:web3.eth.accounts[0]});

It seemed work well.
But when I tried the following:

>  proof.get.call("abcdefgh")

I got this following error:

Error: new BigNumber() not a base 16 number:
    at L (bignumber.js:3:2876)
    at bignumber.js:3:8435
    at a (bignumber.js:3:389)
    at web3.js:1110:23
    at web3.js:1634:20
    at web3.js:826:16
    at map (<native code>)
    at web3.js:825:12
    at web3.js:4080:18

So the question is how can you run the function in Web3 without running into this error?

thx!


texts: transfering token from one account to another

texts:
i wanted to move token from one account to the other but the transaction is pending, what should i do?

 pragma solidity ^0.4.24;

contract smart{
event TransformToken(
    address _source,
    address _destination,
    uint amount
    );
mapping (address => uint)account;

function showToken(address _address)public view returns(uint){
 uint token=account[_address];
 return (token);

}
function addToken(address _address,uint amount)public{
 account[_address]+=amount;
 }
 function subToken(address _address,uint amount)public{
 account[_address]-=amount;
}

 function transfer(address _address,uint amount)public view returns(uint){
   addToken(_address,amount);
   subToken(msg.sender,amount);
   emit TransformToken(msg.sender,_address,amount);
   return showToken(_address);
   }
  }


texts: Is it possible to deplete all funds in an Ethereum account?

texts:
I have an Ethereum account loaded with Ethers and I need to spend all of them, leaving account final balance at exactly zero Weis. Is that possible?

I know using method eth_estimateGas() and multiplying by gasPrice it computes txCost, but is really there any guarantee this will be the actual fee of my next transaction? Gas estimation could change according to https://github.com/ethereum/go-ethereum/issues/2395 and gas price is not fixed, nor predictable https://etherscan.io/charts/gasprice

Is there any way to perform a transaction knowing exactly the final balance of sender prior to sending it?


texts: How do i loop through an array of structs? "TypeError: Integer constant expected." Solidity

texts:
What i want my code to do
Everytime the function is called the exampleValue of all users should be increased by 5
What the code actually does
When i compile it in Remix i get this error message:

TypeError: Integer constant expected. User[i].value = User[i] + 5; ^

Code
pragma solidity 0.6.0;

contract LoopingThroughArray {

    struct User {
        uint256 exampleValue;
        address id;

    }

    User[] public users;

    receive() external payable {
        for (uint i=0; i<=users.length; i++) {
            User[i].exampleValue = User[i] + 5;  // thats the line where i get the error
        }
    }

}

What i already tried

replacing the users.length with a constant uint both in- and outside of the function
using a normal function instead of the receive function


texts: Not able to populate my smart contract with data after deployment

texts:
I want to populate my smart contract with data. I am using truffle framework. In migrations file for the smart contract I'm populating the data but it is giving error:

TypeError: instance.create is not a function
    at newFunction (/home/user/Desktop/new/migrations/2_initial_migration.js:17:14)

Migration File:

var Storage = artifacts.require("./Storage.sol");

module.exports = function(deployer) {
    deployer.deploy(Storage)
    .then(() => Storage.deployed())
    .then((instance) => {
        instance.create("Allahbad", "Sanket", "car", "automobile","11-12-12", 1234);
    });
}

Smart Contract:

pragma solidity ^0.5.16;

contract NPA {

    struct NPADat {
        uint id;
        string bankName;
        string borrowName;
        string asset;
        string sector;
        string date;
        int Auction_id;
    }
    NPADat [] public npa;
    uint public nextId;

   function create(string memory bankName, string memory bname, string memory asset, string memory sector,  string memory Date, int auctionId  ) public{
        npa.push(NPADat(nextId, bankName, bname, asset, sector, Date, auctionId));
        nextId++;
    }

    function readId(uint id) view public returns(uint, string memory, string memory, string memory, string memory, string memory, int){
        for(uint i=0; i<npa.length; i++){
            if(npa[i].id==id){
                return(npa[i].id, npa[i].bankName, npa[i].borrowName, npa[i].asset, npa[i].sector, npa[i].date, npa[i].Auction_id);
            }
        }
    }
}


texts: Remix not showing function buttons after the contract is successfully deployed

texts: I am expecting Remix to show me buttons through which I could interact with the contract functions once I have deployed it successfully but the buttons are not showing you as can be seen in the below snapshot.


texts: Buy tokens form other smart contract using interface

texts:
I have two separate contracts, let's say Token and BuyFrom.

pragma solidity >=0.4.22 <0.7.0;

interface InterfaceToken {
    function invest(address contributor) external payable;
}

contract Token {
    string public name = "Token";
    string public symbol = "TKN";
    uint public decimals = 0;
    uint tokenPrice = 1000000000000000;

    uint public supply;
    address public founder;
    address payable public deposit;

    mapping(address => uint) public balances;

    constructor(address payable _deposit, address _founder) public{
        supply = 300000;
        deposit = _deposit;
        founder = _founder;
        balances[founder] = supply;
    }

    function invest(address contributor) public payable {
        uint tokens = msg.value / tokenPrice;

        balances[contributor] += tokens;
        balances[founder] -= tokens;

        deposit.transfer(msg.value);
    }
}

I want to buy tokens from BuyFrom using an interface. But it doesn't work.

pragma solidity >=0.4.22 <0.7.0;

import 'Token.sol';

contract BuyFrom {
    address payable private token;

    constructor(address payable _token) public {
        token = _token;
    }

    function buyToken(address contributor) external payable {
       InterfaceToken(token).invest(contributor);
    }
}

What I'm doing wrong?


texts: Are contract confirmations essentially executed for free?

texts:
Reading this question and this one, it's not clear to me whether the full nodes execute contract code for free. From my understanding, the client has to pay an amount of ether prior to making a transaction to a contract (startgas) and then an amount (gasprice) for each transaction.

The client pays this amount in order to execute the contract but when miners (full nodes) execute the contract for confirmation, do they do so for free?


texts: Upcoming Ethereum hard fork and ERC-20 token as fiat money

texts:
The ethereum network may face a new hard fork with the release of Ethereum 2.0 (scalability fixes)

Is it true that we might have two parallel ethereum networks each running a different consensus mechanism?

What happens with the tokens in that case? If i have 100 tokens before the fork, and later after the fork they are going to be duplicated. Will I be able to spend 200 tokens?
Let’s think of the token as a fiat currency for example. (1 token = 1$) i don’t mean a crypto currency, but rather like fiat money backed in a real guarantee bank account.

I would really appreciate if anyone could clear this out for me.


texts: How can I make a function that increases the total supply of a token every 365 days?

texts: Does anybody know a simple function that can increase the total token supply every 365 days with solidity?


texts: How can I make a Dapp that is free to use?

texts: I have a dapp where I want users to be able to register an account without needing Ether. Is it possible on the Ethereum network?


texts:
I'm currently in the process of deploying a ERC20 token with my symbol being CLC, and wondering if it's possible to change the value of the token based on the current date?

Basically splitting the value between phases?

1st August to the 20th August = 1CLC = $0.50
20th August to the 9th September = 1CLC = $0.75
9th September to the 6th October = 1CLC = $1.00

Would something like this be possible within a contract?


texts: How to send a transaction to Besu configured as a Free Gas Network


texts: Struct Mapping: DeclarationError: Identifier not found or not unique for

texts:
Using openzepplin version 2.0.0 and solc version 0.5. I am writing an ERC721 token contract on truffle. Truffle compiles with no error on solc 0.4.23. I had to upgrade to 0.5 due to openzepplin version.

Here's declaration for mapping:

struct Coordinates {
        string ra;
        string dec;
        string mag;
    }

    struct Star {
        string name;
        string story;
        Coordinates coordinates;
    }

mapping(uint256 => Star) public tokenIdToStarInfo;

Here's the method for returning Star mapping:

function tokenIdToStarInfo(tokenId) public view returns(string, string, string, string, string) {
        return (tokenIdToStarInfo[tokenId].name,
        tokenIdToStarInfo[tokenId].story,
        tokenIdToStarInfo[tokenId].coordinates.ra,
        tokenIdToStarInfo[tokenId].coordinates.dec,
        tokenIdToStarInfo[tokenId].coordinates.mag);
    }

Here's console for the truffle compilation error:

  starNotary.sol:21:5: The previous declaration is here:
      mapping(uint256 => Star) public tokenIdToStarInfo;
      ^-----------------------------------------------^

  starNotary.sol:80:32: DeclarationError: Identifier not found or not
  unique.
      function tokenIdToStarInfo(tokenId) public view returns(string, string, string, string, string) {
                                 ^-----^