texts:
I tried my hand at creating a crowdsale contract.

After sending my custom token to the contract and doing test purchases by sending ether to the crowdsale contract a issue is now at hand where the crowdsale has ended with the funded ether and the remaining custom tokens still in the crowdsale contract and is not being sent to the beneficiary. did I miss something out.

"funded Ether and remaining ico tokens are stuck in the crowsale contract"

bellow is the code used. " source ethereum.org"

pragma solidity ^0.4.18;

interface token {
    function transfer(address receiver, uint amount) public ;

}

contract Crowdsale {
    address public beneficiary;
    uint public fundingGoal;
    uint public amountRaised;
    uint public deadline;
    uint public price;
    token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool fundingGoalReached = false;
    bool crowdsaleClosed = false;

    event GoalReached(address recipient, uint totalAmountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);

    /**
     * Constrctor function
     *
     * Setup the owner
     */
    function Crowdsale(
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        address addressOfTokenUsedAsReward
    ) public {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken * 0.0005 ether;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

    /**
     * Fallback function
     *
     * The function without name is the default function that is called whenever anyone sends funds to a contract
     */
    function () private payable {
        require(!crowdsaleClosed);
        uint amount = msg.value;
        balanceOf[msg.sender] += amount;
        amountRaised += amount;
        tokenReward.transfer(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    modifier afterDeadline() { if (now >= deadline) _; }

    /**
     * Check if goal was reached
     *
     * Checks if the goal or time limit has been reached and ends the campaign
     */
    function checkGoalReached() private afterDeadline {
        if (amountRaised >= fundingGoal){
            fundingGoalReached = true;
            GoalReached(beneficiary, amountRaised);
        }
        crowdsaleClosed = true;
    }

    /**
     * Withdraw the funds
     *
     * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
     * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
     * the amount they contributed.
     */
    function safeWithdrawal() private afterDeadline {
        if (!fundingGoalReached) {
            uint amount = balanceOf[msg.sender];
            balanceOf[msg.sender] = 0;
            if (amount > 0) {
                if (msg.sender.send(amount)) {
                    FundTransfer(msg.sender, amount, false);
                } else {
                    balanceOf[msg.sender] = amount;
                }
            }
        }

        if (fundingGoalReached && beneficiary == msg.sender) {
            if (beneficiary.send(amountRaised)) {
                FundTransfer(beneficiary, amountRaised, false);
            } else {
                //If we fail to send the funds to beneficiary, unlock funders balance
                fundingGoalReached = false;
            }
        }
    }
}


texts: How can I multiply a fixed decimal var by a uint in solidity?

texts:
In base to this example:
Dealing with multiplying fractions in solidity
I am adding th DSMath correctly.
I can operate and compile with integers but if I try to compile a contract with any decimal inside the functions Remix dont let me compile: (for ex) this function
function theCalc(uint aNumber) public view returns(uint){
    return wmul(aNumber, 3.1416);
}

Remix error: TypeError: Invalid type for argument in function call.
Invalid implicit conversion from rational_const 3927 / 1250 to uint256
requested. return wmul(aNumber,3.1416);

Any idea how could I work with a fixed decimal number in my solidity calcs?
Thank you.


texts: How to write a function that is automatically called when a contract receives an ERC20 token?

texts: Fallback functions only work when a contract receives ether. Is there a way to write a fallback-style function that is automatically called when a contract receives an ERC20 token?


texts: Error in the truffle init command, quorum

texts:
i'm trying to truffle a project but each time it shows me this message,
whereas, i'm sure i installed the truffle successfully.

vagrant@ubuntu-xenial:~/quorum-examples$ cd project
vagrant@ubuntu-xenial:~/quorum-examples/project$ truffle init
truffle: command not found

my ubuntu machine version is 16.04


texts: Pyethapp port forwarding and configuration help?

texts:
I'm trying to setup an ethereum node on my raspberry pi using pyethapp as the client.

I was wondering if allowing port forwarded inbound connections would help to make my node more useful to the network, however I can't find any documentation about it in the docs, in fact they are quite scarce. If someone could point me to an example config.yaml file or an page with some configuration options for the python client (such as changing the default listening port) I would be very grateful.

I know bitcoin encourages all nodes to port forward 8333, and a few sources say that the default port ethereum uses is 30303, but I can't find any information that suggests that this is the case for the python client (as oppose to the more mainstream go client) and if there is point bothering with port forwarding at all.


texts: Why Deployment of ERC20 token contract to Ropsten is taking lot of time?

texts:
I'm trying to deploy my ERC20 token contract on Ropsten network, It took 2hr 30 mins and still pending, what is happening, any problem with deployments?
Is it linked to the recent batchOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018–10299) Look here

I have to deploy my ICO today, if some one have any news please let me know.
Thanks,
Fariha


texts: Question regarding ether cost of each token in crowdsale contract on ethereum.org

texts:
Is someone please able to clarify if I wanted 1000 tokens to be issued for 1 ether then what would I enter the price value in the contract.

function Crowdsale(
    address ifSuccessfulSendTo,
    uint fundingGoalInEthers,
    uint durationInMinutes,
    uint etherCostOfEachToken,
    address addressOfTokenUsedAsReward
) public {
    beneficiary = ifSuccessfulSendTo;
    fundingGoal = fundingGoalInEthers * 1 ether;
    deadline = now + durationInMinutes * 1 minutes;
    price = etherCostOfEachToken * 1 ether;
    tokenReward = token(addressOfTokenUsedAsReward);
}

I tried the below 3 options

0.001 but the contract won't accept anything i.e 0.xxxx

1000 and then the contract always never has enough GAS and I tried 0.0001 and it won't execute

I changed the code to be

price = etherCostOfEachToken * 0.001 ether;

and the contract runs but I get 0.0000001 of that token instead upon sending ether.

So can anyone please tell me from their experience what was the right value to put in to get 1000 tokens for 1 ether?

Thanks


texts:
I am including web3.js 0.19.0 and getting the following error from the browser console: Uncaught ReferenceError: web3 is not defined at file.html:270 when using it with the following code:

<script src="https://cdn.jsdelivr.net/npm/web3@0.19.0/dist/web3.js"></script>

<script>

window.addEventListener('load', function () {
    if (typeof web3 !== 'undefined') {
        console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
        web3 = new Web3(web3.currentProvider);
    } else {
        console.log('No Web3 Detected... using HTTP Provider')
        web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/key"));
        if(!web3.isConnected())
            console.log("not connected");
        else
            console.log("connected");
    }
});

web3.eth.defaultAccount = "0x..."; // <-- here starts the error "web3 undefined!!"
var myContract = web3.eth.contract(...abi...);
var myInstance = myContract.at('0x...');

</script>

On the other hand the browser gives me a positive message and tells me:

No Web3 Detected... using HTTP Provider    (because I don't use Metamask)

connected

So how can web3 not being defined, if I get a connection with it?


texts: How come npmjs website shows that Truffle latest version is 4.1.14, and that it was published 3 days ago?

texts:
According to this page, Truffle latest version is 4.1.14, and it was published 3 days ago.

However:

I have been using this version for months now.
I have noticed this "published 3 days ago" several times before (more than 3 days ago).
This version works in conjunction with solc v0.4.24, and I have encountered several questions here about using Truffle in order to test contracts compiled with Solidity v0.5.0.

Can somebody please explain what exactly is going on here, and what is the current latest version of Truffle?

Thanks


texts: Where to include arguments for invocation of state-changing function

texts:
I have this contract:

pragma solidity ^0.4.0;
contract Proof {
    function register(bytes32 hash) {
        if (hashToDate[hash] != 0) return;
        hashToDate[hash] = now;

    }
    function dateOf(bytes32 hash) constant returns (uint date) {
        return hashToDate[hash];

    }
    mapping (bytes32 => uint) hashToDate;
}

I deployed this contract successfully. I can call dateOf successfully as well, since it is a constant function (return value 0 is intended, since the hash has not been registered, yet):

> proof.dateOf("0x492...fee7d")
0

Now I want to call register(bytes32).

This is what I have from the documentation, but I don't know where to include the argument.

var tx = proof.register.sendTransaction(proof.address, 0, {from:eth.accounts[0]})


texts: How do I retrieve the token created by a transaction, and its history, via Etherscan API?

texts:
I am trying to walk to transaction history for this item. There were 300 of these (?) created. I have the transaction ID from Etherscan, 0x397cf219aadb0e25afc7fcbb35f36ebccd8611375b5c7ad888e4cbacced2d7ea that created a token. How do I get the address of the actual token being created (is it the to: and there are 300 additional detail token IDs????)? Then how can I see all the transactions that relate to that token (all sales) similar to how it's displayed on the superrare website?
Update: implementation in https://github.com/dblock/lost-robbies, walk-through in https://code.dblock.org/2021/04/27/walking-etherium-transaction-logs-to-find-lost-robbies-using-etherscan-api.html


texts: Why use Chrome Extensions for Hardware Wallets?

texts:
Is there any way for a remote webserver to connect to a USB device using serial? If so, why did major hardware wallets use a Chrome Extension as opposed to a backend server for connection? Ledger used to do it and Trezor still does it to connect hardware wallets to their own websites.

Thanks!


texts:
Several places say insecure unlock is poor practice.

Yet this module I am learning implements it.

Where can I find a way to Deploy an account without insecure unlock

Here is repository with files I am working with, i.e. deploy.js, etc, https://github.com/ArtieLadie/no_unlock

Here is screenshot from Pluralsight

By the way, I tried doing sudo geth attach http://127.0.0.1:8545 --allow-insecure-unlock (and other variations) for learning sake, but that also doesn't work!


texts: Why can't we use Transfer() to get a fallback from a contract?

texts: Does this discussion imply that we cannot call transfer() to some contract and call its fallback function and can only do the same by using call() and setting gas?


texts: How can execute function that send ether in geth console?

texts:
I want to execute the send function that sends ether from the sender to the receiver, the code is as shown below.

    contract Sender {
    function send(address _receiver , uint amount) public payable {
        address payable pReceiver = address(uint160(_receiver));
         pReceiver.send(amount);
    }
    function sending(address _receiver , uint amount) public payable {
        address payable pReceiver = address(uint160(_receiver));
        pReceiver.send(amount);
     }
 }

  contract Receiver {
  uint public a = 2;
  function aIs() public returns (uint256){
          return a;
      }

  function () payable external {
    if (msg.value == 0){
              require(true,"value is 0");
              a = 0;
          }
          else{
             require(true,"value is not 0");
              a = 1;
          }
          aIs();
  }
}

///////////////////////////////////////////////////

I just do like this in geth console.

------------------------------------------------
> loadScript('/home/ether/go-ethereum/build/bin/node2/rece.js')

true
> var receBin = '0x'+receBin
undefined
> var receAbi = receAbi
undefined
> var sendBin = '0x'+sendBin
undefined
> var sendAbi = sendAbi
undefined
> var conR = eth.contract(receAbi)
undefined
> var conS = eth.contract(sendAbi)
undefined
> personal.unlockAccount(eth.accounts[0])
Unlock account 0x25bd266f595501e1a0c2319f36b14ff942fa6901
Passphrase:
true
> var conSend = conS.new({from:eth.accounts[0], data:sendBin, gas:'5000000'})
----------------------------------

And when I try to execute Sender's function send, with Recevier's address

-----------------------------------
conSend.send.call(conReceive.address, 1)
evm.go/call function
>>input : d0679d34000000000000000000000000a40c342aaf0f4e8550395467627295327a60678d0000000000000000000000000000000000000000000000000000000000000001
>>using getDataBig : d0679d34
[1][op: PUSH1]
[2][op: PUSH1]
[3][op: MSTORE]
[4][op: PUSH1]
[5][op: CALLDATASIZE]
[6][op: LT]
[7][op: PUSH2]
[8][op: JUMPI]
[9][op: PUSH1]
[10][op: CALLDATALOAD]
[11][op: PUSH1]
[12][op: SHR]
[]

it is stop before running send

Could you give me some help??


texts: Can i delete some old files inside chaindata folder?

texts: I am running geth with fast sync, Can i delete some old files inside chaindata folder so that my ssd will have some empty space or it will create some problems ?


texts: Compute transactions trie root hash from a BlockBodies message using ethereumjs

texts:
Given a decoded BlockBodies message, I want to compute the root hash of the transactions trie, so that I can match it against block headers that my node has downloaded.

After reviewing How Ethereum transaction tree is formed and scanning through the source code for go-ethereum, OpenEthereum (nee Parity) and ethereumjs-block, I feel like I'm close — but I'm still not getting the correct result.

Here are the important bits from my code:

const { Transaction } = require('ethereumjs-tx')
const { rlp, toBuffer } = require('ethereumjs-util')
const Trie = require('merkle-patricia-tree')

// Construct a Patricia trie, using each transaction's index as the key, and the
// raw transaction body as the value.
const tree = new Trie()
tree.batch(transactionsRaw.map((t, i) => ({
  type: 'put',
  key: rlp.encode(toBuffer(i)),
  value: new Transaction(t).serialize()
})))

// According to Infura, the transactions trie root for block 9069000 is...
console.log('Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537')
// And this is what my code generates...
console.log(`Actual   tx root: 0x${tree.root.toString('hex')}`)

Here's what I get when I run the code:

Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537
Actual   tx root: 0x8147ebbcffc667ee12746a2154299728a46435f4078d2f6f8b113e34f2758c6b

I have verified that transactionsRaw contains the correct data by unserialising each transaction and comparing their hashes against Infura.

I feel like I'm just putting the wrong keys/values into the trie, but I can't find any examples, and comparing hashes doesn't exactly provide a whole lot of feedback

What am I doing wrong here?


texts: Generate timed transactional deposit wallets

texts:
I am looking at developing a service that can take a payment in Eth and return a erc-20 token to their desired address.

I want to generate a new address per transactional user. What would be the best way to develop a wallet per transaction?

A good example is www.latoken.com

* UPDATED *
I have found a solution using eth-hd-wallet package in node. The following example creates 1 million wallets from a generated mnemonic code. Documentation can be found here: eth-hd-wallet

const { generateMnemonic, EthHdWallet } = require('eth-hd-wallet');

const phrase = generateMnemonic();

const wallet = EthHdWallet.fromMnemonic(phrase);

console.log(phrase);

console.log( wallet.generateAddresses(1000000));

To display the QR code, I can utilise Google's api to generate the QR per wallet. Link to site is here: Google QR Code

Thanks


texts: I’m trying to build a versioning System using IPLD and IPFS .Is it possible to publish hashes from multiple users to the same IPLD object?

texts: I’m using Ipfs-api from Infura for interaction .I’m able to create and upload files to the Ipld object .I want to store different versions of the same file on the object.These versions can be published from different users.Is it possible to publish hash to the same IPLD object if we know it’s hash?


texts: is there any advantage of using inline assembly call over address.call?

texts:
Is there any advantage of using inline assembly call over address.call?

For example

// address addr
// uint value
// bytes memory data

// using inline assembly
assembly {
    call(gas, addr, value, add(data, 0x20), mload(data), mload(0x40), 0)
}

// using address.call
addr.call.value(value)(data)

I am looking at the code for Gnosis multisig wallet and wondered why they were using assembly call instead of address.call


texts:
pragma solidity ^0.4.23;

contract adding{

  uint256 public total;
  function  add(uint256 val1,uint256 val2) public returns(uint256){
    total = val1+val2;
    return total;
  }
}

The above code add two numbers

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

contract ('adding', function(accounts){

  it ("it will add two numbers", function(){
    return adding.deployed().then(function(i){
      instance = i ;
      return instance.add(3,4)
    }).then(function(value){
      assert.equal(value,7,"the values of 3 and 4 must be equal to 7" );
    });
  });
});

The above code is my unit test but the unit test fails. If I interact with my truffle console it will work

  Contract: adding
    1) it will add two numbers
    > No events were emitted

      0 passing (115ms)
      1 failing

      1) Contract: adding
           it will add two numbers:
         AssertionError: the values of 3 and 4 must be equal to 7: expected { Object (tx, receipt, ...) } to equal 7

I can see the following error in my console while running truffle test


texts: Eth Console Won't Start: Invalid Argument Console

texts:
Can't Use "Eth Console" Command upon Installing Eth with Spacebrew

Hi everyone, I'm learning how to create my own d'apps on the Ethereum blockchain as part of a Master's thesis research process. So far I've been taking tutorials with geth and Mist, but am now moving into Eth and Mix for the C++ implementation.

I've already successfully installed geth with spacebrew and can use it normally from the command line.

I just tried to install eth using the instructions from the github and was able to successfully compile using spacebrew.

However, when I try to run

eth console

as per the instructions, I keep getting the error, "Invalid Argument: console".

I've tried using

eth --console
eth -console
eth console --frontier
eth console --testnet

all with similar results, and have made sure to upgrade and update spacebrew.

I've looked all over for someone with a similar problem, but can't find anything in the forums.

Does anyone have any insight?


texts: Should the constructor function be public?

texts:
In all the tutorials I'm watching nobody specifies public, but remix presents warnings that function visibility has not been specified, and public is assumed.

Since I don't like warnings if possible, I am specifying public where necessary, but I wonder if the constructor function itself should be public or private. It seems to me that it should be a private one, as it's called automatically by the contract itself on creation, or is my reasoning faulty?


texts: Gas estimation failed when send a transact

texts:
When I run sendDeposit function, everything works fine, but when I try to run startSession function an error saying :
"Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted"
can someone help me, please?
    pragma solidity 0.4.25;

    contract Bank
    {
     string app_name = "";
     int status = 0;
     string invoiceNumber = "000000000";
     string receiptNumber = "000000000";
     int balanceDue = 0;
     int depositAmt = 0;
     int officeId = 0;
    string owner_address = "";
    string tenant_address = "";
    int timestamp = 0;
    int stageNumber = 0;
    string water_rate = "";
    string water_cons= "";
    string elec_rate= "";
    string elec_cons= "";
    string band_rate= "";
    string band_cons= "";

constructor()public
{
    app_name = "Future Estate";
}

 function startSession(int _officeId,int _timestamp, string _waterRate, string _waterCons, string _elecRate, string _electCons,  string _bandRate, string _bandCons) public
{
    stageNumber = 2;
    officeId = _officeId;
    timestamp = _timestamp;
    water_rate = _waterRate;
    water_cons = _waterCons;
    elec_rate = _elecRate;
    elec_cons = _electCons;
    band_rate = _bandRate;
    band_cons = _bandCons;
}

function sendDeposit(int _officeId,int _deposit,string _owner_address,string _tenant_address) public
{
    officeId = _officeId;
    depositAmt = _deposit;
    stageNumber = 1;
    owner_address= _owner_address;
    tenant_address = _tenant_address;

}

function endSession( int _officeId, int32 _timestamp,string _waterRate, string _waterCons, string _elecRate, string _electCons, string _bandRate, string _bandCons,string _invoiceNo, string _receiptNo) public
{
    stageNumber = 3;
    officeId = _officeId;
    timestamp = _timestamp;
    water_rate = _waterRate;
    water_cons = _waterCons;
    elec_rate = _elecRate;
    elec_cons = _electCons;
    band_rate = _bandRate;
    band_cons = _bandCons;
    invoiceNumber = _invoiceNo;
    receiptNumber = _receiptNo;

}

function settlePayment(int _officeId, int32 _timestamp,int32 _serviceCost) public
{
    stageNumber = 4;
    officeId = _officeId;
    timestamp = _timestamp;
    balanceDue = _serviceCost - balanceDue;

}

}

this is the  input parameters that I am sending:


texts: Rinkeby: waiting for transaction to be mined

texts:
My transactions (publishing contracts and sending ether) aren't going through on Rinkeby (last several hours). Metamask is listing those txs as failed.

I've set my gas price fairly high (100+) with no results.

Why is this, and what is the prognosis?


texts: Is there a need of network additional security measure

texts:
I didn't find information about the risk and threat of being connected to the Ethereum network / internet. I was wondering if we would need additional measures such as a firewall, proxy to protect some intrusion inside a corporate network.
I illustrate this on the following figure.

Thank you!


texts: Saving gas on large amount of token distribution

texts:
I was wondering if this function is safe to use? is there any way to reentrancy or cause arithmetic issues?
function sendBatchCS(address[] _recipients, uint[] _values) external returns (bool) {
        require(_recipients.length == _values.length);

        uint senderBalance = balances[msg.sender];
        for (uint i = 0; i < _values.length; i++) {
            uint value = _values[i];
            address to = _recipients[i];
            require(senderBalance >= value);
            if(msg.sender != _recipients[i]){
                senderBalance = senderBalance - value;
                balances[to] += value;
            }
            emit Transfer(msg.sender, to, value);
        }
        balances[msg.sender] = senderBalance;
        return true;
}

I did not find any issues with it and it seems to be a convenient way to save on gas costs during congested network time.


texts: Call contract function with address and abi to return value to frontend

texts:
I've deployed the following contract to Ethereum testnet.

contract demo {
  string public name = "someString";

  function returnValue() constant returns (string){
      return name;
  }
}

I am trying to retrieve the contract's string and this won't work

var contract = web3.eth.contract(contractAddress, abi); //contractAddress+abi known
console.log(contract.returnValue);

returns undefined

If I use this code:

var asdf = web3.eth.contract(abi).at(contractAddress);
alert(asdf.returnValue);

I get `function(){[native code]}
How can i get the string "name" from my solidity contract to my javascript? Thank you


texts: Please help me understand suspicious transactions moving funds from my wallet

texts:
I see some mysterious ETH withdrawals from my address. Could you please help me to understand why it happened?

I have an address 0xee5119... in my local Ethereum wallet. There are transactions 0xf86327... and 0xa668e5... that move some funds to the address 0x8f0d1d....

I do not recognize neither this address nor these transactions. Soon after that, funds are further moved to the address 0xc96d5d..., which has the current balance of 64063 ETH and a lot of activity.

Any ideas what might be going on here?


texts: If I send a transaction with a low gas fees and then send another one with high gas fee elsewhere?

texts:
Let's say, I send a transaction, all of my Ether, with low gas fees and it'll take hours for it to complete. Right away I send another one, from the same wallet or address, also all of my Ether, to some other address and with a high gas fee so that it'll complete in a minute.
Is this called double spend or what?What'll happen to my 1st  transcaction when the time has come and it's being processed by miners or validators? How will it be resolved?


texts: geth js commands to handle my Wallet contract

texts:
I have created a Wallet contract using the Mist. Now I am trying to handle it using geth console javascript commands. By handling I mean sending ether to an account. Can someone help me with the js commands to do that? I have come this far:

abiDef = *interface from Mist*
Wallet = eth.contract(abiDef);
myWallet = Wallet.at(*address from Mist*);

So how do I send ether to an account using myWallet?

I found it :) :
https://github.com/ethereum/mist/wiki/Wallet-Contract


texts: How do in invoke a contract function from code and sign the transaction?

texts:
My use case is that I have to invoke a contract function when an API is called.

Now I have tried multiple ways, but I have issues with both. My function name is "transfer".

Method - I

In this method I first unlock the account of the user. Then invoke the contract function by contractInstance.methodName(). In the callback method, I lock the account again

Issue: The issue I see here is, when I get multiple calls to my api at the same time, it will cause an issue. As one call might lock the account just when one more thread is trying to invoke the function.

/ * Getting the contract Instance */

import Web3 from 'web3';
  const tokenABI = require('../ContractABI.json');

  if (typeof web3 !== 'undefined') {
    var web3 = new Web3(web3.currentProvider)
} else {
    var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'))
}

var TokenContract = web3.eth.contract(tokenABI.abi);
var tokenInstance = TokenContract.at(contractConfig.id);

/ * Getting the contract Instance */

router.post('/transferTokens',async (req,res,next)=>{
    let senderAddress = req.param("sender");
    let receiverAddress = req.param("receiver");
    let transferAmount = req.param("amount");

    let searchCriteria = {
        address:senderAddress
    }

    try{
        // Getting the private key of the user from DB.

        let senderDetails = await MongoHelper.findOneByCriteria('accounts',searchCriteria);
        console.log('senderDetails:',senderDetails);

        let chk = web3.personal.unlockAccount(senderDetails.address, senderDetails.pwd, 95000);

        // Unlocked the account and then invoke the transfer function with the necessary parameters.

        tokenInstance.transfer(receiverAddress, transferAmount, { from: senderDetails.address })
        .then(function (msg) {
            res.data = msg;
            let chk = web3.personal.lockAccount(senderDetails.address);
            next();

        }).catch(function (e) {
            console.log('Error %%%%%%%%%%%%%%%%%',e);
            let chk = web3.personal.lockAccount(senderDetails.address);
            next(e)

        });

    }catch(err){
        console.log(' Error err:',err);
        next(err);
    }

});

Method - II

**In this method, I am deriving the callData for my contract function. I am creating a Raw Transaction Object. I am signing it with the user's private key. Then I am using web3.eth.sendRawTransaction to send the transaction **

Issue: The issue i am facing is: I see a transaction is created. But it is not doing what it should do ideally. It is just a dummy transaction. The contract method is not getting invoked. I guess the call data is not proper or something.

I see the calldata something similar to below:
0xb7184b680000000000000000000000000000000000000000000000000000000000000578

router.post('/transferTokens2',async (req,res,next)=>{
    let senderAddress = req.param("sender");
    let receiverAddress = req.param("receiver");
    let transferAmount = req.param("amount");

    let searchCriteria = {
        address:senderAddress
    }

    try{
        let senderDetails = await MongoHelper.findOneByCriteria('accounts',searchCriteria);
        let callData = tokenInstance.transfer.getData(receiverAddress,transferAmount);

        let rawTx = {
            from:senderAddress,
            nonce: 93,
            gasPrice: '0x4a817c800', // eth_estimateGas rpc result
            gasLimit: '0x2fd618',
            to:receiverAddress,
            data:callData
        }
        var privateKey = new Buffer(senderDetails.key, 'hex')

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

        var serializedTx = tx.serialize();

        web3.eth.sendRawTransaction('0x'+ serializedTx.toString('hex'), function(err, hash) {
            if (!err) {
                console.log('$$$$$:',hash);
                res.data = hash;
                next();
            }else{
                next(err);
            }
        });

    }catch(err){
        next(err);
    }

});


texts: Web3 Console Test -> tokenInstance.balanceOf(boom).then(function(bal) {balance = bal;}) ERROR

texts:
Learning Web3 right now and I am getting an error when I try to read the token balance of a Ganache account when I run the following line in the console:
tokenInstance.balanceOf(boom).then(function(bal) {balance = bal;})

And I get the error:
Uncaught:
Error: invalid address (argument="address", value={}, code=INVALID_ARGUMENT, version=address/5.0.5) (argument=null, value={}, code=INVALID_ARGUMENT, version=abi/5.0.0-beta.153)
    at evalmachine.<anonymous>:0:15
    at sigintHandlersWrap (vm.js:273:12)
    at Script.runInContext (vm.js:140:14)
    at runScript (/Users/x/node_modules/truffle/build/webpack:/packages/core/lib/console.js:258:1)

NOW I experienced something similar with >truffle(development)> tokenInstance.balanceOf(admin)
which gave the same error. I realized it was because Web3 has evolved to make previously correct code to be invalid. I corrected it using the .getAccounts() as seen here:
boom = web3.eth.getAccounts().then( function (result) { return result[0] });

*NOTE: boom is the address being used!
My question is: What is the correct syntax to retrieve the token balance of a specific Ganashe address?
Also what is some documentation you recommended for learning tests, as there isn't much compared to web3 and Solidity.
Just began my journey, thank you for any response.
Cheers


texts: Web3js - Decode multisend ABI contract results in BigNumber Error

texts:
I am trying to decode the following  smart contract ABI. When I try to decode a transaction input with it, it yields following error:

Unhandled rejection BigNumber Error: new BigNumber() not a number: 27699642598250537994,27699642598250537994,27699642598250537994,27699642598250537994,27699642598250537994,27699642598250537994,27699642598250537994,...

I am using the following code to decode the contract:

    const source = fs.readFileSync("MultiSend.sol", "utf8");
    const compiledContract = solc.compile(source, 1);
    const abi = JSON.parse(compiledContract.contracts[":Airdropper"].interface);

    const abiDecoder = require("abi-decoder");
    abiDecoder.addABI(abi);

    Config.web3.eth.getTransaction("0x8f2c00ebd1f5bce60fcc09024423037813e7bc21f5e995f10bff225502b8beab").then((t: any) => {
        const decodedInput = abiDecoder.decodeMethod(t.input);

        // handle decoded input....
    });

My goal is to decode the multi-send operation of the contract.

Can anybody help?


texts: Using gnosis safe with ledger hardware wallet

texts:
I have created a 2/2 multisig wallet using the Gnosis Safe with one of the signer being a ledger hardware wallet.
I have done 2 tests:

The ledger is the first to cosign, then the ledger screen will display a rather cryptic transaction hash and ask for validation

The ledger is the last to sign, then it will ask me to validate the amount (incorrectly displayed, I wanted to transfer 0.2ETH and it was displaying 0) and the destination address (again, showing incorrect data and not the address I was sending my transaction to)

So either it shows (1) no relevant information regarding the transaction or (2) incorrect data - is this a known limitation using Gnosis Safe?


texts: web3js.eth.getAccounts() and ethersjs.listAccounts() always returning one account in an array even when more are in metamask?

texts:
I have tested web3js.eth.getAccounts() of web3js and ethers.listAccounts() of etherjs and they are returning an array with a single account although my metamask has one or more accounts.
Is this the way they are intended to work? ANd if yes, then why have a method like listAccounts()? Instead of listAccount() and why return an array instead of a single item?
In what circumstances will the methods mentioned above return an array of more than one account?


texts: Is there a Ethereum mainnet node that I can query txpool APIs?

texts:
I want to call txpool APIs of Ethereum mainnet but I found Infura doesn't provide that.
Is there any service providing txpool JSON-RPCs?


texts: Geth is syncing very slowly in testnet after block 588000. I read that it might be because the testnet is under attack? To fix the problem do I have to delete the current blockchain and download it all over again? or is there an easier way? If I let geth keep syncing in this very slow rate will it pick up the pace later?


texts: Should I stop the geth node during hard-fork?

texts:
As the countdown on https://ethernodes.org/istanbul, should I need to stop my geth node before hard-fork? Or I could continue to syncing during hard-fork.
Thanks alot.


texts:
let yourAccount = web3.eth.getCoinbase();
$("#accountAddress").html("Your Account: " + yourAccount);

What I'm trying to do here is retrieve the account value using getCoinbase(), copy it into yourAccount, and then use that in some html.  On the web page that I'm using, I get an undefined value.  What am I doing wrong?  Could it be a setting with my metamask?


texts: How to pass the external account address to the contract function when calling another contract

texts:
If we deploy the contract B, and pass the contract B address to the contract A.  When call the contract B function from the contract A, inside the contract B function, the msg.sender is the "address of contract A", not external account original calls from the contract A.

Here is the example:

pragma solidity ^0.4.18;

contract metaCoin {
    mapping (address => uint) public balances;
    address[] public addresses;

    function metaCoin() {
        balances[msg.sender] = 10000;
        addresses.push( msg.sender );
    }
    function getBalance(address _addr) public view returns (uint) {
        return balances[_addr];
    }
    function sendToken(address receiver, uint amount) returns(bool successful, address _caller){
        if (balances[msg.sender] < amount) return (false, msg.sender);
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        addresses.push( receiver );
        return (false, msg.sender);
    }
}

contract coinCaller{

    function sendCoin(address coinContractAddress, address receiver, uint amount) public returns (address) {
        metaCoin m = metaCoin(coinContractAddress);
        var (status, addr) = m.sendToken(receiver, amount);
        return addr;
    }
}

Step 1. Using the account, 0x1328500533b017449698300A868fA24eaC1D7486 to deploy metaCoin contract at the address, 0x9628a8814b1b83c67a974f23af8dfd16fea49ae9

Step 2. Use the same account to deploy coinCaller contract at the address 0xd8d5b5f968f119531a941a05682bbbb154d367c0, then call,

coinCaller.sendCoin("0x9628a8814b1b83c67a974f23af8dfd16fea49ae9", "_any_account_addr_", 88)

This function should have transferred the balance from 0x1328500533b017449698300A868fA24eaC1D7486 to _any_account_addr_ with 88.  But, it doesn't perform like that. The issue is that in metaCoin.sendToken() the msg.sender is coinCaller contract address, 0xd8d5b5f968f119531a941a05682bbbb154d367c0.

This is documented in the Solidity documentation as the "sender of the message (current call)", which is the coinCaller contract in this call.

Is there a way to work around this to have the external account address of coinCaller.sendCoin()?


texts:
I am trying to pair two unique values, lets call them A and B, there is no mathematical correlation between them. When having value A I want to know value B and vice versa. I thought of creating two mappings:

mapping( uint32 => byte32 ) toB;
mapping( byte32 => uint32 ) toA;

However I will need to store each value twice, is there another solution to this ?


texts: Unlocking function after time - is it safe?

texts:
In my code there is a function which will be called once every 2 months by me. I would like to make it impossible to call it more often than once every 2 months for some security reasons.

I found out that I can store time and in the very beginning of the function simply add assert until time gets greater than variable, and when function goes complete, it stores current time + 2 months to the variable.

It's pretty simple, but is it safe? Can time be anyhow hacked or written by block miners? Or maybe is there any other way to make it possible to lock function for specific amount of time?


texts:
I want to generate large number of transaction probably in thousands per day to store document hashes of certificates from Universities so that I can verify the integrity of documents through time stamp and hash. The problem is the Ethereum transaction fees has jumped quite high.

Will Ethereum 2.0 decrease transaction cost significantly with implementation of Sharding and ZkSnarks?


texts: Solidity for loop over a huge amount of data

texts:
I want to use a function to find all tokens of a user in solidity, so I use a for loop to iterate over all tokens and look if the addresses do match. But my function always returns zero for 10Mio iterations, so I implemented a test function to see where the limits are. Does solidity have a problem with huge for loops? For example I tried the following test function, which returns always 0 if the number of iteration is above around 3'000'000. It looks like there is a timeout for a function to run?

function testLoop(uint256 num) external view returns(uint256 res) {
        uint256 i=0;
        uint256 cnt=0;

        for(i;i<num;i++) {
            cnt++;
        }

        return cnt;
    }


texts: Execute contract without gas on parity private network

texts:
is it real to execute contract without gas?

I develop app on parity private network, in what user can register account, after registration he must receive coins from admin address.

But new users (new addrress on private netowkr) can't execute contract, because they don't have coins for pay gas.


texts:
I am having trouble creating a private ethereum network on AWS. I have enabled TCP/UDP for the desired ports in the firewall in AWS.

On one node A(aws instance) I start the geth console by making use of a custom genesis file using command

geth --datadir="ethdata" init fresh.json

I then execute geth on the same node A using the following command

geth --datadir="ethdata" --networkid 1234 console

Now I startup another AWS instance node B. Here to I initilize geth using the custom genesis file

geth --datadir="ethdata" init fresh.json

And then start geth console in node B using

geth --datadir="ethdata" --networkid 1234 console

And then in node B I execute the following command

>admin.addPeer("<enode of the nodeA")

The above command returns me true

However admin.peers in both node A and node B comes up with empty strings.

Occasionally I am able to view other peers connected to either of these nodes (probably because I am executing geth without --nodiscover option), but I am still unsuccessful in establishing a peer-peer connection between my two nodes.

Please advise what could I be going wrong.

PS: I have tried with the bootnode option as well, but still no success.

Question: Can I have just bootnode running on node A and then node B having a geth console running that connects to the enode using bootnodes "enode url" ? Although I did try this, it still didnt result in a proper peer-peer connection.


texts: How can I create complex array relationships in solidity?

texts:
Hello I'm trying to work out how to create complex relationships in Solidity.

In this example a customer will place an order using a function with arguments, however it cannot be for any combination of shops, types, and products, the relationship must already be established.

In a normal relational database the foreign keys would ensure the relationship was good, and I think in Solidity this is the case with mappings, but I'm not sure how this could be applied:

struct ShopName {
    string name; // ShopA, ShopB, ShopC
}

// Each shop can have one or more types
struct ShopType {
    string type; // market, brick, online
}

// each type can have one or more products
struct Product {
    string productCode;
    uint unitPrice;
}

struct SalesOrders {
    address customer;
    uint qty;
    string status; // paid, unpaid
}

So I am imagining a transaction something like this:

function placeOrder(string _shopName, string _shopType, string _productCode, uint _qty) {
    ...
}

In this example the ShopName ShopType and Product must have an established set of related values, and when an order is placed only those related values can be allowed.

But somehow I think I have a got totally lost because I don't know how to think about this problem, let alone how to access the data.

I have seen the example in readthedocs but I am confused about putting this into practice. Can someone give me some direction please?


texts: What are the benefits to using string datatypes over bytes32 to represent text data. It seems my contract runs into an out of gas exception when I switch the data structures from bytes32 to string.


texts: where is the file that references accounts in the geth client

texts:
There must be a .dat file or something that stores the accounts in the geth client, where is this file located?

As an aside, are Externally Owned Accounts (EOAs) and Contract Accounts actually represented differently?

Update:

In ~/Library/Ethereum/keystore I found a file called UTC--2017-05-26T21-30-22.367673851Z--ca02951f8bcd593e26f54801a4da85c221f89731 which has been reproduced below:

{
    "address":"ca02951f8bcd593e26f54801a4da85c221f89731",
    "crypto":{
                "cipher":"aes-128-ctr",
                "ciphertext":"8e13b86398de9bc1977153c683315d13771d65b38fcb425a99bcc59761071e1f",
                "cipherparams":{
                                "iv":"49227b95cf1fb8c96c749fe1d180b25b"
                                },
                "kdf":"scrypt",
                "kdfparams":{
                                "dklen":32,
                                "n":262144,
                                "p":1,
                                "r":8,
                                "salt":"6233be72e2478cf7ed4aee675e7862c5d55f23a270cd8c46f66cf37460badca0"
                            },
                "mac":"5243792b391ea7171f23b5378cf77bdcf90f4baa03067ba55d988c6ecb9ee8e5"
            },
    "id":"6b3fba5f-d3cb-452e-9d73-2b760085be71",
    "version":3
}

Would someone please explain to me the significance of this file?

I was under the impression that this would be all the accounts on the entire Ethereum blockchain, but it seems to me that this is perhaps only my own account that was automatically generated when I fired up geth, is that right?


texts: If all nodes execute smart contracts, why do only block creators get the gas fee?

texts:
I have a question regarding smart contract execution.

It is my understanding that when a user requests a smart contract, miners will execute the smart contract, and bundle its output in a block before broadcasting to the network.

But then all other full nodes / miners will have to check the transactions inside the received block, and doing such requires also executing the smart contract to see if the output is the same as the miner's.
And so all full nodes end up executing the smart contract requested by the user.

However, only the miner earns the gas associated with the smart contract execution. Does that mean that all nodes that execute the smart contract after the miner to verify its result do not earn any gas?

I understand why in Bitcoin it's not really problematic to only reward the miner because most of the computation goes into solving a proof of work. But verifying a block is "easy" (verify transactions, the pow solution, and a few other things). So it's fair to say that block creation is where most of the calculation is at, not block verification (cost per node; energy consumption of block creation vs verification network wide is another question I guess...)

In Ethereum however, it's not exactly the same thing, because verifying a block may include executing many smart contracts. Which is more costly than just verifying a user<=>user transaction I assume.

Am I missing Something?

Is it worrying for smart contract scalability that all nodes execute the contact?

What are the energy code of adding two integers together via an Ethereum smart contract considering all nodes will execute this addition?

What will convince nodes to become full nodes and verify blocks if it becomes costly for them ? What is the most computationally intensive smart contract one could reasonably have on Ethereum?

I guess I've just realized the implications of everyone node running smart contracts at some point hence my many questions. I would love it if someone could enlighten me a bit on that aspect!

Cheers!


texts: Is it possible to create and assign any number of NFTs without emitting Transfer event? (ERC721)

texts:
I am asking this question regarding to the dev note above Transfer event in the ERC721 spesification / code.

/// @dev This emits when ownership of any NFT changes by any mechanism.
///  This event emits when NFTs are created (from == 0) and destroyed
///  (to == 0). Exception: during contract creation, any number of NFTs
///  may be created and assigned without emitting Transfer. At the time of
///  any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);

I am scratching my head for days because of this. How is this possible? Technically, I couldn't think of any solution to create "n" tokens and assign to a wallet address, without mapping token ids in a for loop in the mint function. Probably to achieve this, enumeration functions in the official implementations should be bypassed. But then how do the tokens exist in contract? Is there an example implementation regarding this? I searched everywhere but couldn't find anything. Being able to create "n" number of NFTs on contract creation (without emitting an event) would benefit me a lot; I am working on some experiments, so I am disregarding the events for now.
Thanks!


texts: how to judge if a struct var exists in solidity?

texts:
code like this:

struct Voter {
    bool voted;
    uint vote;
    uint votetime;
    bytes32 remark;
}
mapping(address => Voter) public voters;

I want to judge like this:

if(voters[msg.sender]) {
    do something…
}


texts: Creating and pushing transactions while preserving IP privacy

texts:
What is the simplest way to generate a signed transaction without compromising your IP address? MEW for one either doesn't work over TOR at all, or when it does it makes the signed transaction impossible to copy, and in that case the send transaction button doesn't work either. (Is that intentional or just bugs?)

Is there a way to make MEW work properly under TOR? Or perhaps there is some other tool that I am not aware of yet? Thanks.


texts:
my etherbase password stopped working.  the passwords for my other accounts work fine.  I'm on windows, same thing happens in every version, 32&64.  any idea how this could happen?  is there any info I need to paste in here?  thanks

edit: it looks like I can't select a fee even though I have more than 1 ETH in the account, does this matter?  it says the same thing for other accounts, and those transactions go through fine.


texts: Using Infura with Web3, HTML, ProviderEngine

texts:
Currently, I have a Dapp that cannot rely on the users having their own Metamask accounts or Ethereum nodes. I plan to create a frontend that allows the users to interact with a deployed Ethereum Contract through Infura, but I've run into a snag. I can read from the contract just fine, but I cannot write to it through the frontend, as any attempt to do so results in:

Uncaught Error: invalid address

A spot of research suggests to me that this is because, well, Infura cannot access my Ethereum address. I was also recommended to use ProviderEngine to deal with this, but I am having great difficulty in finding more specific information and examples. Can anyone give me a hand with puzzling out exactly how this should work?

Thanks


texts: is there any problem if i put GETH/PARITY and webserver in one server?

texts: my website need to use something about ETH,so i have to setup a geth/parity rpc server.  is there any problem if i set the geth/parity rpc in my webserver?


texts:
I understand that both the Rinkeby and Kovan testnets employ the Proof of Authority (PoA) consensus algorithms. I also understand how PoA works. However, I still dont understand how Kovan and Rinkeby differs. From this post, I see Kovan is "supported by Parity" and Rinkeby is "supported by geth".

What does this mean?
I have noticed that my transactions take on average 5 sec to get mined on Kovan while it takes on average 20 sec to get mined on Rinkeby. If the consensus algs on both these networks are identical PoA, why is there a huge difference in the mining times of transactions across these networks?


texts:
Can geth dev mode (https://geth.ethereum.org/docs/getting-started/dev-mode)
access on chain data?
If not what is the point of using it?


texts: Is there a BIP38 equivalent for Ethereum private keys?

texts: What is the best practice to encrypt an Ethereum private key? For example, Bitcoin has BIP38.


texts: How to create a data structure in Solidity with no limits on size?

texts:
In solidity we are not allowed recursive Structs, so I cannot create a recursive data structure with unlimited nodes.
Similarly, Solidity Arrays are fixed to the size you initialize them with.

So I am wondering, say I need a smart contract which has a data structure which has no fixed limits? Is this even possible?

I am interested in doing this in just one smart contract. However I am aware that if I have smart contracts deploy new smart contracts then each one can point to the next and have unlimited storage. (Linked list where each smart contract is a node)

But can I do it in just one smart contract?


texts: Can a flash loan used to flash attack a smart contract?

texts:
I am new to flash loans. Let us say I have smart contract where people vote. Your voting power on this contract is based on how many token x you have. The votes are yes and no and the vote with more than 50% wins.
During voting, can an attacker take a flash loan and cast their vote to manipulate the results to what they want?


texts: How to connect private nodes over the Internet

texts:
I have looked at dozens of similar questions about this, but none seems to have this particular problem. I have created a private network of three nodes on three different machines using geth1.5.5. When I take any two of them to a friend's house and connect via wifi, I can use admin.addPeer() with the sub-net address to connect them together and they sync up nicely and mine for each other, everything.

BUT when the machines are on different (xfinitywifi) routers and I try to connect with admin.addPeer() using an external IP address, they never connect. I have tried these machines with geth connecting to the mainnet and testnet and they have no trouble discovering peers there. So it's not as if xfinitywifi is blocking the nodes. The private net uses nodiscovery and they have the same networkid and genesis block - after all, they work fine on the same subnet. So what can possibly be the difference?? I use a web page to find my external IP on each machine, so I don't see how I can get that wrong. I have tried different listening ports, but again, that doesn't seem to do anything and the nodes work when on the same subnet. Anybody have any ideas?


texts:
I have a solidity function that returns an array.
I'm trying to read the values inside this array from web3j but it gives me stage results.

My solidity function

function getAllSubTokenByTokenID(uint256 _id)
    public
    view
    returns (uint256[] memory)
{
    return tokens[_id].subTokens;
}

tokens is a Struct and subTokens an array of uint32

In Web3j:

Function function2 = new Function(
            "getAllSubTokenByTokenID",
            Arrays.asList(new Uint256(1)),  // Solidity Types in smart contract functions
            Arrays.asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));

    String encodedFunction2 = FunctionEncoder.encode(function2);
    org.web3j.protocol.core.methods.response.EthCall response2 = web3j.ethCall(
            Transaction.createEthCallTransaction(credential.getAddress(), "0x1B2858ae498bA0aEd0176Bd68ad4fB950E80D708", encodedFunction2), DefaultBlockParameterName.LATEST)
            .sendAsync().get();

    List<Type> values = FunctionReturnDecoder.decode(
            response2.getValue(), function2.getOutputParameters());

System.out.println((values.get(0)).getValue());
print always 32

System.out.println((values.get(1)).getValue());
print the array's length

System.out.println((values.get(2)).getValue());
print the first item into the array

If I call the getter inside web3js all wors fine.

If I call this function in web3j

function getSub() external pure returns(uint256[4] memory) {
    uint256[4] memory a = [uint(1),2,3,4];
    return a;
}

all works fine


texts:
Does the concept of mining exist if an application is designed with a blockchain in the banking domain?

From what I understand from mining with respect to Bitcoin, the miners keep on creating valid blocks for their work. Then a few might get rewarded with Bitcoin for their effort.

I'm trying to understand how mining would work in banking transaction terms. If they exist, what will they get for the work they do?


texts: what does "Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" mean

texts:
In this question the OP is running into a warning upon using the keccak256 function in Solidity:

  Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.

uint256 _unixTimestamp;
uint256 _timeExpired;

bytes32 output = keccak256(msg.sender, _unixTimestamp, _timeExpired);

What is the rationale behind this error - why do I need to use abi.encodePacked and what does it do in comparison to using it just like shown above?


texts: Get all accounts that have interacted with contract

texts: Other than looping through every transaction since the contract was mined is there a way to get every account that has interacted with a contract (or sent a transaction to an address) conveniently using the standard web3 API that will work for all browsers (Mist/Metamask/Parity)?


texts: If I previously had an account in my Ledger Waller Ethereum desktop app called 'rocket funds', how would this appear in a newly restored ledger or can I only access the funds/wallets by manually creating the custom accounts again? I assume the account names are stored on the actual device.


texts: Error trying to deploy a contract that requires a token in the constructor

texts:
I have a contract (Factory) that needs to store and interact with a ERC20PresetMinterPauser token but I get an error when i try to deploy it. :
How can I deploy my factory contract?
this is the error:
  1) addMintRequest test
       should add a mint request:
     Error: invalid ENS name (argument="name", value="<SignerWithAddress 0x3b8486Cc119fB849DC5Dbf92dDe42f703E1Ae036>", code=INVALID_ARGUMENT, version=providers/5.0.21)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:205:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:217:20)
      at Logger.throwArgumentError (node_modules/@ethersproject/logger/src.ts/index.ts:221:21)
      at EthersProviderWrapper.<anonymous> (node_modules/@ethersproject/providers/src.ts/base-provider.ts:1365:20)
      at step (node_modules/@ethersproject/providers/lib/base-provider.js:46:23)
      at Object.next (node_modules/@ethersproject/providers/lib/base-provider.js:27:53)
      at fulfilled (node_modules/@ethersproject/providers/lib/base-provider.js:18:58)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

contract code (constructor)
contract Factory is Ownable, AccessControl {

  ERC20PresetMinterPauser public token;

  bytes32 public constant CUSTODIAN_ROLE = keccak256("CUSTODIAN_ROLE");
  bytes32 public constant MERCHANT_ROLE = keccak256("MERCHANT_ROLE");

  enum RequestStatus {PENDING, CANCELED, APPROVED, REJECTED}

  mapping(bytes32=>uint) public mintRequestNonce;

  // requests
  Request[] public mintRequests;
  Request[] public burnRequest;

  struct Request {
    address requester;
    uint amount;
    address depositAddress;
    string txid;
    uint nonce;
    uint timestamp;
    RequestStatus status;
  }

  constructor(address custodian, address merchant, address _token) {
    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);

    _setupRole(CUSTODIAN_ROLE, custodian);
    _setupRole(MERCHANT_ROLE, merchant);

    token = ERC20PresetMinterPauser(_token);
  }
//...

test:
const {expect} = require("chai");
describe("addMintRequest test", function () {
  it("should add a mint request", async function () {
    const GCLP = await ethers.getContractFactory("GCLP");
    const Factory = await ethers.getContractFactory("Factory");
    const token = await GCLP.deploy();

    [owner, merchant, custodian, acct1] = await ethers.getSigners();

    await token.deployed();

    console.log(token.interface);
    const factory = await Factory.deploy(custodian.address, merchant.address, token.address);

    await factory.deployed();

    expect(await factory.addMintRequest(1000, "txid", acct1)).to.equal(true);
  });
});

instead of token.address in the arguments i have tried only 'token' 'token.instance' etc...


texts: Solidity Contract Needs Another Contract's Address

texts:
Is there a way for a Solidity contract to programmatically find out another solidity Contract's address?

Right now I'm letting Contract A know about Contract B by hard-coding the address of B into the constructor of A, like so:

BContract = MyNFT721(0xA8978c16E9640508947A93B4Df5b49c8740B752D);

But every time I make edits/updates to B I have to redeploy it, which means it gets a new address - and then A can no longer find it.

It'd be great if A could programmatically find the newly updated address of B, cause right now I have to deploy them separately, deploying B first, then getting its new Address, then hard-coding this new address into A, and then redeploying A.

Its kinda crazy.

(same thing for the ABI's by the way: every time I do an update, I have to copy-paste the new ABI into the calling contract's code...)

=======================

UPDATE:

I resorted to using the Migrations approach - but from past experience I wouldn't recommend it for deploying to the mainnet. I just remember it kept error'ing out.
I think it had to do with how long it was taking for Blocks to be approved/mined.

Remember that Contract 1 has to be deployed first, at which point its address becomes known and available - and can then be passed into Contract 2, which is the next contract in the Migration files cue to be deployed.

So they're basically chained to one another.

But if the first deployment times out - or anything else goes wrong or "too long" with it, the 2nd. deployment will suffer/fail.

So while this solution works well for development - meaning deploying contracts locally to Ganache, it has NOT worked for me on live MainNet deployment.

But I supposed that when you get to that last "MainNet" stage (or even Ropsten or Rinkeby) - after thoroughly testing everything out locally,  you can then just do your deployment manually, one contract at a time - and be good to go.


texts: Does running a Geth RPC server locally also require having a full Ethereum node?

texts:
I've been trying to learn about smart contracts and attempting to work through a few examples.  Specifically, I found this one about creating an Oracle -- https://github.com/axic/tinyoracle.  The instructions specify to start an RPC server using the command

geth --rpc --rpcaddr "127.0.0.1" --rpcport "8545" --unlock 0

I notice that this produced a lot of output, including lines like below

WARN [06-14|15:17:56] Synchronisation failed, retrying         err="block download canceled (requested)"
WARN [06-14|15:18:19] Synchronisation failed, retrying         err="block download canceled (requested)"
INFO [06-14|15:19:18] Imported new block headers               count=192 elapsed=969.455ms number=192 hash=5221b7…6c6c14 ignored=0
INFO [06-14|15:19:18] Imported new block receipts              count=192 elapsed=1.612ms   number=192 hash=5221b7…6c6c14 size=768.00B ignored=0
INFO [06-14|15:19:20] Imported new block headers               count=192 elapsed=26.918ms  number=384 hash=5377ec…85cf44 ignored=0
INFO [06-14|15:19:20] Imported new block receipts              count=192 elapsed=1.504ms   number=384 hash=5377ec…85cf44 size=768.00B ignored=0
INFO [06-14|15:19:21] Imported new block headers               count=192 elapsed=27.780ms  number=576 hash=28e01b…6ebada ignored=0

This seems to keep going.  I eventually interrupted the process.  I'm not 100% sure on what's happening but it looks like an Ethereum node is getting downloaded to my local machine.  Is there a way to run a Geth RPC server without downloading an entire node?


texts: Transfer ether from one account to another using smart contract

texts:
I`m trying to transfer ether from account A to a smart contract and from the smart contract to account B. I wrote some code that approximately works on Remix IDE, but I completely got lost with the msg.value.
pragma solidity ^0.5.11;
contract MyFirstContract
{
    function() external payable { }
        function getBalance() public view returns(uint)
        {
            return address(this).balance;
        }

    function send(address payable _To )public payable returns (bool)
    {
     _To.transfer(msg.value);
     return true;
    }
}

This works fine if I insert an input in the value textbox on Remix, as shown in the next image:

Remix IDE value
But I need to transfer ether using my Dapp which based on C#. So, how am I supposed to set the msg.value there? Can I do it using Solidity?


texts: Why do people use uint8 for constant variables such as decimals for tokens, isn't it better to use uint256? the EVM would need to use additional calls to go from 256/32bits to 8 and therefore increase gas costs


texts: deploying a simple ERC721 contract: transaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P

texts:
You can check out the code here: https://github.com/lopeselio/Chainlink-VH-DynamicNFT
Command:
truffle migrate --reset --network rinkeby -f 3

Then response is as follows:
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Starting migrations...
======================
> Network name:    'rinkeby'
> Network id:      4
> Block gas limit: 10000000 (0x989680)

3_NFT_simple.js
===============

   Deploying 'NFTSimple'
   ---------------------

Error:  *** Deployment Failed ***

"NFTSimple" -- transaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P.

    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:365:1
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at Migration._deploy (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:74:1)
    at Migration._load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:61:1)
    at Migration.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:212:1)
    at Object.runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:150:1)
    at Object.runFrom (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:110:1)
    at runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:258:1)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:228:1)
    at Command.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/command.js:136:1)
