How can I solve the error of Smart Contract? - smartcontracts

I try to Call Smart Contract by NEAR Protocol for the first time.
Please tell me how can I solve the error as follows.
I have created Testnet NEAR Account.
I have compiled "Counter" Contract by using this example "https://github.com/near-examples/rust-counter/blob/master/contract/src/lib.rs".
I have deployed this contract to the testnet by using "near cli", and it has been succeed.
I call "veiw function" of near cli,Error Returned.
% near view Counter get_num '{}'
View call: Counter.get_num({})
An error occured
Error: [-32000] Server error: Account ID Counter is invalid
at /Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:322:31
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Object.exponentialBackoff [as default] (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/utils/exponential-backoff.js:7:24)
at async JsonRpcProvider.sendJsonRpc (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:297:24)
at async JsonRpcProvider.query (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:109:22)
at async Account.viewFunction (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:356:24)
at async exports.callViewFunction (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/index.js:75:48)
at async Object.handler (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)
TypedError: [-32000] Server error: Account ID Counter is invalid
at /Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:322:31
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Object.exponentialBackoff [as default] (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/utils/exponential-backoff.js:7:24)
at async JsonRpcProvider.sendJsonRpc (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:297:24)
at async JsonRpcProvider.query (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:109:22)
at async Account.viewFunction (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:356:24)
at async exports.callViewFunction (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/index.js:75:48)
at async Object.handler (/Users/shin.takahashi/.nodebrew/node/v14.14.0/lib/node_modules/near-cli/utils/exit-on-error.js:52:9) {
type: 'UntypedError',
context: undefined
}

Counter is not a valid account-id. Uppercase letters in accounts-id are not allowed). You need to pass the proper account-id.
I would expected your account-id to be something of the form takahashi.testnet or dev-1623565709996-68004511819798 (if contract was deployed using near dev-deploy command).
This is how you can deploy to testnet using dev-deploy, and call view function using near-cli:
❯ near --version
2.0.2
❯ near dev-deploy out/main.wasm
Starting deployment. Account id: dev-1623565709996-68004511819798, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/main.wasm
Transaction Id 5eTde2dUw5QTA8hbpWvAw4ABary64Tsnj9FzBCPS9Ne
Done deploying to dev-1623565709996-68004511819798
❯ near view dev-1623565709996-68004511819798 get_num '{}'
View call: dev-1623565709996-68004511819798.get_num({})
0
If you are using mainnet network (instead of testnet), you need to let near-cli knows about this, by setting the environment variable:
❯ export NEAR_ENV=mainnet

Related

Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)

