When deploying a smart contract how can I let users in my own platform (mobile or web) interact with it? Let's say I have the following contract:
contract Test {
event Log(address addr);
function logMe () public {
Log(msg.sender);
}
}
In order to use it I must have access to the private and public keys of the user. Is it possible to allow users to interact with the blockchain through their own accounts without the need to have their credentials?
First of all, if you have tried to deploy your contract on blockchain using Remix. And you have used the created API to your created contract, You are actually interacting with your contract with web. You can skim this video to see how to deploy and use call functions inside your contract. I encourage you to watch this video and do its tutorial here.
If you wanna call functions ( Public ) There are three steps so you can use your contracts.
STEP one : Deploy your contract on Blockchain and find your ABI and contract address. For example if you used remix for deploying your contract you see these information by clicking on details in compile tab.
STEP TWO : use web3 and inject it into your web browser ( install Metamask then you have web3 injected to the browser already )
STEP Three: Create a contract API like instance by setting web3 provider and ABI and contract address you got from the step 1.
STEP four: Call your contract functions.
Here is the way you make sure web3 is already injected and you are connected to the right blockchain ( TestNet / MainNet )
var Web3 = require('web3');
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
console.log('Web3 exist!')
console.log(web3)
web3 = new Web3(web3.currentProvider);
web3.version.getNetwork((err, netId) => {
switch (netId) {
case "1":
console.log('This is mainnet')
break
case "2":
console.log('This is the deprecated Morden test network.')
break
case "3":
console.log('This is the ropsten test network.')
break
default:
console.log('This is an unknown network.')
}
})
} else {
console.log('No web3? You should consider trying MetaMask!')
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
Here is the way you can interact with your deployed contract.
var fooContract = web3.eth.contract( YOUR_ABI, (err, ctr) => { return ctr} );
web3.eth.defaultAccount = web3.eth.accounts[0];
$scope.accounts = web3.eth.accounts;
console.log(web3.eth.defaultAccount);
var CONTRACT = fooContract.at('YOUR_Deployed_contract_ADDRESS',(err, ctr)=>{
return ctr;
} )
Now You can easily use the CONTRACT variable to call its public functions.
Calls looks like this :
CONTRACT.contractFunction(params)
PS: Please contact me if you have any question or problem (It's hard to explain all in one post)!