Truffle v5.2.5 (core: 5.2.5)
Node v15.5.0

My truffle-config.js:
const HDWalletProvider = require('@truffle/hdwallet-provider');
require('dotenv').config();
// require('babel-polyfill');
// require('babel-register');

const mnemonic = process.env.MNEMONIC
const url = process.env.RPC_URL

module.exports = {
  networks: {
    cldev: {
      host: '127.0.0.1',
      port: 8545,
      network_id: '*',
    },
    ganache: {
      host: '127.0.0.1',
      port: 7545,
      network_id: '*',
    },
    kovan: {
      provider: () => {
        return new HDWalletProvider(mnemonic, url)
      },
      network_id: '42',
      skipDryRun: true
    },
    rinkeby: {
      provider: () => {
        return new HDWalletProvider(mnemonic, url)
      },
      network_id: '4',
      skipDryRun: true,
      networkCheckTimeout: 999999
    },
  },
  compilers: {
    solc: {
      version: "0.6.12",
      optimizer: {
        enabled: true,
        runs: 1
      }
    }
  },
  api_keys: {
    etherscan: process.env.ETHERSCAN_API_KEY
  },
  plugins: [
    'truffle-plugin-verify'
  ]
}


texts: Mist hang at downloading new node in rpc mode at first run

texts:
I am trying to use Mist to connect to geth rpc.

