Getting index out of range error when creating metaplex metadata account - token

Why am I getting the following error when trying to create a metadata account using createCreateMetadataAccountV2Instruction from the #metaplex-foundation/mpl-token-metadata library?
SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Program failed to complete
at Connection.sendEncodedTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4464:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Connection.sendRawTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4423:20)
at async Connection.sendTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4411:12)
at async sendAndConfirmTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\util\send-and-confirm-transaction.ts:31:21)
at async addMetadataToToken (C:\xampp\htdocs\sol-tools\src\lib\metadata.ts:86:16)
at async Command.<anonymous> (C:\xampp\htdocs\sol-tools\src\cli.ts:48:7) {
logs: [
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s invoke [1]',
'Program log: Instruction: Create Metadata Accounts v2',
"Program log: panicked at 'range end index 36 out of range for slice of length 0', program/src/utils.rs:231:27",
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s consumed 6223 of 1400000 compute units',
'Program failed to complete: BPF program panicked',
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s failed: Program failed to complete'
]
}
Here's my code:
import {
createCreateMetadataAccountV2Instruction,
PROGRAM_ID,
} from '#metaplex-foundation/mpl-token-metadata'
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
Transaction,
} from '#solana/web3.js'
export const addMetadataToToken = async (
connection: Connection,
tokenMint: PublicKey,
tokenOwner: Keypair,
name: string,
symbol: string,
arweaveLink: string
) => {
const seed1 = Buffer.from('metadata', 'utf8')
const seed2 = PROGRAM_ID.toBuffer()
const seed3 = tokenMint.toBuffer()
const [metadataPDA, _bump] = PublicKey.findProgramAddressSync(
[seed1, seed2, seed3],
PROGRAM_ID
)
const accounts = {
metadata: metadataPDA,
mint: tokenMint,
mintAuthority: tokenOwner.publicKey,
payer: tokenOwner.publicKey,
updateAuthority: tokenOwner.publicKey,
}
const dataV2 = {
name,
symbol,
uri: arweaveLink,
// we don't need these
sellerFeeBasisPoints: 0,
creators: null,
collection: null,
uses: null,
}
const args = {
createMetadataAccountArgsV2: {
data: dataV2,
isMutable: true,
},
}
const ix = createCreateMetadataAccountV2Instruction(accounts, args)
const tx = new Transaction()
tx.add(ix)
const txid = await sendAndConfirmTransaction(connection, tx, [tokenOwner])
console.log(txid)
}

Turns out I was on trying to create metadata for a token on devnet, but was using a mainnet-beta rpc endpoint for the Connection class. Thus the token I was trying to create metadata for didn't exist.

This is a really Common Error Message that occurs when there is some issue with what you are passing to the program. So make sure everything that you are input to the program is correct. In 90% of the cases, it gets resolved when checking the inputs correctly.

Related

Zoho Catalyst Data Store, Functions - Unable to retrieve a row

I'm trying to get a row from datastore, while trying I've got the below error.I've included the script I'm trying.
Output:
{
"status": "failure",
"data": {
"message": "basicio Execution Time Exceeded",
"error_code": "EXECUTION_TIME_EXCEEDED"
}
}
Code Snippet :
let rowData =
{
response: "George Hamilton",
};
const https = require("https");
const axios = require("axios");
const catalyst = require("zcatalyst-sdk-node");
const app = catalyst.initialize(context);
let datastore = app.datastore();
let table = datastore.table('xxxx');
let rowPromise = table.getRow(xxxxx);
basicIO.write(rowPromise + "");
}
Zoho Catalyst Basic IO functions will have an execution timeout of maximum of 30 seconds. Missing of proper exception handling might also lead to a timeout. Enclose your code in a try catch block in order to catch the exceptions and you need to await in table.getRow() since it returns a promise and you have to resolve the promise by using .then().
let rowPromise = await table.getRow('xxxxx');
rowPromise.then((response) => {
console.log(response);
res.status(200).send(JSON.stringify(response));
}).catch((err)=> {
console.log(err);
res.status(500).send(err.toString());
})

Trying to run the Hyperledger calliper on my chaincode in test network and keep getting errors with create transaction