i have develop a simple smartContract. when i run truffle test it showed the following error:i am new in this so i cant figure it out.
PS F:\pracdap> truffle test
Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SimpleSmartContract.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:
Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "urce file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more informa
--> /F/pracdap/contracts/SimpleSmartContract.sol
> Artifacts written to C:\Users\HP\AppData\Local\Temp\test--1224-GWVOn3NGyps8
> Compiled successfully using:
- solc: 0.8.3+commit.8d00100c.Emscripten.clang
Contract: SimpleSmartContract
1) should be deployed
> No events were emitted
0 passing (128ms)
1 failing
1) Contract: SimpleSmartContract
should be deployed:
Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)
at Object.checkNetworkArtifactMatch (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\utils\index.js
at Function.deployed (F:\node\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.j
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at Context.<anonymous> (test\simpleSmartContract.js:5:33)
Solidity code
pragma solidity >=0.4.22 <0.9.0;
contract SimpleSmartContract {
}
Node js. test code
const SimpleSmartContract = artifacts.require('SimpleSmartContract');
contract('SimpleSmartContract', () => {
it('should be deployed', async () => {
const simpleSmartContract = await SimpleSmartContract.deployed();
assert(simpleSmartContract.address !== '');
});
});
Looks like you have not added a Migration file for your SimpleSmartContract.
Create a file named 2_deploy_contracts.js in your Migrations directory. The add the following code in it :
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = function (deployer) {
deployer.deploy(SimpleSmartContract);
};
Then try running the test.
try using migration...if is shows any error let me know.
const SimpleSmartContract = artifacts.require("SimpleSmartContract");
module.exports = async function(deployer, _network, accounts) {
await deployer.deploy(SimpleSmartContract);
};
You should create a new 'migrations file' in the migration folder with a (possible) name of 2_deploy_contracts.js.
async function arguments:
deployer: deployment of the contract
_network: specified network (truffle-config.js)
accounts: to access the truffle accounts when deploying (I.E Solidity constructor arguments)
Ref: https://trufflesuite.com/docs/truffle/getting-started/running-migrations.html

react-apollo Error: Network error: Unexpected token < in JSON at position 1

I want to send a request to this server via Apollo and get a query :
const client = new ApolloClient({
link: new HttpLink({
uri:'http://mfapat.com/graphql/mfaapp/'}),
cache: new InMemoryCache()
})
const FeedQuery = gql
query{
allFmr{
fmrId,
name,
studio,
bedRm1,
bedRm2,
bedRm3,
bedRm4
}
}
`
But I'm facing this error message:
Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1
at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)
....
But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?
Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.
To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:
As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.
Reading the specific error sent enables you to fix the bug.
To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.
EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.
Base on #eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors.
// On Apollo server
// Error handler
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
const { status } = err;
res.status(status).json(err);
};
app.use(errorHandler);

Hello world contract method call returns Unhandled rejection Error

This is my package.json:
{
"dependencies": {
"solc": "^0.4.16",
"web3": "^1.0.0-beta.20"
}
}
This is my smart contract code:
contract HelloWorld {
function displayMessage() constant returns (string) {
return "Hello from a smart contract";
}
}
I've compiled this contract on the node repl with testprc running, and I'm trying to call the displayMessage method like so:
myContract.methods.displayMessage().call()
or
myContract.methods.displayMessage.call()
but I'm just getting this error:
> Unhandled rejection Error: ERROR: The returned value is not a convertible string:
at SolidityTypeString.formatOutputString [as _outputFormatter] (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/formatters.js:245:15)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/type.js:246:25
at SolidityTypeString.SolidityType.decode (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/type.js:247:11)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/index.js:327:49
at Array.forEach (<anonymous>)
at ABICoder.decodeParameters (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-abi/src/index.js:326:13)
at Contract._decodeMethodReturn (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-contract/src/index.js:490:22)
at Method._parent._ethereumCall.call.method.outputFormatter (/Users/alberthu/Documents/solidity-intro/node_modules/web3-eth-contract/src/index.js:820:42)
at Method.formatOutput (/Users/alberthu/Documents/solidity-intro/node_modules/web3-core-method/src/index.js:179:54)
at sendTxCallback (/Users/alberthu/Documents/solidity-intro/node_modules/web3-core-method/src/index.js:446:33)
at /Users/alberthu/Documents/solidity-intro/node_modules/web3-core-requestmanager/src/index.js:144:9
at XMLHttpRequest.request.onreadystatechange (/Users/alberthu/Documents/solidity-intro/node_modules/web3-providers-http/src/index.js:64:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/Users/alberthu/Documents/solidity-intro/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
I've tried reading through the web3 api docs but I'm new to this and haven't found anything useful. Anyone know how I can get "Hello from a smart contract" to show on the server?
Thanks!
I have the same problem. And insert correct contract address.
My contract (example from documentation web3js) I use web3.1.0.0-beta.23.
pragma solidity ^0.4.18;
contract MyContract {
function myFunction() returns(uint256 myNumber, string myString) {
return (23456, "Hello!%");
}
}
code
const contract = new web3.eth.Contract(abi, contractAddress);
contract.methods.myFunction().call()
.then(res => console.log(res))
.catch(e => console.log(e.message))
contract creating and send from test net good. But if I tried call methods - have the same error:
ERROR: The returned value is not a convertible string:
I am also learning how to code smart contracts and came across this error earlier today. I found what was causing it was that I had the wrong address tied to my smart contract.
Contract objects in web3 have an address property which represents the address used for that contract instance. In my case this address was incorrect and was causing me to have the same error. The contract address should have been returned to you after your deployment.
The correct contract address should have been returned to you in a callback function after you deployed it.
You can set and check your contract address as follows:
myContract.options.address // returns the current address you have set for this contract instance
myContract.options.address = "the correct contract address"
I would have left this as a comment but unfortunately I do not have enough reputation. Let me know if you need some more help or want to get together to learn.
Here is the web3js documentation on contract address property: https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#options-address

Express server crashing due to MongoDB connection loss

I am having issues with an HTTP Node.js server built with:
Ubuntu 14.04
MongoDB 3.0.4
iojs v2.3.3
express=4.10.*
mongodb=1.4.34
The following middleware are being used:
app.use(response_time());
app.use(body_parser.urlencoded({extended: true}));
app.use(body_parser.json());
var MongoClient = require('mongodb').MongoClient;
app.use(function (req, res, next) {
var connection_options = {auto_reconnect: false};
MongoClient.connect(config.server.db, connection_options, function (err, db) {
if (err) {
log.error(err); // Logging error.
return next(err);
}
req.db = db;
next();
});
});
The server started running at 20:40:10 and successfully handled multiple requests.
At 02:59:02, the following error started to get logged on every request:
02:59:02.114Z ERROR CrowdStudy: failed to connect to [127.0.0.1:27017]
Error: failed to connect to [127.0.0.1:27017]
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/server.js:555:74)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1237:8)
My initial suspicion was that I was that the connection pool was filling up because I don't have anything to handle calling req.db.close(). I thought that passing in the options {auto_reconnect: false} would fix this issue by automatically closing the connection after some time, but it seems I was wrong.
Note that restarting the server fixes the issue, so I believe the problem has to do with Node rather than Mongo.
If this has to do with the connection pool, is there some setting I can pass to fix this, or can I have an end-ware that makes sure the connection always gets closed?
Thanks a lot to anyone who can help me out!
autoReconnect is an option that should be passed to the server configuration:
MongoClient.connect(config.server.db, {
server : { autoReconnect : false }
}, ...);
The documentation contains some errors: it states that the default setting is false (which it isn't), and it also states that autoReconnect should be set in an object called socketOptions (which it shouldn't).
You can add various event listeners to the db object that gets passed back, to detect when the connection to the database got closed/reconnected/...:
db.on('close', function(reason) { ... });
db.on('reconnect', function(db) { ... });
More events here.

Get PDF files from Worklight Server to the client

Based on the following reference:- Worklight Adapter getting pdf file from rest service, i got the PDF file from tomcat server through the worklight adapter. The server side code is:-
var input = {
method : 'get',
returnedContentType : 'plain',
path : '/PDF/example-abstract.pdf'
};
return WL.Server.invokeHttp(input);
When i invoke the invoke the procedure i am able to successfully retrieve the result. When i invoke the same procedure from client side like below:-
var invocationData = {
adapter: 'PdfReader',
procedure: 'readPDF',
parameters: []
};
I am unable to receive the response in the success handler. In logcat it showing the following error:-
07-03 13:07:05.330: E/pdf(4214): [http://Path-to-pdf:10080/pdf/apps/services/api/pdf/android/query] exception. SyntaxError: Unexpected token ILLEGAL
07-03 13:07:05.377: D/dalvikvm(4214): GC_FOR_ALLOC freed 347K, 10% free 8082K/8967K, paused 19ms
07-03 13:07:05.424: D/dalvikvm(4214): GC_CONCURRENT freed 155K, 7% free 8390K/8967K, paused 2ms+3ms
07-03 13:07:05.424: D/pdf(4214): response [http://Path-to-pdf:10080/pdf/apps/services/api/pdf/android/query] success: {"responseID":"2","statusCode":200,"text":"%PDF-1.4\n%????\n3 0 obj <<\n\/Length 2445 \n\/Filter \/FlateDecode\n>>\nstream\nx?X[??\n~?_?#?YQ?O?dw??M??3?4'\u000f0 \\Shorted
07-03 13:07:05.424: W/PluginManager(4214): THREAD WARNING: exec() call to Logger.DEBUG blocked the main thread for 45ms. Plugin should use CordovaInterface.getThreadPool().
07-03 13:07:05.455: E/pdf(4214): [http://Path-to-pdf:10080/pdf/apps/services/api/pdf/android/query] exception. TypeError: Cannot read property 'isSuccessful' of undefined
07-03 13:07:05.455: D/CordovaLog(4214): file:///data/data/com.pdf/files/www/default/worklight/worklight.js: Line 3320 : Uncaught SyntaxError: Unexpected token ILLEGAL
07-03 13:07:05.455: E/Web Console(4214): Uncaught SyntaxError: Unexpected token ILLEGAL at file:///data/data/com.pdf/files/www/default/worklight/worklight.js:3320
07-03 13:07:05.463: D/CordovaLog(4214): file:///data/data/com.pdf/files/www/default/worklight/worklight.js: Line 3320 : Uncaught TypeError: Cannot read property 'isSuccessful' of undefined
07-03 13:07:05.471: E/Web Console(4214): Uncaught TypeError: Cannot read property 'isSuccessful' of undefined at file:///data/data/com.pdf/files/www/default/worklight/worklight.js:3320
I need to know, how to make it reachable in the successHandler. Thanks in advance.
The problem is with parsing the JSON data, based on the following answer, I have converted the Json data to string using JSON.stringify(), so that the string can successfully reach the successHandler inside the handler i am using JSON.parse() to convert the string to JSON for use.