First getting geth up running:

geth --datadir data --rpc

and then run mist with rpc:

/Applications/Mist.app/Contents/MacOS/Mist --rpc http://localhost:8545

After Mist opened, the Download new node... showed up and it just won't enter the main UI. Mist don't have to sync the blocks since it's a local testnet. How long do I have to wait for it disappears?


texts:
I've sent some ETH from the Ledger Live app to an exchange but I only used 1 Gwei and now the transaction is pending. It's been 20 hours. Will the transaction run out of gas eventually or will it go through?

I know it's possible to cancel a transaction with MEW but since I used Ledger Live, I'm not sure how to do it. Or would it just be better to wait?

Thanks


texts: use metamask to send eth to many adresses

texts:
i want to use metamask / myetherwallet  and not mist because of sync problemems to send token to 100 addresse

i have this code (solidity) but i dont know how to implement it

please help me

link to the code : https://pastebin.com/hjKmsMp8


texts: Method overloading conflicting with transaction object

texts:
In my contract there is a buy method with 1 argument being overloaded by a 2nd one with 2 arguments:

function buy( uint id )
function buy( uint id, uint quantity )

Now I want to call the 1st method via web3, but also provide the options for the underlying sendTransaction, to specify the from, value and gas values.

How can I call this and prevent the 2nd buy method with 2 arguments to be called as happens currently with:

myContract.buy(id, { gas: 100000 })


texts: Traversing transaction within a contract

texts: Is it possible to get an address' transaction history within a contract using solidity? If it is possible, how can one go about it?


texts: Solidity : Error when pushing an address into a dynamic address type array

texts:
I'm trying to insert an address into an address type dynamic array. It works well when I do the operation inside a function. There are no errors and the elements are properly pushed into the array.

pragma solidity ^0.5.2;

contract Random {
    address[] public participants;

    function addParticipant() public {
        participants.push(0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c);
        participants.push(0x583031D1113aD414F02576BD6afaBfb302140225);
        participants.push(0xdD870fA1b7C4700F2BD7f44238821C26f7392148);
    }
}

But when I try to do it without a function it shows an error.

  Error: Expected identifier but got '('

pragma solidity ^0.5.2;

contract Random {
    address[] public participants;

    // function addParticipant() public {
        participants.push(0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c);
        participants.push(0x583031D1113aD414F02576BD6afaBfb302140225);
        participants.push(0xdD870fA1b7C4700F2BD7f44238821C26f7392148);
    // }
}

Please advise.


texts: I've tried three times, keeps cancelling for running out of gas. I can't change the amount of gas, it's static at 21000. Honestly not sure what to do.


texts: How to write a first solidity contract in remix - ide online?

