Handling exception for invalid json format for `assemblyscript-json` in `JSON.parse` - nearprotocol

The following works:
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));
but if jsonString has an invalid json format, it breaks my subgraph.
Using:
"#graphprotocol/graph-cli": "0.35.0",
"#graphprotocol/graph-ts": "0.29.0",
"assemblyscript-json": "1.1.0"
Since assemblyscript doesn't have support for error handling (try/catch) is there a way to handle an invalid json string with assemblyscript-json ?

Exception handling (and error handling in general) is currently hard to do in AssemblyScript, because the developers are waiting for the WebAssembly exception proposal to go through.
The assemblyscript-json package is recommended by the documentation, but it seems, at least to me from afar, to be unmaintained actively. Maybe the json-as package would prove to be useful for you. Still no exception handling, but it does not fail on invalid jsons, it merely returns an object with all nulls and zeros, so you can check it more easily.
import { JSON } from "json-as";
export function test(): Player {
// #ts-ignore
const data: Player = {
firstName: "Emmet",
lastName: "West",
lastActive: [8, 27, 2022],
age: 23,
pos: {
x: -3.4,
y: 1.2
},
isVerified: true
}
return JSON.parse<Player>("[1, 2, 3]"); // invalid json
}
This, for me, returns:
{
firstName: null,
lastName: null,
lastActive: null,
age: 0,
pos: null,
isVerified: false
}
In order to install the package, be sure to call:
npm install --save json-as
because that is the name on the npm, as opposed to the name on github. You can check the package documentation on github, to ensure that this is correct.

Related

GraphQL input parameter

There is JSON-object (an array of different structures) like:
"cells": [
{
"x":3,
"y":6,
},
{
"type": "shape",
"direction": right,
},
....
{
"a": 4,
"b": 5,
"c": 6,
}
]
I need to save this object using graphql mutation. Whats the way to do it?
type A {
x: Int!
y: Int!
}
type B {
type: String!
direction: String!
}
type C {
a: Int!
b: Int!
c: Int!
}
union Request = A | B | C
input InputR {
cells: [Request!]!
}
type Mutation {
save(cells: InputR!): InputR
}
I tried the following, but it doesnt work. Any ideas?
Thanks!
So there are a few answers, depending on what you're looking for.
You can't. GraphQL doesn't have union input types (today). It was originally proposed to be an antipattern, though there are proposals making their way through the processes as of today.
You could just create a single input type that has all of those fields, all nullable, though that leads you to the problem of "Anemic Mutations"
Are you sure you want to? Those structures are so incredibly different that it may be you're thinking about the problem from an implementation standpoint, rather than a data-architecture one.
If #1 & #2 aren't good enough and #3 isn't true, the "best way for today" at that point is probably just to use a JSON scalar type. It requires you pass all of that in as a single JSON-compatible string. Here is an example of one.

How to get Solana transaction data from transaction object

I'm doing a simple transaction with a single transfer instruction for 0,1 SOL from one account to another. Then I want to get the transaction data and use it to verify the data it carries - in this case that a transfer has been made for 0,1 SOL.
I use getTransaction with the tx signature and get a response like this:
{
message: Message {
header: {
numReadonlySignedAccounts: 0,
numReadonlyUnsignedAccounts: 1,
numRequiredSignatures: 1
},
accountKeys: [ [PublicKey], [PublicKey], [PublicKey] ],
recentBlockhash: '9S44wiNxXZSdP5VTG6nvaumUJBiUW1DGUXmhVfuhwTMh',
instructions: [ [Object] ],
indexToProgramIds: Map(1) { 2 => [PublicKey] }
},
signatures: [
'8ykRq1XtgrtymXVkVhsWjaDrid5FkKzRPJrarzJX9a6EArbEUYMrst6vVC6TydDRG4sagSciK6pP5Lw9ZDnt3RD'
]
}
So, I dig into message.instructions and find the following object:
{ accounts: [ 0, 1 ], data: '3Bxs411Dtc7pkFQj', programIdIndex: 2 }
Ok, so data is the base58-encoded string '3Bxs411Dtc7pkFQj'. I decode that from base58 (using bs58), but that only gives me a Uint8Array, which I am not really sure how to convert into a JS object.
I can see in the tx in Solscan that the data information is decoded into hex:
And I can also get this info in my script:
---> Instructions:
{ accounts: [ 0, 1 ], data: '3Bxs411Dtc7pkFQj', programIdIndex: 2 }
---> Instructions Data:
3Bxs411Dtc7pkFQj
0200000000e1f50500000000
-----
But not sure what to do next. How do I get the actual amount data out of it.
So, I guess the question is: How to decode the instruction data into a JS object?
So, for your second question:
To know how to deserialize the array returned from the bs58 decoding you need to know how the sender serialized the instruction.
I was redirected to solana.stackexchange.com and there I found the answer. Basically, I could use getParsedTransaction instead of just getTransaction.
The parsed function would give me exactly what I need, since the instructions prop is an array containing one object (in my case), which looks like this:
{
parsed: {
info: {
destination: 'foo',
lamports: 100000000,
source: 'bar'
},
type: 'transfer'
},
// ... other props
}

