How to manually burn tokens on BSC network - blockchain

I have a token contract deployed on Binance Smart Chain and want to burn some of the tokens manualy, thus to execute following function call from some kind of console.
myContract.burn(10000);
I have ABI and bytecode
How and where can I execute this?

If the burn() function has a public or external visibility modifier, you can execute it by submitting a transaction containing the function signature and the argument value(s) in the data field.
One of the ways is to build the data field value manually or semi-manually
const data = web3.eth.abi.encodeFunctionCall({
name: 'burn',
type: 'function',
inputs: [{
type: 'uint256',
name: '_amount'
}]
}, [10000]);
which returns
0x42966c680000000000000000000000000000000000000000000000000000000000002710
42966c68 is the function signature
2710 is hex value for 10000 (dec)
and pass it to any wallet that supports custom data field (e.g. MyEtherWallet).
Another way is to instantiate your contract with web3.eth.Contract and execute the function from there. This generates the data field for you and if you've configured your web3 instance correctly, it also uses your private key to sign the transaction and broadcasts it to the network.
const contract = new web3.eth.Contract(jsonInterface, contractAddress);
contract.methods.burn(10000).send({from: yourAddress});

Related

Where to get a signature for smart contract interaction via block explorer?

In BSC (Binance Smart Chain) contracts I often meet a signature parameter but I have no idea where to get it.
If you think that it is a signature message which you need to sign with Metamask - it's not. It's just a one of parameters of the function I need to run.
Example can be found there, just look at the purchase function and you'll see signature as a last parameter - https://bscscan.com/address/0xabc306ae80595f6c7748b81d6c2efc48b32a9e22#writeContract
Signature is a result of signing a message with a private key.
Example from the web3 docs page:
message Hello world
signed with the private key of address 0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe
results in signature 0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400
A contract can then verify if the signature and message (or hash of the message) can be recovered back to the signer address (cannot get the private key).
For example the OpenZeppelin ECDSA library is a developer-friendly wrapper for the low-level (EVM assembly) recovery method.
Unfortunately the contract linked in the question is passing the signature to another unspecified contract for the recovery, so I was unable to find the specific message that they're validating against and the actual recovery snippet that they're using. However, you can find more info about the signing process and on-chain recovery in this answer (the mentioned v, r and s params are literally parts of the whole signature).

How to store a hash of some data in a currently publicly available blockchain?