texts:
I have written a small contract which is just to set and get a name. I choose JavaScript VM, when I deployed it and set my name as "vijay" and when I selected getname. I didn't got output. It shows error as attached in below image.

Please Give me a solution. Thank you.


texts: How to sign a transaction using web3.js and ethereumjs-tx on the BSC testnet

texts:
How do I sign and send a transaction using web3.js and ethereumjs-tx on the BSC testnet?
I have found this question and answer:
Is it possible to send transaction in Binance Smart Chain using web3 and ethereumjs-tx?
This only seems to cover the mainnet:
const common = Common.default.forCustomChain('mainnet', {
  name: 'bnb',
  networkId: 56,
  chainId: 56
}, 'petersburg');

If I substitute the chainId for 97 (BSC Testnet Id) and replace 'petersburg' with Chapel. I get 'Error: Chain with name Chapel not supported'
Any help is greatly appreciated. Thanks in advance.


texts: Storing encrypted data and decrypt on-chain

texts:
The idea was to store the encrypted number of tokens,and when user was sending his private key, smart-contract would decrypt the data and perform an action of sending tokens to someone else. The catch is, user doesn't have his own ethereum address, so I need another private key generated for this and everything will be performed by one account from back-end. Also this will be one-time action - once private key sent and tokens released there will be no need for this private key anymore, so it's ok for it to be exposed to public chain.

