After one approve is made,
I want to know how to get current approval allowance(from an address, to a specified contract and gateway), in json-rpc way.
e.g. like eth_call?
The to field of the call is the token contract, and the data param is ABI-encoded signature of allowance() function followed by its arguments. eth_call also requires to specify at which block you're requesting the data - you can use the "latest" value for the current block
curl -X POST \
--url "<your_node_url>" \
--data '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xdAC17F958D2ee523a2206206994597C13D831ec7","data":"0xdd62ed3e00000000000000000000000086987cca9f86da6b4d8a805c1ebd4130ae120a24000000000000000000000000b2723beacce4bc54f23544343927f048cef6bd5a"}, "latest"],"id":1}'
Docs: https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call
I used this JS snippet to build the data param value:
const data = web3.eth.abi.encodeFunctionCall({
name: 'allowance',
type: 'function',
inputs: [{
type: 'address',
name: 'from'
},{
type: 'address',
name: 'to'
}]
}, [
"0x86987cca9f86da6b4d8a805c1ebd4130ae120a24",
"0xB2723BEacce4BC54F23544343927f048CeF6bD5A"
]);
console.log(data);
Related
I am using aws go sdk and accessing the cost data from AWS. This query returns all ths services in an aws account like S3, EC2...
result, err := svc.GetCostAndUsage(&costexplorer.GetCostAndUsageInput{
TimePeriod: &costexplorer.DateInterval{
Start: aws.String(startDate),
End: aws.String(endDate),
},
Granularity: aws.String(granularity),
GroupBy: []*costexplorer.GroupDefinition{
&costexplorer.GroupDefinition{
Type: aws.String("DIMENSION"),
Key: aws.String("SERVICE"),
},
},
Metrics: aws.StringSlice(metrics),
})
How can I add a filter to this query so I can retrieve data of a few selected services ?
The docs (link) show there's a field in the costexplorer.GetCostAndUsageInput struct called Filter that's a *types.Expression, which has a field named CostCategories that's a *types.CostCategoryValues that should do the trick.
Here's your code but modified to filter only costs for S3 (fair warning, this code has not been tested):
result, err := svc.GetCostAndUsage(&costexplorer.GetCostAndUsageInput{
Filter: &types.Expression{
CostCategories: &types.CostCategoryValues{
Key: aws.String("SERVICE"),
Values: []string{"s3"}, // 's3' may not be the right value here, this is just an example
},
},
TimePeriod: &costexplorer.DateInterval{
Start: aws.String(startDate),
End: aws.String(endDate),
},
Granularity: aws.String(granularity),
GroupBy: []*costexplorer.GroupDefinition{
&costexplorer.GroupDefinition{
Type: aws.String("DIMENSION"),
Key: aws.String("SERVICE"),
},
},
Metrics: aws.StringSlice(metrics),
})
I'm trying to be notified when a new review is added on my Google Business Profile.
According to the documentation, I have setup the notification but I got nothing when a new review is added.
First of all, I have created a Pub/Sub Topic projects/my-project/topics/business-profile-notifications.
Then, I have created a Push subscription projects/my-project/subscriptions/business-profile-notifications-push attached to the previous created Topic. I have also defined an endpoint: https://my-endpoint/webhook. This endpoint is listening POST requests
Finally, I have added the service account mybusiness-api-pubsub#system.gserviceaccount.com into IAM with Pub/Sub admin role.
On the code side, I'm using NPM googleapis client in a TypeScript Node.js server.
I'm updating the account settings to setup the notifications:
const { data }: GaxiosResponse<mybusinessnotifications_v1.Schema$NotificationSetting> = await google.mybusinessnotifications({
version: 'v1',
auth,
}).accounts.updateNotificationSetting({
name: `accounts/${params.accountID}/notificationSetting`,
updateMask: 'notification_types',
requestBody: {
name: `accounts/${params.accountID}/notificationSetting`,
pubsubTopic: 'projects/my-project/topics/business-profile-notifications',
notificationTypes: [
'NEW_REVIEW',
'UPDATED_REVIEW',
],
},
});
At this point, nothing happens when a new review is added.
When I'm sending a POST request on my endpoint via curl command curl -X POST -H "Content-Type: application/json" -i "https://my-endpoint/webhook", the request is successfully catched.
In the other hand, when I'm getting notifications settings from the configured account, I have the notifications types but not any subscribed topic:
const { data }: GaxiosResponse<mybusinessnotifications_v1.Schema$NotificationSetting> = await google.mybusinessnotifications({
version: 'v1',
auth,
}).accounts.getNotificationSetting({
name: `accounts/${accountID}/notificationSetting`,
fields: 'pubsubTopic,notificationTypes',
});
Response:
{
"notificationTypes": [
"NEW_REVIEW",
"UPDATED_REVIEW"
]
}
What I forgot to do ?
I resolved the issue by myself 😁
In the documentation of updateNotificationSetting method, is it stated that "The only editable field is notificationSetting" about the updateMask field. But it's wrong. I had to add pubsubTopic as value.
Finally, the parameter values of this method are:
const opts = {
name: `accounts/${params.accountID}/notificationSetting`,
updateMask: 'notificationTypes,pubsubTopic',
requestBody: {
name: `accounts/${params.accountID}/notificationSetting`,
pubsubTopic: params.pubsubTopic,
notificationTypes: params.notificationTypes,
},
};
const { data }: GaxiosResponse<mybusinessnotifications_v1.Schema$NotificationSetting> = await google.mybusinessnotifications({
version: 'v1',
auth,
}).accounts.updateNotificationSetting(opts);
I would like to use listDevices to get all my devices under a registry.
Google NodeJS Core IOT API spec
I get an array back which seems to contain a metadata obj/json doc but it's empty.
---
- credentials: []
metadata: {}
id: device001
name: ''
numId: '3038801391636994'
config:
lastConfigAckTime:
state:
lastConfigSendTime:
blocked: false
lastStateTime:
logLevel: LOG_LEVEL_UNSPECIFIED
gatewayConfig:
- credentials: []
metadata: {}
id: device002
name: ''
numId: '2991873732633082'
config:
lastConfigAckTime:
state:
lastConfigSendTime:
blocked: false
lastStateTime:
logLevel: LOG_LEVEL_UNSPECIFIED
gatewayConfig:
If I run a getDevice I do get the expected metadata but that requires a request for each device which becomes too slow and hammers resources. Bug or design?
const [response] = await iotClient.getDevice({name: devicePath});
Which actually shows the metadata
Found device: device002 {
credentials: [
{
expirationTime: [Object],
publicKey: [Object],
credential: 'publicKey'
}
],
metadata: {
hasGPS: 'true',
model: 'Pyton_v1',
hasSolar: 'true',
netType: 'WIFI'
},
id: 'device002'
}
I've made some tries with the device list functions and I think it is a design.
If you run the "gcloud iot devices list" command you get only the fields id and num_id, the ones that are filled in your output array too.
I tried using other client libraries and I got the same results, so it looks like it is designed like this but the NodeJS library retrieves additional fields for each device.
It is defined in the fieldMask parameter in listDevices api. Check the example code here:
https://cloud.google.com/iot/docs/how-tos/devices?authuser=1#getting_device_details
I've added a request validator to my API Gateway swagger file (OAS 3.0). When I test the validation by passing in an invalid request body the error message I receive includes errors that I don't understand. Steps to reproduce are below.
Create a new api gateway using the following swagger:
openapi: 3.0.0
info:
version: "1"
title: Request Validation Example
description: |
## Request Validation
Minimal swagger to reproduce request validation errors.
x-amazon-apigateway-request-validators:
all:
validateRequestBody: true
validateRequestParameters: true
x-amazon-apigateway-gateway-responses:
BAD_REQUEST_BODY:
statusCode: 400
responseTemplates:
application/json: |
{
message: $context.error.messageString
errors: $context.error.validationErrorString
}
paths:
/employee:
post:
x-amazon-apigateway-request-validator: all
summary: Create a new Employee
operationId: CreateEmployee
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/Employee"
required: true
responses:
"201":
description: Created
$ref: "#/components/responses/200"
components:
responses:
"200":
description: Success
schemas:
Employee:
type: object
properties:
id:
type: integer
format: int32
phoneNumbers:
type: array
items:
$ref: "#/components/schemas/PhoneNumber"
salary:
type: number
format: double
required:
- phoneNumbers
- salary
PhoneNumber:
type: object
properties:
number:
type: string
required:
- number
Set up the integration method for the newly created employee resource, choose the mock integration.
Test the employee POST method using the following request body:
{
"id": 1,
"phoneNumbers": [
{
"number": "1234567890"
}
],
"salary": 45000
}
Request validation will succeed with this request body
Test the employee POST method with the following request body:
{
"id": "1",
"phoneNumbers": [
{
"number": "1234567890"
}
],
"salary": 45000
}
You will now see the following request validation error:
{
message: "Invalid request body"
errors: [instance type (string) does not match any allowed primitive type (allowed: [\"integer\"]), format attribute \"double\" not supported, format attribute \"int32\" not supported]
}
You can see that this message includes the correct error saying that the string id doesn't match the type integer. You will also see errors regarding format attributes double and int32 not being supported, these are the errors I don't understand. As far as I know double and int32 format attributes are supported by OAS 2.0 and 3.0. Do API Gateway request validators support the double and int32 format attributes? Is the request validator incorrectly configured in my swagger definition?
Edit:
It appears that the int32 and double format attributes are known issues: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html#api-gateway-known-issues-rest-apis
However, I also experience these issues using a regex in the format attribute. This isn't specifically mentioned in the known issues so still looking for information on that.
I think it's important to note that the models defined in a OAS document are supposed to be JSONSchema, not necessarily OpenAPI. They're validated at runtime as JSONSchema Draft 4, which does not include a format attribute in the specification.
What can be confusing at times is the import operation. When using OpenAPI to define your API and importing it, API Gateway ends up parsing the intersection of the OAS specification for models and JSONSchema draft 4.
If there is an attribute of JSONSchema that you need, which is not included in OpenAPI's Schema specification, (e.g. type: [..., null]) then creating or updating an API Gateway ::Model directly is a workaround.
Trying to use loopback framework for simulating a backend service. I need to retrieve an object using POST method. I know REST services typically allow POST to update/create a resource, but here, I cannot use GET with resource details for retrieving data.
In my case, POST data contains a few query fields that have to be used to query an object and send json back. Is this possible with loopback? I cannot use GET with query parms due to security restrictions with sending data as query parms in a GET URL.
here is post request data
[ { customer:"sam", city:"noWhere", } ]
the POST event should query by customer and city, then return matching customer object
[ { customer:"sam", postcode:"352345", city:"noWhere", country:"US" } ]
I think that what you need is an express http method override middleware: https://github.com/expressjs/method-override
And defining middleware in loopback:
http://docs.strongloop.com/display/LB/Defining+middleware
You can override default loopback endpoint, like this
// Define custom remote method
Customer.fetch = function(oRequest, fnResponseCb) {
/* Do staff to find customer and finally call fnResponseCb(null, oCustomer) */
}
// Override custom remote method
Customer.remoteMethod('fetch', {
accepts: {
arg: 'oRequest',
type: 'object',
http: { source: 'body' }
},
returns: {
type: 'object',
root: true
},
http: {
path: '/',
verb: 'POST'
},
description : 'Fetch Customer'
});