I have read that blockchains aren't good at storing large files. But you can create a hash of a file and somehow store that in the blockchain, they say. How do I do that? What API or service should I be looking at? Can I do it on bitcoin.org, or does it need to be some special "parameterized" blockchain service of some sort?
In the blogs I've seen touting how cool it is where you can store your data in mysql but store the hash in the blockchain, they don't show how you actually nitty-gritty get the hash into the blockchain, or even what services are recommended to do this. Where is the API? What field do I pass to the hash into?
This is what I think the frontend would look like:
hashedData = web3.utils.sha3(JSON.stringify(certificate));
contracts.mycontract.deployed().then(function(result) {
return result.createCertificate(public_addresskey,hashedData,{ from: account }); //get logged in public key from metamask
}).then(function(result) {
//send post request to backend to create db entry
}).catch(function(err) {
console.error(err);
// show error to the user.
});
The contract might look something like the sketch below.
There is a struct to contain everything but the id. A mapping from hash => Cert for random access (using the hash as id) and a certList to enumerate the certificates in case the hash isn't known. That should not happen because it emits events for each important state change. You would probably want to protect the newCert() function with onlyOwner, a whiteList or role-based access control.
To "confirm" a cert, the recipient confirms by signing a transaction. The existence of a true in this field shows that the user mentioned did indeed sign because there is no other way for this to occur.
pragma solidity 0.5.1;
contract Certificates {
struct Cert {
address recipient;
bool confirmed;
}
mapping(bytes32 => Cert) public certs;
bytes32[] public certList;
event LogNewCert(address sender, bytes32 cert, address recipient);
event LogConfirmed(address sender, bytes32 cert);
function isCert(bytes32 cert) public view returns(bool isIndeed) {
if(cert == 0) return false;
return certs[cert].recipient != address(0);
}
function createCert(bytes32 cert, address recipient) public {
require(recipient != address(0));
require(!isCert(cert));
Cert storage c = certs[cert];
c.recipient = recipient;
certList.push(cert);
emit LogNewCert(msg.sender, cert, recipient);
}
function confirmCert(bytes32 cert) public {
require(certs[cert].recipient == msg.sender);
require(certs[cert].confirmed == false);
certs[cert].confirmed = true;
emit LogConfirmed(msg.sender, cert);
}
function isUserCert(bytes32 cert, address user) public view returns(bool) {
if(!isCert(cert)) return false;
if(certs[cert].recipient != user) return false;
return certs[cert].confirmed;
}
}
The short answer is: "Use Ethereum smart contract with events and don't store hash values in the contract."
On Etherscan your may find a complete contract for the storage of hash values in Ethereum: HashValueManager. As you will see in this code example - things are a bit more complex. You have to manage access rights and here the cost was not important (this contract has been designed for a syndicated blockchain)
Actually it is very expensive to store hash data in a blockchain. When you use an Ethereum contract to store the hash data, you have to pay about 0.03 Euro (depending on the ETH and Gas prize) for each transaction.
It would be a better option not to store the hash value in the contract. A much more cheaper alternative is to emit indexed events in a smart contract and query the events (this is very fast). Information about the events are stored in a bloom filter of the mined block and will be readable forever. The only disadvantage is that an event can't be read from within the contract (but this is not your business logic)
You may read more details here about events and how to fetch them in an application : "ETHEREUM EVENT EXPLORER FOR SMART CONTRACTS" (disclaimer: this article is my blog). Also the complete source code is available on GitHub.
For store there is existing several ways. More interesting question: how would you planning to retrieve and use your data? I assume, you planning go retrieve by some way. Otherwise, if no retrieve - there is no sense to store.
OK. there is 2 ways to store your hashes. I will demonstrate examples within emercoin blockchain.
Store as OP_RETURN UTXO. To do this, use the command "createrawtransaction" by using JSON RPC API or command line interface. Just specify "data" for define UTXO, contains your hash.
In this case, data will be stored within one of unspendable transaction output. This saved data is not indexed, and you need to save TXID for future retrieval. Otherwise, you need rescan the entire blockchain for retrieve your data.
You can store data within indexed NVS-subsystem (Name-Value Storage). to upload, you need run the command "name_new", where hash can be your search key. In future, you can quickly retrieve your data by search key with commands "name_show" or "name_history". Also, there is possible to save your data as DNS-records within emerDNS, and retrieve by DNS UDP requests by protocol RFC1035.
For details, see the doc: https://emercoin.com/en/documentation/emercoin-api

Getting mined blocks instead of the supposed returned values

I've just deployed a Smart Contract using the ethereum wallet.
I got the Smart Contract address , I copied its ABI from remix and verified it on ethereum wallet,it was active and I could see all its methods.
Then I tried to call it from my nodejs server.I did it,I didn't get any error...
But instead of a classic response like the returned values of the methods below I got mined blocks....and this is very weird I think...
How am I supposed to get the methods output(the returns) ?
After that I tried to deploy another contract,this time a very simple one with the same methods name,smart contract name,parameters but without code inside the methods only a basic hard-coded return.When I deployed this contract as well I got the same mined smart contract address...which is weird,in my opinion...
I've been using 1.0.0-beta.46 , nodejs , expressjs
When I said eth wallet I meant...that website generated with puppeth , on /#wallet page
Here is the basic smart contract I tried to deploy second time.The result was the same as the first smart contract.
pragma solidity >= 0.4.22 < 0.6.0;
contract BasicContract {
function function1(uint16 a,uint16 b,uint16 c,uint16 d) external payable returns(uint256){
//a,b,c,d doesn't matter
return 68;
}
//buy a ticket
function function2(uint128 a,uint16 b) external payable returns(uint128){
//a,b doesn't matter
return 94;
}
function function3(uint128 a) external payable returns(bool){
//a doesn't matter
return false;
}
}
There are two ways to invoke a function in a smart contract: through a transaction sent to the network or via a local call.
Transactions don't have return values. What you get back from the library you use to make the transaction is typically the transaction hash. Any return value from the function you invoked is discarded.
A local call doesn't involve a transaction to the network and thus can't change any state. But it does give you a return value.
Which method is chosen by default for most libraries is based on whether the function is state-changing or not. If you mark your functions as view or pure, it tells the library that those functions don't change state and can then safely be just called locally to get a return value. So a simple "fix" for the above code is to make those functions pure. For functions that do change state, you'll want to switch from using return values to emitting events instead, which can be read after the transaction is mined.