I am new to the block chain. Trying to run the calliper on my chaincode, in the the test network and getting the following errors. Not sure what I need to do here, to get the arguments be passed successfully to the chaincode.
Calliper command I used:
npx caliper launch manager --caliper-workspace ./ --caliper-networkconfig networks/networkConfig.yaml --caliper-benchconfig benchmarks/myPolicyBenchmark.yaml --caliper-flow-only-test --caliper-fabric-gateway-enabled
My Workload
'use strict';
const { WorkloadModuleBase } = require('#hyperledger/caliper-core');
class MyWorkload extends WorkloadModuleBase {
constructor() {
super();
}
async initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext) {
await super.initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext);
for ( let i=0; i<this.roundArguments.policies; i++) {
const policyID = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Creating policy ${policyID}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: 'CreatePolicy',
invokerIdentity: 'Admin',
contractAtguments: [policyID,"Test Policy 2","This is a test policy", "PUBLIC","PUBLIC","[\"READ\"]", "ABC", "abc#gmail.com", "[\"NONE\"]", "{}"],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
async submitTransaction() {
const randomId = Math.floor(Math.random()*this.roundArguments.policies);
const myArgs = {
contractId: this.roundArguments.contractId,
contractFunction: 'ReadPolicy',
invokerIdentify: 'Admin',
//contractArguments: [`${this.workerIndex}_${randomId}`],
contractArguments: ['3'],
readOnly: true
};
await this.sutAdapter.sendRequests(myArgs);
}
async cleanupWorkloadModule() {
for (let i=0; i<this.roundArguments.policies; i++){
const policyID = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Deleting policy ${policyID}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: 'DeletePolicy',
invokerIdentity: 'Admin',
contractAtguments: [policyID],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
}
function createWorkloadModule() {
return new MyWorkload();
}
module.exports.createWorkloadModule = createWorkloadModule;
The error I get is
2022.06.14-00:46:51.063 info [caliper] [caliper-worker] Info: worker 0 prepare test phase for round 0 is starting...
Worker 0: Creating policy 0_0
2022.06.14-00:46:51.078 info [caliper] [caliper-worker] Info: worker 1 prepare test phase for round 0 is starting...
Worker 1: Creating policy 1_0
2022-06-14T06:46:51.130Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
2022.06.14-00:46:51.132 error [caliper] [connectors/v2/FabricGateway] Failed to perform submit transaction [CreatePolicy] using arguments [], with error: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
at newEndorsementError (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:49:12)
at getResponsePayload (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:17:23)
at Transaction.submit (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:212:28)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async V2FabricGateway._submitOrEvaluateTransaction (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-fabric/lib/connector-versions/v2/FabricGateway.js:376:26)
at async V2FabricGateway._sendSingleRequest (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-fabric/lib/connector-versions/v2/FabricGateway.js:170:16)
at async V2FabricGateway.sendRequests (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/common/core/connector-base.js:78:28)
at async MyWorkload.initializeWorkloadModule (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/workload/readPolicy.js:25:13)
at async CaliperWorker.prepareTest (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/worker/caliper-worker.js:160:13)
at async WorkerMessageHandler._handlePrepareMessage (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/worker/worker-message-handler.js:210:13)
The same inputs works fine with running through the peer
peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem" -C mychannel -n policylist --peerAddresses localhost:7051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" --peerAddresses localhost:9051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt" -c '{"function":"CreatePolicy","Args":["4","Test Policy 2","This is a test policy", "PUBLIC","PUBLIC","[\"READ\"]", "ABC", "abc#gmail.com", "[\"NONE\"]", "{}" ]}'
2022-06-14 00:58:06.489 CST 0001 INFO [chaincodeCmd] chaincodeInvokeOrQuery -> Chaincode invoke successful. result: status:200 payload:"{\"PolicyId\":\"4\",\"docType\":\"PolicyDoc\",\"PolicyName\":\"Test Policy 2\",\"PolicyDescription\":\"This is a test policy\",\"PolicyDataClassification\":\"PUBLIC\",\"PolicyAccessCategory\":\"PUBLIC\",\"PolicyAccessMethod\":[\"READ\"],\"PolicyOwner\":\"ABC\",\"PolicyApprovalStatus\":\"NEW\",\"PolicyCreatedOn\":\"Tue, 14 Jun 2022 06:58:06 GMT\",\"PolicyContactEmail\":\"abc#gmail.com\",\"PolicyRestrictions\":\"[\\\"NONE\\\"]\",\"PolicyMiscellaneous\":{}}"

Invalid value for transfer while using ipcRenderer.postMessage of electron

Invalid value for transfer while using ipcRenderer.postMessage of electron?I don't know what's wrong with it
// eslint-disable-next-line no-undef
const { port1 } = new MessageChannel();
// eslint-disable-next-line no-undef
ipcRenderer.postMessage('port', { message: 'hello' }, [port1]);
I wonder if something wrong in my preload.js?
I upload all my code to github
https://github.com/codeh2o/electronVuePreloadIssue

How to write the completion for the callable function for Stripe Apple Pay for Native iOS

I'm following the Stripe Apple Pay documentation. I don't know how to pass the client secret. I'm passing the data to Stripe. The order goes through but I'm not returning the information back to my app to notify the user. The error I'm getting is: Assertion failed: secret format does not match expected client secret formatting.
The callable function asks for a String in the success completion but I don't know how to extract it.
The code shown in the documentation is as follows:
// Set your secret key. Remember to switch to your live secret key in production!
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_THISISMYSTRIPETESTKEY');
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
});
const clientSecret = paymentIntent.client_secret
// Pass the client secret to the client
In my index.js for my Cloud Functions, I have a createApplePayCharge function shown below:
exports.createApplePayCharge = functions.https.onCall( async (data, context) => {
const amount = data.total;
const customerId = data.customer_id;
const paymentMethodId = data.payment_method_id;
const idempotency = data.idempotency;
const description = data.description;
const paymentIntent = await stripe.paymentIntents.create({
payment_method: paymentMethodId,
customer: customerId,
amount: amount,
description: description,
currency: 'usd',
confirm: true,
payment_method_types: ['card']
}, {
idempotencyKey: idempotency
}).then(object => {
console.log('Charge Success: ', object.id);
return paymentIntent.client_secret;
}).catch(err => {
console.log(err);
throw new functions.https.HttpsError('internal', ' Unable to create charge: ' + err);
});
});
And in my ProductViewController where I display the Apple Pay Button I have the following function:
func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: STPPaymentMethod, paymentInformation: PKPayment, completion: #escaping STPIntentClientSecretCompletionBlock) {
let idempotency = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let data : [String: Any] = [
"total" : 30000.00,
"customer_id" : Api.userService.user.stripeId,
"payment_method_id" : paymentMethod.stripeId,
"idempotency" : idempotency,
"description" : "Mobile Order - Apple Pay"
]
Functions.functions().httpsCallable(Firebase_Functions.applePayCharge).call(data) { (result, error) in
if let error = error {
completion(error.localizedDescription, error)
return
}
completion("Need a String here", nil)
}
}
The problem I'm having is that I can not find the String I need for the error and success completions in the code above which is the reason why the app either crashes or does not complete the order process with the following error: Assertion failed: secret format does not match expected client secret formatting.

Passing array object in find Method (TypeORM)

I am migrating the API to TypeORM from mongoose. I have an array(conversationIds) containing list of id to be searched from the Database and it should return me the available id. Below are the query which i have tried.
const conversationMessagesWithDuplicates = await consversationRepository.createQueryBuilder("conversation").where("conversation.channel_message_ID = :channel_message_ID",{channel_message_ID : conversationIds}).getMany();
and also this one
const conversationMessagesWithDuplicates = await consversationRepository.find({channel_message_ID: conversationIds});
But i am getting below issue:
(node:11548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): QueryFailedError: Error: Incorrect syntax near ','.
I have tried using entity Manger also but no success
const conversationMessagesWithDuplicates = await entityManager.query(`SELECT channel_message_ID FROM Conversation where channel_message_ID IN (conversationIds)`);
Below is the MoongoseAPI which is working fine:
Conversation.find( { channel_message_ID: { $in: conversationMessageIdArray } } ).exec(function(err, conversationMessagesDuplicatesArray) {}
This is the solution
const conversationMessagesWithDuplicates = await consversationRepository.createQueryBuilder("conversation").where("conversation.channel_message_ID IN (:conversationIds)", { conversationIds: conversationIds }).getMany();

Resources