I've found the only solution is to encrypt off-chain, keep it in smart-contract and for someone to read it there and decrypt again off-chain, but I need to perform an action after this so it doesn't fit here.

Hope for any suggestions, thanks.


texts: GSN relay transaction call not being allowed to happen

texts:
Rejected relayTransaction call - should not happen. Reason: {"code":-32000,"message":"gas required exceeds allowance (0)

Getting this error, wondering if I'm missing something. I have set a deposit of 2 eth on the relayhub for the address in question and properly wrapped the web3 connection into a provider that is utilizing GSN. The paymaster is the generic accept-everything paymaster listed here, https://docs.opengsn.org/contracts/addresses.html#ethereum
Just wondering if there is an additional step.


texts: After stopping ethereum private networks, Are account, ethers etc persisted?

texts:
Does private network persist ether, accounts and contracts when they are closed?

I have started a private network with following command

geth --datadir=./chaindata --networkid 15 --ipcpath /Users/{user-name}/Library/Ethereum/geth.ipc

I have created and account and mine some ether.

Afterwards, I have stopped the private network and when I have restarted it. Everythings was gone. Is it normal? Is there a way to persist private network even it is stopped.

p.s. I have stopped private network with "kntrl + c". Maybe There is another way for graceful stop.


texts:
I am writing a smart contract to be the backend of a game. Instead of using a mapping, I have decided to use an array to store the addresses of accounts who have paid my contract. (I know it is common practice to use a mapping for this but I find them to be confusing)

address[] paidPlayers;

As players join, their address is added via the following function.

function addPlayer(address player) constant returns (address[]) {
   paidPlayers.push(player);
   return paidPlayers;
}

Periodically, when a round in the game is completed, I want my contract to reset.  I thus need a way of emptying my paidPlayers array.  How is this done in solidity?  Is there anything like the javascript

paidPlayers = [];

I have found methods for deleting a specific element but not the array as a whole.


texts: Run geth and mine in different locations?

texts:
In one location I have renewable power, at my friend's place, but the internet is filtered, so p2p/geth seems to be blocked.

At home I have unfiltered net.

Is it possible to run geth at home (Windows), but mine at her place (Windows)?


texts: Token with whitelisting on crypto exchange

texts:
we are planing to implement a ERC-20 token with whitelisting (only whitelisted addressees, can trade tokens). And we are planing to list this token on some exchanges. Is this possible? What must be done for the exchange to work with the whitelisting:

Add the exchange address as whitelisted?
Each customer that participates on the exchange must have his exchange wallet whitelisted by our platform?

Will exchanges even list this type of token?


texts: Unable to call setter function in solidity using Infura

texts:
Solidity code

contract Greeter {
string public greeting;

function Greeter() public {
    greeting = 'Hello';
}

function setGreeting(string _greeting) public {
    greeting = _greeting;
}

function greet() view public returns (string) {
    return greeting;
}

I've deployed the contract through remix - 0x5b62B76bE6Ec44724f8832F6f4402e9128C6309a and receive the response from contract.functions.greet().call() as 'Hello'. I've whitelisted the contract address in Infura.

However on calling the function tx_hash = contract.functions.setGreeting('Nihao').transact(), I receive the following error.

Traceback (most recent call last):
File "<input>", line 1, in
<module>
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/contract.py", line 1151, in transact
**self.kwargs
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/contract.py", line 1454, in transact_with_contract_function
txn_hash = web3.eth.sendTransaction(transact_transaction)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/eth.py", line 268, in sendTransaction
[transaction],
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/manager.py", line 109, in request_blocking
response = self._make_request(method, params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/manager.py", line 92, in _make_request
return request_func(method, params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 50, in apply_formatters
response = make_request(method, params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/gas_price_strategy.py", line 18, in middleware
return make_request(method, params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 48, in apply_formatters
response = make_request(method, formatted_params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/attrdict.py", line 18, in middleware
response = make_request(method, params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 48, in apply_formatters
response = make_request(method, formatted_params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/normalize_errors.py", line 9, in middleware
result = make_request(method, params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 48, in apply_formatters
response = make_request(method, formatted_params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 48, in apply_formatters
response = make_request(method, formatted_params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/middleware/exception_retry_request.py", line 87, in middleware
return make_request(method, params)
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/providers/rpc.py", line 68, in make_request
**self.get_request_kwargs()
File "/Users/siddharth/venv/lib/python3.6/site-packages/web3/utils/request.py", line 27, in make_post_request
response.raise_for_status()
File "/Users/siddharth/venv/lib/python3.6/site-packages/requests/models.py", line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://ropsten.infura.io/v3/cf37a080c46b470b9c828359ece27ba8

Full code - https://web3py.readthedocs.io/en/stable/contracts.html

Where am I going wrong? Thank you.


texts: Extract v, r and s from signature for use with pyethereum.transaction library

texts: Given an unsigned transaction, constructed using pythereum.transaction, and a signature, created by signing the transaction's hash with a private key, how do I extract the v, r, s values from the signature so they can be added to the unsigned transaction to sign it?


texts: I'm new to block chain technology. I'm trying to store and read blocks using testRPC along web3.js. I'm able to get the latest block data but not able to fetch previous blocks data. Please some one tell me how can I get it.


texts: how to get revert at the previous timestamp of evm in testrpc

texts:
I am testing my contracts so at some point i need to increase the timestamp of evm that i achieve through evm_timeIncrease but now i want to execute some functions on the basis of current timestamp but because of evm_increaseTime it get changed and continues from the new timestamp.

I try evm_revert , evm_snapshot but nothing get worked .
Please suggest any solution

testrpc v4+

node.js v8.4.0

truffle v3.4.3


texts: Is it legal create an algorithmic trading cryptocurrency fund for social groups around the globe to pool in their money? What is the viability of this project in terms of regulatory compliance?


texts: go generate command on faucet.html not working

texts:
I forked go-ethereum, i made some modification to the faucet.html, and used 'go generate' command to persist the changes to Geth, but when i use Puppeth to generate my faucet, the changes i made on the faucet.html does not reflect.

I have tried to make the modification severally on faucet.html, persisting my modification using 'go generate' command and generating my faucet, yet my changes does not reflect.

please i need urgent help on how to make changes to faucet.html, persist the changes and to see the changes reflect on my generated faucet. Thank you.


texts: What is the most efficient integration of off-chain tools like Matlab or R into Ethereum? (in order to do off-chain calculations and reduce gas costs)


texts: How to send erc20 tokens through web3 on nodejs

texts:
My transactions go through without errors, while they're pending the data field shows the amount of tokens I'm sending, but when the transaction goes through the data field is empty. Here is my code:
const abi = My_Contract.abi
const web3 = new Web3('https://rinkeby.infura.io/v3/INFURA_PROJECT_ID')
const gasprice= await web3.eth.getGasPrice()
var count = await web3.eth.getTransactionCount(myAccount)
const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

var amountInDecimal = 166
const txObject = {
  from: myAccount,
  nonce: "0x" + count.toString(16),
  to: '0x153ed6D60AcaE6E915907233F10663462FF67622',
  gas: 100000,
  value:"0x0",
  data:token.methods.transfer('0x153ed6D60AcaE6E915907233F10663462FF67622',
  web3.utils.toHex(web3.utils.toWei(amountInDecimal.toString(), "ether"))).encodeABI(),
  gasPrice:gasprice
}
console.log(txObject)
web3.eth.accounts.signTransaction(txObject, privateKey, (err, res) => {
  if (err) {
    console.log('err',err)
  }
  else {
    console.log('res', res)
  }
  const raw = res.rawTransaction
  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    if (err) {
      console.log(err)
    }
    else {
      console.log("txHash:", txHash)
    }
  })
})

When I call the transfer function through truffle console it works perfectly. Please help, I am dying


texts:
const { ethers } = require('ethers');
console.log(ethers.BigNumber.isBigNumber(totalBalance));

Returns true
const { ethers } = require('ethers');
console.log(ethers.BigNumber.toNumber(totalBalance));

ethers.BigNumber.toNumber is not a function
According to the docs
https://docs.ethers.io/v5/api/utils/bignumber/#BigNumber
toNumber() is a function on BigNumber.
Are the docs wrong or is maybe toNumber called wrong?


texts: Have a connection problem with smart Contract using web3.js

texts:
Anyone that can help me in how to interact with our smartcontract
  using web3.js.

I tried below code but this not work:
This the code that I am using:

if (typeof web3 !== 'undefined')
{
  web3 = new Web3(web3.currentProvider);}
else {
                web3 = new Web3(new Web3.providers.HttpProvider("htpp://localhost:8545"));
            }

            web3.eth.defaultAccount = web3.eth.accounts[0];

            var careercertificateContract = web3.eth.contract(CODE ABI);

        var careercertificate = careercertificateContract.at('0xe1EeCd0a848Bf59509F32f0c97B61d34727C84AB');
        console.log(Certificate);

        $("#button").click(function(){

            Certificate.createCertificate($("#id").val(), $("#fecha").val(), $("#NombreAlumno").val(), $("#RutA").val(), $("#NombreInstitucion").val(), $("#RutI").val(), $("#titulo").val(), $("#FechaTitulacion").val(), $("#NumeroRegistro").val(), $("#CodigoVer").val(), $("#TotalHash").val(),);

        });


texts:
Right now I have a sequence if ids used for mapping in contract:

mapping (uint => Document) documents;
uint documentsCount;

which is incremented for every new document:

function createDocument() returns (uint docId) {
    docId = documentsCount++;
    documents[docId] = Document(...);
    Created(msg.sender, docId);
}

When I make this call I receive a transaction id (tx_id), which is uniq and finalized if I understand correctly. Also I can get docId if I listen for Created events.

This docId depends on execution order, and in distributed systems such as Ethereum, we should wait until it's finalized in blockchain.

I wonder what should I do if I want to use it as a reference in further transactions? Say I have addSignature(uint docId, bytes sign) transaction next to it. Or simple read, like getState(unit docId).

If I call it just after first transaction, it still possible that in blockchain it will be executed against different block and wrong document. Or what if pass this docId to a different machine which can have slightly different order or transactions at this moment.

What is a best practice to generate a reference id at this case?


texts: Can't use object of web3.eth.compile.solidity(source)

texts:
I have the following code (source is the solidity contract to be compiled).

var compiled = web3.eth.compile.solidity(source);
var code = compiled.code;
var abi = compiled.info.abiDefinition;

However compiled.code and compiled.info.abiDefinition return undefined. What am I doing wrong?


texts:
I need to determine an expiry date for a contract a for this I use the foloowing code as the constructor of the contract :

constructor(address _recipient, uint256 duration)
        public
        payable
    {
        sender = msg.sender;
        recipient = _recipient;
        expiration = now + duration; // Here we determine the expiry date.
    }

However when I want to determine this expiry date for one day (60 * 60 * 24 = 86400 seconds) at the time of deploying this contract using the following web3.js commands :

const thisContract = new web3.eth.Contract(abi);
thisContract.deploy({
        data: bytecode,
        arguments: [ "0x84f0c8fC2F6bc8394EB77BaAAe89cB6e12C048C2", [86400/*here is duration*/] ]
    }).send({
       from: "0x3455D7167A2EE2d660EE85F8e90C6b3B1cCB7163",
       gas: 5000000 ,
       gasPrice: '3000000000',
       value: 5000
    },
    function(error, transactionHash) {
        console.log(error);
        console.log(transactionHash);
        console.log('function exec');
    }).then(function(newContractInstance) {
    console.log('Contract Instance:' + newContractInstance.options.address);
});

Then, I receive the following error concerning converting the Integer to Big Number :

  Error: [number-to-bn] while converting number [3600] to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported. Given value: "3600"

And here is the screen shot:


texts: I'm wondering how transactions are handled at Bitcoin/Ethereum/... . Miners send their found blocks to a fixed number of other miners who will redistribute them if they don't already have another version of this block. My question now is how transactions are handled. A transaction is sent to a miner who tries to mine it into a block. Does the miner also distribute the transaction in the network so that other miners can also try to mine this transaction, or does only the miner know about the transaction where the transaction was started inital?


texts: ETH token transfer Fail and error is: Warning! Error encountered during contract execution [Bad instruction]

texts:
sometimes I am encountering a problem where I am trying to send tokens (USDT in this particular case) to other address and the transaction fails, because of "Warning! Error encountered during contract execution [Bad instruction]" error as shown on etherscan.
I tried to send USDT tokens to another address, I set Gas limit: 130,000, gas price: 200 Gwei. Called transfer function, but it Failed with that error.

What could be possible issue and how could I avoid this from happening again? As for this particular failed transaction 40 USD was paid...


texts: AMD Radeon HD 7350 / Asus HD 7350 Hash Rate

texts:
What hash rate can I expect from an AMD Radeon HD 7350?

Additional Info:
CPU: Intel i5-3450 @ 3.10GHz / 4 CPUs
RAM: 4gb (4096MB)
MoBo: Asus CM6630_CM6730_CM6830
OS: Windows 10 Pro

Any inputs are highly appreciated! Thanks in advance.


texts: How i can bun my tokens i tried this code but getting error

texts:
In last there is code of burning tokens please help me i am getting this error
TypeError: Indexed expression has to be a type, mapping or array (is function (address) view returns (uint256)) --> Token.sol:51:17: | 51 | require(balanceOf[msg.sender] >= _value); | ^^^^^^^^^
pragma solidity ^0.8.2;

contract Token {
    mapping(address => uint) public balances;
    mapping(address => mapping(address =>uint)) public allowance;

    uint public totalSupply =10000000000 * 10 ** 18;
    string public name = "The Mouse";
    string public symbol = "MIK";
    uint public decimals = 18;

    event Transfer(address indexed from, address indexed to, uint_value);
    event Approval(address indexed owner, address indexed spender, uint_value);
    constructor(){
        balances[msg.sender] = totalSupply;
    }

    function balanceOf(address owner) public view returns(uint){
        return balances[owner];

    }

    function transfer(address to, uint_value) public returns(bool){
        require(balanceOf(msg.sender) >=_value, 'balaNce too low');
        balances[to] +=_value;
        balances[msg.sender] -=_value;
        emit Transfer(msg.sender, to,_value);
        return true;

    }

    function transferFrom(address from, address to, uint value) public returns(bool){
        require(balanceOf(from) >= , 'balance tOo low');
        require(allowance[from][msg.sender] >= _value, 'allowance too low');
        balances[to] += _value;
        balances[from] -= _value;
        emit Transfer(from, to, _value);
        return true;

    }

    function approve(address spender, uint value) public returns(bool){
        allowance[msg.sender][spender] = _value;
        emit Approval(msg.sender, spender , _value);
        return true;
    }

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

        balanceOf[msg.sender] -= _value;
        totalSupply -= __value;
        return true;

    }

    function burnFrom (address _from, uint256 _value) public returns(bool success) {
    require(balanceOf[_from] >= _value);
    require(_value <= allowance[_from][msg.sender]);

    balanceOf[_from] -= _value;
    totalSupply -= _value;

        return true;

    }

}


texts:
I've been trying to understand the limits of the stack and how it works. It seems like the "Stack too deep" error only happens if there is an assembly block in the function. Without an assembly block, I have declared up to 27 uint variables with no problem.
uint one = 1;
uint two = 2;
uint three = 3;
uint four = 4;
    .
    .
    .
uint twentyfive = 25;
uint twentysix = 26;
uint twentyseven = 27;

However, if I add an assembly block, with the following simple operation, then I can't have more than 20 uint variables without getting the "Stack too deep" error.
assembly
{
    let result := mul (5, 4)
}

If I use uint variables in the MUL operation, then my limit drops to 19 uint variables in order to prevent the "Stack too deep" error.
assembly
{
    let result := mul (five, four)
}

Even with a long, complicated assembly operation, as long as there are no variables in it, I can have lots of uint variables declared. (Maybe this value is computed at compile-time.)
assembly
{
    pop (mul (mul (mul (mul (mul (mul (mul (mul (1, 2), 3), 4), 5), 6), 7), 8), 9))
}

But if I use one variable in the assembly operation, the limit drops to 10 uint variables, or else compilation fails with "Stack too deep".
assembly
{
    pop (mul (mul (mul (mul (mul (mul (mul (mul (1, two), 3), 4), 5), 6), 7), 8), 9))
}

Why is that? What is the relationship between variables declared in a function and the types of assembly operations that are performed in the function?
How many elements does the stack hold?
What size is each stack element? (32 bytes, I would assume.)
What is the stack used for?


texts: I have 35 ETH. Etherscan shows this correctly, but MyEtherWallet displays 0.013 ETC. I did nothing. I just downloded Mist and started syncing.


texts: Scripts : what's the difference between exec file.js and js file.js?

texts:
The doc says that scripts can be executed with : geth --exec 'loadscript("script.js")' attach, but in the example script they give right after, they say to use geth js script.js 2>>geth.log.

What is the difference between the two ?


texts: How to transacting with a smart contract using web3j in Android?

texts:
i used web3j to Transacting with a smart contract.
this is my Contract function which i want to intertact with.

function usersRegister(string _id, string _password){
    Equipment e = equipments[msg.sender];
    e.users[e.usersNum++] = User({id: _id, password: _password, registerTime: now});
}

and this is my code in Android using web3j

Web3j web3j = Web3jFactory.build(new HttpService(url));
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                        equipmentAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
                BigInteger nonce = ethGetTransactionCount.getTransactionCount();
BigInteger gasPrice = Contract.GAS_PRICE;
BigInteger gasLimit = Contract.GAS_LIMIT;

List<Type> inputParameters = new ArrayList<>();
Type usersId = new Utf8String(_usersId);
Type usersPassword = new Utf8String(_usersPassword);
inputParameters.add(usersId);
inputParameters.add(usersPassword);
Function function = new Function("usersRegister",
                        inputParameters,
                        Collections.<TypeReference<?>>emptyList());
String functionEncoder = FunctionEncoder.encode(function);
Transaction transaction = Transaction.createFunctionCallTransaction(
                        equipmentAddress, nonce, gasPrice,
                        gasLimit, contractAddress, new BigInteger("0"),
                        functionEncoder);
EthSendTransaction transactionResponse =
                 web3j.ethSendTransaction(transaction).sendAsync().get();

but i get "null" in transactionResponse.getTransactionHash()

someone know what's wrong with my code?thx for help :x


texts: Can't add peers outside of local machine

texts:
I am able to spin up as many nodes on the same machine as I would like and have them peered in the same private blockchain network.  But when I try to use addPeer() on a separate EC2 instance, I am having no success.

One of the nodes is on block 16000 and the other is on block 50, and I want to sync the 50 block node to the 16000 block node.

Security Groups are set up appropriately, what are some other possible reasons for my failure in using addPeer()?


texts: Can you selfdestruct a contract more than once?

texts: I read the Contract's state after a selfdestruct thread, but it doesn't answer the question whether you can selfdestruct multiple times.


texts: Deploy contract to Kovan with brownie and infura

texts:
I'm trying to simply deploy a smart contract in Kovan network, i've used the export of the ID using export WEB3_INFURA_PROJECT_ID=xxxx but i'm getting this error
ValueError: The method eth_sendTransaction does not exist/is not available

Taking a look into infura documentation, that method is not avaible. What i'm doing wrong?


texts: What's the Solidity statement to print data to the console?

texts: Sometimes it would be really helpful to be able to see string representations of variable values in the Geth console, like of argument values in functions. Can I somehow print them to the Geth console?


texts: Can oracles send data to smart contracts on multiple blockchains?

texts: Can oracle implementations like Oraclize and Reality Keys work with two different blockchains? More precisely, if I have a custom data source and my own oracle running on top of it, can that oracle determine the source of the API call and send data accordingly? Can I design a permission layer in this oracle to allow/deny API calls from a specific address?