Identification of purchased product

I have created coins on test network.Now the confusion is,
I have distributed coins to 100 members,who can use those coins to buy digital products(domains) on my platform.Now the confusion is if all domains are listed for sale for $10(100 coins),and multiple domains got sold,how can I identify which user made payment to me.Because all users can see my wallet address.Is there any way to detect that payment came in for which purchased product?
Make your wallet into a smart contract.
Then checkout the fallback function payable. That function gets called anytime someone sends ether to your contract.
function () payable {
address guyWhoPaiedMe = msg.sender;
}
To figure out who sent you the ether use msg.sender.
You can pass the identifier of a particular product as the input data of the transaction. In this case it will be easy to identify the product against which the payment was made.
web3.eth.sendTransaction
web3.eth.sendTransaction(transactionObject [, callback])
Sends a transaction to the network.
Parameters
1. Object - The transaction object to send:
• from: String - The address for the sending account. Uses the web3.eth.defaultAccount property, if not specified.
• to: String - (optional) The destination address of the message, left undefined for a contract-creation transaction.
• value: Number|String|BigNumber - (optional) The value transferred for the transaction in Wei, also the endowment if it's a contract-creation transaction.
• gas: Number|String|BigNumber - (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).
• gasPrice: Number|String|BigNumber - (optional, default: To-Be-Determined) The price of gas for this transaction in wei, defaults to the mean network gas price.
• data: String - (optional) Either a byte string containing the associated data of the message, or in the case of a contract-creation transaction, the initialisation code.
• nonce: Number - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.
Returns
String - The 32 Bytes transaction hash as HEX string.

How to make smart contract private in quorum

In the 7nodes example (https://github.com/jpmorganchase/quorum-examples/tree/master/examples/7nodes ) for quorum, the smart contract that is deployed is a private contract between node1 and node7. To make it private the script file author used public key passed by private key."sending of a private transaction to generate a (private) smart contract (SimpleStorage) sent from node 1 "for" node 7 (denoted by the public key passed via privateFor: ["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc="] in the sendTransaction call)."
How exactly the key value "ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=" was generated i could not understand?
Also, after the completion of the JS file script1.js, it gave me the Contract transaction send: TransactionHash", and i never got the contract address.
When will the contract address come after the mining is completed ?
How do i recognise that this address is my smart contract address ?
The keys are already generated for the nodes.
When you spin up the environment, each node is assigned a predefined dummy public keys.
this can be found at location : \quorum-examples\examples\7nodes\keys
In 7Nodes example you can see the 256bit private key in raft/nodekey* files and the corresponding 512bit public key in nodename (enode) text in static-nodes.json. Use bootnode to create private and public key pairs. And use constellation-node to generate .pub and .key files.
To answer the second part of your question, to get the contract address you can use eth.getTransactionReceipt(__); and copy the txHash you get (quoted) into the blank.
Then the contract address should come up in one of the fields returned.
Check out this page for more info/details.
The key used here is the public key of transaction manager which is respobsible for sending and receiving private transactions in addition to encrypting communications. You can find this key in file named tm.pub inside data folder of the node alongside its associated private key in file tm.key.