At https://github.com/NEAR-Edu/near-certification-tools/blob/ba220aa6d13b9d8e1996526c796aec203a2853d3/data-contract/src/contract/mint.rs#L41 I call self.tokens.internal_mint(token_id, to_account_id, Some(combined_metadata)) which calls NftMint { owner_id: &token.owner_id, token_ids: &[&token.token_id], memo: None }.emit();
But when I mint an NFT, I never see the nft_mint event in the testnet Explorer.
What am I doing wrong, or how can I step through a debug to narrow down to the general area where something is wrong?
The NFT does successfully get minted, in the sense that my TypeScript const response = await (contract as NFT).nft_tokens_for_owner({ account_id: accountId }); finds it.
Running the TypeScript integration-tests in https://github.com/near-examples/NFT with worskpaces version 3.2.2 will print the smart contract logs, so the standard contract will emit the events with emit().
As for this contract, you can create an integration-tests folder in the project root. Here you can make use of the workspaces library to run a local version of NEAR Blockchain and upload your smart contract code to it, and run the nft_mint function as follows:
import { Worker, NearAccount, tGas, NEAR, BN } from 'near-workspaces';
import anyTest, { TestFn } from 'ava';
import { mint_more, nft_total_supply } from './utils';
const test = anyTest as TestFn<{
worker: Worker;
accounts: Record<string, NearAccount>;
}>;
test.beforeEach(async t => {
const worker = await Worker.init();
const root = worker.rootAccount;
const nft = await root.devDeploy(
'../data-contract/target/wasm32-unknown-unknown/release/near_certification_tools.wasm',
{
initialBalance: NEAR.parse('100 N').toJSON(),
method: "new",
args: {
owner_id: root.accountId,
metadata: {
spec: "nft-1.0.0",
name: "Certification Tools",
symbol: "CT",
icon: null,
base_uri: null,
reference: null,
reference_hash: null,
},
options: {
can_transfer: true,
can_invalidate: true
}
}
},
);
const alice = await root.createSubAccount('alice', { initialBalance: NEAR.parse('100 N').toJSON() });
t.context.worker = worker;
t.context.accounts = { root, alice, nft };
});
test.afterEach.always(async t => {
await t.context.worker.tearDown().catch(error => {
console.log('Failed to tear down the worker:', error);
});
});
test('Simple mint', async test => {
const { root, alice, nft } = test.context.accounts;
await root.call(
nft,
"add_issuer",
{ account_id: root.accountId },
);
test.log('Issuer set');
await root.call(
nft,
"nft_mint",
{
token_id: "0",
receiver_account_id: alice.accountId,
token_metadata: {
title: "Olympus Mons",
description: "The tallest mountain in the charted solar system",
media: null,
media_hash: null,
copies: 10000,
issued_at: null,
expires_at: null,
starts_at: null,
updated_at: null,
extra: null,
reference: null,
reference_hash: null,
},
certification_metadata: {
authority_name: "NASA",
authority_id: null,
program: "Mars 2020",
program_name: null,
program_link: null,
program_start_date: null,
program_end_date: null,
original_recipient_id: null,
original_recipient_name: null,
valid: true,
memo: null
}
},
{ attachedDeposit: '8540000000000000000000' }
);
test.pass();
});
This generates the following output, whereby EVENT_LOG is sent to the logs of contract:
Related
I am unable to store timestamp in Dynamo DB using Node JS Lambda. i am new to Node JS.
while run the test case, it was stored. but while trigger this lambda function getting error.
i was try to insert below timestamp
LastUpdateTimestamp
The date and time this contact was last updated, in UTC time.
Type: String (yyyy-mm-ddThh:mm:ssZ)
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB();
exports.handler = async (event) => {
var surveyResults = {};
var data = event.Details.ContactData.Attributes; // extract the contact attributes from the Amazon Connect event
Object.keys(data).forEach(element => {
if (element.startsWith("survey_result_")) {
surveyResults[element] = { S: data[element] };
}
});
var params = {
TableName: process.env.TABLE,
Item: {
contactId: { S: event.Details.ContactData.ContactId},
date: { S: event.Details.ContactData.LastUpdateTimestamp},
surveyId: { S: event.Details.ContactData.Attributes.surveyId },
...surveyResults
}
}
try {
await ddb.putItem(params).promise(); // write the object to the DynamoDB table
} catch (err) {
console.log(err);
}
const response = {
statusCode: 200,
body: JSON.stringify('OK'),
};
return response;
};
Test Data:
{
"Name": "ContactFlowEvent",
"Details": {
"ContactData": {
"Attributes": {
"surveyId": "123456",
"survey_result_1": "4",
"survey_result_2": "5"
},
"Channel": "VOICE",
"ContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
"LastUpdateTimestamp": "2023-02-14T06:52:29Z",
"CustomerEndpoint": {
"Address": "+11234567890",
"Type": "TELEPHONE_NUMBER"
},
"InitialContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
"InitiationMethod": "API",
"InstanceARN": "arn:aws:connect:us-east-1:123456789012:instance/9308c2a1-9bc6-4cea-8290-6c0b4a6d38fa",
"MediaStreams": {
"Customer": {
"Audio": {
"StartFragmentNumber": "91343852333181432392682062622220590765191907586",
"StartTimestamp": "1565781909613",
"StreamARN": "arn:aws:kinesisvideo:us-east-1:123456789012:stream/connect-contact-a3d73b84-ce0e-479a-a9dc-5637c9d30ac9/1565272947806"
}
}
},
"PreviousContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
"Queue": null,
"SystemEndpoint": {
"Address": "+11234567890",
"Type": "TELEPHONE_NUMBER"
}
},
"Parameters": {}
}
}
Error:
2023-02-15T14:10:26.426Z 94fad25e-bcdb-443b-95c0-47640bfaba34 INFO ValidationException: Supplied AttributeValue is empty, must contain exactly one of the supported datatypes
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:52:27)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:686:14)
at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:688:12)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
code: 'ValidationException',
time: 2023-02-15T14:10:26.328Z,
requestId: 'F5JJOCF20D507JCFRO7FEMAH6VVV4KQNSO5AEMVJF66Q9ASUAAJG',
statusCode: 400,
retryable: false,
retryDelay: 15.458319111471575
}
You state that ...surveyResults contains the following:
"survey_result_1": "4",
"survey_result_2": "5"
This is not DynamoDB JSON. You need to modify the values to suit the correct format as you have done with the other values.
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB();
exports.handler = async (event) => {
var surveyResults = {};
var data = event.Details.ContactData.Attributes; // extract the contact attributes from the Amazon Connect event
Object.keys(data).forEach(element => {
if (element.startsWith("survey_result_")) {
surveyResults[element] = { S: data[element] };
}
});
var contact_params = {
ContactId: event.Details.ContactData.InitialContactId, /* required */
InstanceId: 'place your instance id' /* required */
};
var connect = new AWS.Connect();
console.log('describeContact');
/*connect.describeContact(contact_params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});*/
const attributes = await connect.describeContact(contact_params).promise();
console.log(attributes)
console.log(typeof attributes.Contact.LastUpdateTimestamp)
var agent_params = {
InstanceId: 'place your instance id', /* required */
UserId: attributes.Contact.AgentInfo.Id /* required */
};
const agent = await connect.describeUser(agent_params).promise();
let agent_username = "";
if(agent_username != null){
agent_username = agent.User.Username;
}
console.log(agent)
var params = {
TableName: process.env.TABLE,
Item: {
contactId: { S: event.Details.ContactData.ContactId},
surveyId: { S: event.Details.ContactData.Attributes.surveyId },
date: { S: attributes.Contact.LastUpdateTimestamp.toLocaleDateString()},
time: { S: attributes.Contact.LastUpdateTimestamp.toLocaleTimeString()},
agentname: {S: agent_username},
...surveyResults
}
}
try {
await ddb.putItem(params).promise(); // write the object to the DynamoDB table
} catch (err) {
console.log(err);
}
const response = {
statusCode: 200,
body: JSON.stringify('OK'),
};
return response;
};
Does anyone know how I can add a max supply to a Metaplex fungible asset ?
const metadata = await Metadata.getPDA(mint.publicKey);
const createMetadataTx = new CreateMetadataV2(
{ feePayer: mint_authority.publicKey },
{
metadata,
metadataData: new DataV2({
uri :'https://xxxx-88-81-106-161.ngrok.io/sample-uri',
name: 'ttt',
symbol: 'ttt',
sellerFeeBasisPoints: 100,
creators: null,
collection: null,
uses: null,
tokenStandard: TokenStandard.Fungible
}),
updateAuthority: mint_authority.publicKey,
mint: mint.publicKey,
mintAuthority: mint_authority.publicKey,
},
);
const sig = await connection.sendTransaction(createMetadataTx, [mint_authority],{
skipPreflight: false,
} )
const txRpcResponse = await connection.confirmTransaction(sig)
According to the current Metadata Struct, there is no such field as max supply you can look more into the SPL token program it contains a field called supply to know more about it you can look here or checkout the Solana Program Library Repo
Using postman the backend seems to be getting the correct data back but when I throw it into a fetch the components are not re-rendering the state and also giving me a yellow error, of Network Request Failed.
The backend is made of Flask Python, and the FrontEnd is using Expo CLI with an android emulator, I looked up previous issues and found some saying the emulator and the machine are not connected, I fixed that issue by doing a remote/local ip ex: 192.168.1.... but it's still returning a network request failed.
import React, { useEffect, useState } from "react";
import { ScrollView, View, TouchableOpacity, Text } from "react-native";
import { connect } from "react-redux";
import * as actions from "../src/actions";
import EarningsBar from "./EarningsBar";
const DayCalendar = (props) => {
const [isLoaded, setisLoaded] = useState(false);
useEffect(() => {
props.loadStock("daily");
if (Object.keys(props.dailyStocks).length > 0) {
setisLoaded(true);
console.log(props.dailyStocks);
}
}, []);
return (
<ScrollView nestedScrollEnabled={true}>
{isLoaded === true &&
props.dailyStocks.time.map(
({ companyshortname, epsactual, epsestimate, ticker }, index) => {
return (
<EarningsBar
key={index}
companyName={companyshortname}
companyAbbrev={ticker}
companyEPS={epsestimate}
companyRev={"$3.28"}
companyActualEPS={epsactual}
companyActualRES={"$5.66"}
companyGrowthEPS={"103.3%"}
companyGrowthRev={"83.8%"}
arrow={"good"}
/>
);
}
)}
</ScrollView>
);
};
const mapStateToProps = (state) => {
return {
dailyStocks: state.calendar.daily,
};
};
export default connect(mapStateToProps, actions)(DayCalendar);
This is the day calendar Component
Here is the action function
export const loadStock = (stock) => {
return (dispatch) => {
try {
fetch(`http://192.168.1.13:3000/${stock}stock`)
.then((response) => {
return response.json();
})
.then((data) => {
dispatch({ type: "LOAD_STOCKS", payload: { stock, data } });
});
} catch (error) {
console.log(error);
}
};
};
My reducer states/and switch cases
export const initialLoginState = {
users: [],
searchedStocks: [],
calendar: {
daily: [],
weekly: [],
monthly: [],
},
stocks: [],
searchTerm: null,
isLoading: true,
user_id: null,
username: null,
password: null,
confirmPassword: null,
email: null,
birthdate: null,
question: null,
answer: null,
userToken: null,
isValidUser: true,
isValidPassword: true,
};
export default (prevState = initialLoginState, action) => {
switch (action.type) {
case "LOAD_STOCKS":
return {
...prevState,
calendar: {
[action.payload.prop]: action.payload.value,
},
};
default:
return {
...prevState,
};
}
};
If you would like to see the full repo I have linked it down below. I have been trying to figure out the issue for quite some time now and I just need a new perspective on it, thank you so much for your time.
https://github.com/JayPankajPatel/EarningsWhisper
Open CMD and run ipconfig, then copy your ip address there
In your flask code, let say app.py
Change app.run() to
app.run(host=your ip address)
Bear with me, I will explain this the best I can. Please let me know if more information is needed, I am trying to keep this as brief as possible.
I am using Apollo Server and the 'apollo-datasource-rest' plugin to access a REST API. When attempting to get the property values from a nested array of objects I get a null response for each field/property. In addition, the array being queried is only showing a single iteration when multiple are available.
The field in question is the 'cores' field within the Rocket type, i.e., launch.rocket.firstStage.cores
I have attempted various ways of mapping through 'cores' (thinking this was what it wanted) with no success.
To keep things short and simple I'm only including the code for the specific issue. All other parts of the query are operating as expected.
You can view the API response I am hitting here: https://api.spacexdata.com/v3/launches/77
schema.js
const { gql } = require('apollo-server');
const typeDefs = gql`
type Query {
singleLaunch(flightNumber: Int!): Launch
}
type Launch {
flightNumber: Int!
rocket: Rocket
}
type Rocket {
firstStage: Cores
}
type Cores {
cores: [CoreFields]
}
type CoreFields {
flight: Int
gridfins: Boolean
legs: Boolean
reused: Boolean
landingType: String
landingVehicle: String
landingSuccess: Boolean
}
`;
module.exports = typeDefs;
Data Source - launch.js
const { RESTDataSource } = require('apollo-datasource-rest');
class LaunchAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://api.spacexdata.com/v3/';
}
async getLaunchById({ launchId }) {
const res = await this.get('launches', {
flight_number: launchId,
});
return this.launchReducer(res[0]);
}
launchReducer(launch) {
return {
flightNumber: launch.flight_number || 0,
rocket: {
firstStage: {
cores: [
{
flight: launch.rocket.first_stage.cores.flight,
gridfins: launch.rocket.first_stage.cores.gridfins,
legs: launch.rocket.first_stage.cores.legs,
landingType: launch.rocket.first_stage.cores.landing_type,
landingVehicle: launch.rocket.first_stage.cores.landing_vehicle,
landingSuccess: launch.rocket.first_stage.cores.landing_success,
},
],
},
};
}
}
module.exports = LaunchAPI;
resolvers.js
module.exports = {
Query: {
singleLaunch: (_, { flightNumber }, { dataSources }) =>
dataSources.launchAPI.getLaunchById({ launchId: flightNumber }),
},
};
Query
query GetLaunchById($flightNumber: Int!) {
singleLaunch(flightNumber: $flightNumber) {
flightNumber
rocket {
firstStage {
cores {
flight
gridfins
legs
reused
landingType
landingVehicle
landingSuccess
}
}
}
}
}
Expected Result
{
"data": {
"singleLaunch": {
"flightNumber": 77,
"rocket": {
"firstStage": {
"cores": [
{
"flight": 1,
"gridfins": true,
"legs": true,
"reused": true,
"landingType": "ASDS",
"landingVehicle": "OCISLY",
"landSuccess": true,
},
{
"flight": 1,
"gridfins": true,
"legs": true,
"reused": false,
"landingType": "RTLS",
"landingVehicle": "LZ-1",
"landSuccess": true
},
{
"flight": 1,
"gridfins": true,
"legs": true,
"reused": false,
"landingType": "RTLS",
"landingVehicle": "LZ-2",
"landSuccess": true
},
]
}
},
}
}
}
Actual Result (Through GraphQL Playground)
{
"data": {
"singleLaunch": {
"flightNumber": 77,
"rocket": {
"firstStage": {
"cores": [
{
"flight": null,
"gridfins": null,
"legs": null,
"reused": null,
"landingType": null,
"landingVehicle": null,
"landingSuccess": null
}
]
}
},
}
}
}
Any suggestions as to what I am doing wrong here would be greatly appreciated. Again, let me know if more information is needed.
Thank you!
Missing base url
There should be
await this.get( this.baseURL + 'launches'
IMHO there should be a map used within launchReducer to return an array, sth like:
launchReducer(launch) {
return {
flightNumber: launch.flight_number || 0,
rocket: {
firstStage: {
cores: launch.rocket.first_stage.cores.map(core => ({
flight: core.flight,
gridfins: core.gridfins,
legs: core.legs,
landingType: core.landing_type,
landingVehicle: core.landing_vehicle,
landSuccess: core.land_success,
})),
},
},
};
}
.map(core => ({ is for returning object [literal], the same as/shorter version of .map(core => { return {
According to the docs, I should use a post_poll function to add the missing id field in the response.
How do I add the post_poll function ?
Here's my error:
Results must be an array, got: object,
({"totalevents":83,"events":[{"eventid":10266033,"c)
- Got a result missing the "id" property (83)
Tried following this but it is not clear to me, I'm very new to Zapier-CLI
Update - adding code
This is the function that returns the data:
const listEvents = (z, bundle) => {
console.log('listing events.. ');
let client_id = bundle.inputData.client_id;
const requestOpts = {
url: `https://wccqa.on24.com/wcc/api/v2/client/${client_id}/event`
};
return z.request(requestOpts)
.then((response) => {
return z.JSON.parse(response.content);
});
};
The sample response is the following, with the distiction that I added the id param manually to avoid errors when zapier test|push:
{
"id": 9964513,
"eventid": 9964513,
"archivestart": "2017-09-21T10:30:00-07:00",
"archiveend": "2018-09-21T10:30:00-07:00",
"description": "Zapier Event Test",
"iseliteexpired": "N",
"displaytimezonecd": "America/Bogota",
"eventtype": "Live Webcam ",
"regrequired": true,
"clientid": 22921,
"liveend": "2017-09-21T10:00:00-07:00",
"createtimestamp": "2017-09-21T09:47:44-07:00",
"audienceurl": "https://localhost.on24.com/wcc/r/9964513/C49755A02229BD48E6010848D7C81EF8",
"lastmodified": "2017-09-21T09:47:44-07:00",
"livestart": "2017-09-21T08:45:00-07:00",
"goodafter": "2017-09-21T09:00:00-07:00",
"regnotificationrequired": true,
"isactive": true,
"localelanguagecd": "en"
}
The ACTUAL response from the endpoint the following which is used in the app created in the Web Builder App instead of CLI and works fine:
{
"events": [
{
"eventid": 9964513,
"archivestart": "2017-09-21T10:30:00-07:00",
"archiveend": "2018-09-21T10:30:00-07:00",
"description": "Zapier Event Test",
"iseliteexpired": "N",
"displaytimezonecd": "America/Bogota",
"eventtype": "Live Webcam ",
"regrequired": true,
"clientid": 22921,
"liveend": "2017-09-21T10:00:00-07:00",
"createtimestamp": "2017-09-21T09:47:44-07:00",
"audienceurl": "https://localhost.on24.com/wcc/r/9964513/C49755A02229BD48E6010848D7C81EF8",
"lastmodified": "2017-09-21T09:47:44-07:00",
"livestart": "2017-09-21T08:45:00-07:00",
"goodafter": "2017-09-21T09:00:00-07:00",
"regnotificationrequired": true,
"isactive": true,
"localelanguagecd": "en"
}
],
"totalevents": 1
}
I was thinking something along the line of the following, but how do I register this ?
const postPoll = (event,z,bundle) => {
if(event.key === 'events'){
var results = z.JSON.parse(bundle.request.data).results;
var events = results.events.map(function(event){
event.id = event.eventid;
return event;
});
bundle.request.data = events;
}
};
module.exports = postPoll;
Nice, so you're almost there! CLI apps don't have pre_ and post_ poll methods. Instead, you put any manipulation after the response comes in.
const listEvents = (z, bundle) => {
console.log('listing events.. ');
let client_id = bundle.inputData.client_id;
const requestOpts = {
url: `https://wccqa.on24.com/wcc/api/v2/client/${client_id}/event`
};
return z.request(requestOpts)
.then((response) => {
return z.JSON.parse(response.content);
})
.then(data => {
const events = data.events; // array of events
return events.map(function(e){ // returns array of objects with `id` defined
e.id = e.event_id
return e
})
})
};