I have successfully compiled and published my contract in the rinkeby testnet with the remix browser compiler. Now I am struggling to call a function of my contract, either because my code is wrong or because it's published on rinkeby?
Can someone please provide me an example how to call this function using javascript and/or directly from the remix compiler:
function balanceOfTestCoin() returns (uint amount){
for (uint i = 0; i < funders.length; i++){
if(funders[i].addr == msg.sender){
return funders[i].amountTestCoin;
}
}
return 0;
}
Right now i am trying it this way:
<script>
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(web3.currentProvider);
} else {
console.log('No web3? You should consider trying MetaMask!')
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var abi = [{...}];
var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at('0x....');
console.log(myContractInstance);
myContractInstance.balanceOfTestCoin(function(amount){ alert(amount) });
//This doesnt work aswell:
alert("My TestCoins: " + myContractInstance.balanceOfTestCoin());
</script>
I am getting invalid address error on the line where I am trying to call the function. I am very thankful for any kind of help.
Related
The problem only occurs in the compiled application, so I guess it's a browser specific specific problem, but I'm not sure:
I have added the following script to a webpage:
async function exportChatAsXMLHelper(params){
let displayname = params[0];
let includeMedia = params[1];
let debug = params[2];
await exportChatAsXML(displayname, includeMedia, debug);
}
async function exportChatAsXML(displayname, includeMedia, debug)
{
let chat = (await WPP.chat.list()).find(m => m.contact && m.contact.name && m.contact.name.includes(displayname));
await WPP.chat.openChatBottom(chat.id);
let msgs = await WPP.chat.getMessages(chat.id, {count : -1});
const log = (obj) => debug && console.log(obj);
log('Total messages: ' + msgs.length);
let count=msgs.length;
for (var i = 0; i < count; i++) {
log('Message number: ' + i);
let message = msgs[i];
let xml='';
xml+= '<message>';
xml+= '<sender>'+ message.from.user +'</sender>';
xml+= '<receiver>'+ message.to.user +'</receiver>';
xml+= '<type>'+ (message.type || '') +'</type>';
if(message.type == 'chat')
{
xml+= '<body>'+ message.body +'</body>';
}
if(message.type != 'chat' && includeMedia)
{
xml+= '<media>';
xml+= '<caption>'+ (message.caption || '') +'</caption>';
xml+= '<filename>'+ (message.filename || '') +'</filename>';
log('Downloading media');
try
{
let mediabody = await mediatoBase64(message.id);
xml+= '<MediaDownloadStatus>success</MediaDownloadStatus>';
xml+= '<base64>'+ mediabody +'</base64>';
}
catch(e)
{
xml+= '<base64></base64>';
xml+= '<MediaDownloadStatus>fail</MediaDownloadStatus>';
}
xml+= '</media>';
}
xml+= '</message>';
alert('before'); //this is still shown
//where is JSCallbackReceiver defined? it is from vb6
window.JSCallbackReceiver.OnWhatsAppXMLReceived(i, count, xml);
alert('after'); //this is not shown
xml='';
}
}
//-----
async function mediatoBase64(msgid) {
let blob = await WPP.chat.downloadMedia(msgid);
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
It works fine on my developer's machine, but throws an error on a client's machine:
Uncaught (in promise) TypeError: Cannot read property 'OnWhatsAppXMLReceived' of undefined https://web.whatsapp.com/ 80
I have added some alerts now to see where exactely it goes wrong.
The alert "before" is shown, the alert "after" is not shown, so the error definitively occurs in
window.JSCallbackReceiver.OnWhatsAppXMLReceived(i, count, xml);
alert('after');
What could I check to see what exactely goes wrong / what is different on the client's machine?
The callback object is defined in VB6 like this:
Private m_JSCallback As clsJSCallbackReceiver
Set m_JSCallback = New clsJSCallbackReceiver
Me.webkit1.AddObject "JSCallbackReceiver", m_JSCallback
Does the error message mean that the browser does not find the object that I added via AddObject?
I am using mobileFx webkit browser which is based on Chromium, but I guess that is not important.
This is what the class clsJSCallbackReceiver looks like in VB6:
Option Explicit
Public Sub OnWhatsAppXMLReceived(ByVal uIndex As Long, ByVal uCount As Long, ByVal uXml As String)
Debug.Print("I was called!")
End Sub
Public Sub SaySomething(ByVal u As String)
MsgBox(u)
End Sub
Thank you!
Edit:
I only happens when compiled.
When I run it in the VB6 IDE, it works fine.
After the error occurs, I can still call
m_JSCallback.SaySomething("Hello!")
, and it will work.
So the object is still alive.
It is just not connected to the browser, I guess.
I found this document, which says this about an example they've given:
"Next, since the Instancing property of the class is PublicNotCreatable, the project must provide a way for a client to instantiate the object. Add a new function in a standard module. Where clsEmployee is the name of the class of interest. Also, this should not be a private module."
And your code seems to contradict that.
The error message explain you that at the line:
window.JSCallbackReceiver.OnWhatsAppXMLReceived(i, count, xml);
the window.JSCallbackReceiver object is undefined.
First to get rid of this error message you chould replace this line with:
if (window.JSCallbackReceiver) {
window.JSCallbackReceiver.OnWhatsAppXMLReceived(i, count, xml);
}
This will not solve you problem, because it just suppress error.
So you then need to investigate why SCallbackReceiver is undefined on your customer's browser.
To get more help, you need to provide source code about JSCallbackReceiver.
I'm writing a JS file to provide functionality to a smart contract. From what I can tell, MetaMask is injecting web3 into the webpage, but when I attempt to create a contract object, my browsers console (brave browser) is stating that web3.eth.Contract is not a constructor.
I've looked in the object provided by my browsers console, and I don't see the Contract constructor. Is this normal? Or do you think web3 may be incorrectly installed? I've hit a wal at this point.
var blockContractJSON = $.getJSON("../build/contracts/Blocks.json", function(data) {
return data;
});
console.log(blockContractJSON)
// console.log(blocksContract)
var blocksContract;
var currentUser;
var web3js;
console.log(web3js);
// console.log(blockContractJSON);
// defines contract address and initializes contract functions
var startApp = function() {
var contractAddress = "0x2520127E14E8A14C67Ee2B561714ADae53D48110";
console.log('got the contract'); <- web3 not passing to this line?
blocksContract = new web3js.eth.Contract(blockContractJSON, contractAddress);
// console.log(blocksContract);
var checkAccounts = setInterval(function() {
if (web3js.eth.accounts[0] !== currentUser) {
currentUser = web3js.eth.accounts[0];
}
}, 100)();
};
// adds in web3
window.addEventListener('load', function() {
console.log('item loaded from page is')
console.log()
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
console.log('using metamask');
console.log(web3)
// Use Mist/MetaMask's provider
web3js = new Web3(web3.currentProvider);
console.log(web3js)
} else {
alert('install metamask')
}
startApp();
});
Works for me
const Web3 = require('web3')
var web3 = new Web3(new Web3.providers.HttpProvider("infuralink"));
const ABI=[];
const Contract = new web3.eth.Contract(ABI,"contractaddress");
Try using Ethereum lib instead (web3-eth)
[https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html][1]
var eth = new Eth('http://localhost:8545');
check first parameter is the abi node of the JSON not the abi metadata
new eth.Contract(contractAbi.abi, CONTRACT_ADDRESS);
invariant.js contains this code:
error.framesToPop = 1;
I've googled all day, I can't found a proper explanation.
MDN didn't mention this as well.
I know the package says:
// we don't care about invariant's own frame
but I tried it at codepen, it still shows that function in error message
function test() {
let myError = new Error('my error')
myError.name = 'my error name'
myError.framesToPop = 1;
throw myError
}
function main() {
test()
}
main()
at test (pen.js:10:17)
Is it really a thing?
I am having problems with my Unity3D calling Firebase Functions function. My code is actually copied from https://firebase.google.com/docs/functions/callable.
My function code is following: (just copied this file actually)
https://github.com/firebase/quickstart-js/blob/a579893cfa33121952aeed9069c1554ed4e65b7e/functions/functions/index.js#L44-L50
and in Unity I have this:
//Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = "message";
data["push"] = true;
//Call the function and extract the operation from the result.
var function = FirebaseFunctions.DefaultInstance.GetHttpsCallable("addMessage");
function.CallAsync(data).ContinueWith((task) => {
if (task.IsFaulted)
{
foreach (var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
Debug.Log(inner.Message);
}
}
}
else
{
Debug.Log("Finished: " + task.Result.Data);
}
});
But I am getting this result:
Response is not valid JSON object.
What am I doing wrong?
Thank you for your help!!!
I was still working on that problem and suddenly it worked. I dont know why to be honest, because the could looks exactely the same and I did not change anything on that.
I'm using something similar to NodeJS called bondi, it's build on the Firefox js engine.. Basically i'm getting this error and I believe it's due to the way i'm referencing "this" in the .Get function below.
Basically there is a tool called SFtpClient. It has the method of "Get", to list the contents of a folder, but I want to change the prototype for this with a drop in include file. I need to change it so that it
a/ retries several times when it fails, and b/ it has a recursive folder listing function.
So I used the prototype to change it - moved .Get to ._Get.
Can anyone see why I would be getting the error:
Jan 23 04:51:34 beta bondi: === this._Get is not a function --- Prio(6) Result(0x0) File(/home/nwo/approot/include/sftpclientenh
when I run the code below?
Thanks
SFtpClient.prototype._Get = SFtpClient.prototype.Get;
SFtpClient.prototype.Get = function(Folder, Retries){
//defaults
if(!Retries) Retries = 5;
if(!Folder) Folder = "~/";
//vars
var FileListing = [];
var connect = function(){
//TODO JRF 19.01.2012 : re-enable this when bondi is fixed
// this.HomeDirectory.replace(/\/?$/, "/");
FileListing = this._Get(Folder);
return true;
}
var i = 1;
do{
var res = false;
try {
res = connect();
}catch(e){
Debug.LogInfo(e.message);
}
i++;
Server.Sleep(i*2000);
} while(res==false && i < Retries);
return FileListing;
}
Try res = connect.call(this) instead of res = connect().