Apollo based server giving error code - BAD_USER_INPUT

I'm using Vendure headless e-commerce and trying to run a GraphQL mutation according to the specs - but I'm running into an error I cannot seem to decipher.
The error I'm getting is:
{
"errors": [{
"extensions": {
"code": "BAD_USER_INPUT"
},
"locations": [{
"line": 1,
"column": 28
}]
}]
}
This is in turn pointing to the $input variable.
query: "mutation AddPaymentToOrder($input: PaymentInput!) {\n ... etc ...
Usually when I've gotten this error code it means I've made a mistake in the mutation, but in those cases I get a clear message what is wrong. In this mutation I get nothing.
The Vendure docs on this mutation are quite simple: https://www.vendure.io/docs/graphql-api/shop/mutations/#addpaymenttoorder
The mutation I've written is quite simple as well for now:
export const AddPaymentToOrderQuery = gql`
mutation AddPaymentToOrder($input: PaymentInput!) {
addPaymentToOrder(input: $input) {
... on Order {
id
}
}
}
`;
The data I send looks like this:
type Variables = {
input: {
method: string;
}
};
Does anyone understand this error?
The problem was a misunderstanding - a missing input data element metadata that I had forgotten.
Input should look like:
type Variables = {
input: {
method: string;
metadata: Object;
}
};

badRequest: Invalid requests[0]: No request set. (Google::Apis::ClientError)

I can't solve this problem. Can someone help me?
Issue: badRequest: Invalid requests[0]: No request set. (Google::Apis::ClientError)
I just need to include formulas in a cell sequence.
Here is the code:
requests: [
{
repeatCell: {
range: {
sheetId: sheet_id,
startRowIndex: 0,
endRowIndex: 10,
startColumnIndex: 1,
endColumnIndex: 6
},
cell: {
userEnteredValue: {
formulaValue: "=FLOOR(A1*PI())"
}
},
fields: "*"
}
}
]
}
response = service.batch_update_spreadsheet(spreadsheet_id, request) ```
Unfortunately, although I cannot see your whole script in your question, it is found that in your request body, you use the camel case. I think that this is the reason of your issue. In the case of Ruby, please use the snake case as follows.
Modified script:
request = {
requests: [{repeat_cell: {
range: {
sheet_id: 0,
start_row_index: 0,
end_row_index: 10,
start_column_index: 1,
end_column_index: 6
},
cell: {
user_entered_value: {
formula_value: "=FLOOR(A1*PI())"
}
},
fields: "*"
}}]
}
response = service.batch_update_spreadsheet(spreadsheet_id, request, {})
Note:
In this modification, it supposes that your service can be used for using the batchUpdate method of Sheets API to the Google Spreadsheet of spreadsheet_id. Please be careful this.

GraphQL doesn't consider dynamic arrays of strings valid strings

I have a query that works when manually typed:
queryName(where: { ids: ["1234567890123456789", "1234567890123456790"] }, offset: 0, max: 10) {
but when the same values are passed in a variable:
const idArr = ["1234567890123456789", "1234567890123456790"];
...
queryName(where: { ids: ${idArr} }, offset: 0, max: 10) {
I get the error:
Uncaught GraphQLError: Syntax Error: Expected Name, found Int "1234567890123456789"
Can anyone explain this?
Using string interpolation like that will result in the following value being inserted inside your string:
"1234567890123456789,1234567890123456790"
This is not valid GraphQL syntax and so results in a syntax error. Instead of using string interpolation, you should use GraphQL variables to provide dynamic values along with your query:
query ($idArr: [ID!]!) {
queryName(where: { ids: $idArr }, offset: 0, max: 10) {
...
}
}
Note that the type of the variable will depend on the argument where it's being used, which depends on whatever schema you're actually querying.
How you include the variables along with your request depends on the client you're using to make that request, which is not clear from your post. If you're using fetch or some other simple HTTP client, you just include the variables alongside the query as another property in the payload you send to the server:
{
"query": "...",
"variables": {
...
}
}

Resources