UnhandledPromiseRejectionWarning: Error: The contract code couldn't be stored, please check your gas limit - node.js

I am trying to deploy my simple solidity smart contract onto the Rinkeby Network but I keep getting the error:
UnhandledPromiseRejectionWarning: Error: The contract code couldn't be
stored, please check your gas limit.
My solidity code is simple
pragma solidity ^0.4.18;
contract Greetings{
string public message;
function Greetings(string initialMessage) public{
message = initialMessage;
}
function setMessage(string newMessage) public {
message = newMessage;
}
}
and my deploy script is:
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface,bytecode} = require('./compile');
const provider = new HDWalletProvider(
'twelve word mnemonic...',
'https://rinkeby.infura.io/GLm6McXWuaih4gqq8nTY'
);
const web3 = new Web3(provider);
const deploy = async () => {
accounts = await web3.eth.getAccounts();
console.log('attempting to deploy from account',accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode, arguments:['Hello World']})
.send({from: accounts[0], gas:'1000000'});
console.log('Contract deployed to', result.options.address);
};
deploy();
Funny thing is, I used to be able to deploy successfully, but when i created a new project and re did the same code, i get this error now. Please help!

Had exactly same problem! Seems it is caused by the bug in the "truffle-hdwallet-provider" version 0.0.5. During the udemy course it was using "0.0.3" apparently.
If you do the following should be okay, it worked for me.
npm uninstall truffle-hdwallet-provider
npm install --save truffle-hdwallet-provider#0.0.3
Then I ran the same contract which has deployed successfully.
Good luck!

This issue can be solved by adding the '0x' as the prefix of the bytecode:
.deploy({ data: '0x' + bytecode, arguments: ['Hi there!'] })
More information is at https://ethereum.stackexchange.com/a/47654.

I believe bytecode is being treated as a single number rather than a series of bytes. Instead of submitting data:bytecode, try:
data:'0x0' + bytecode
it will "preserve" bytecode value as a string

Also just remove the gas field let metamask decide the gas limit. this way works for me.

Related

Why does my Firebase/Postmark email despatch function fail to deploy?

Firebase deployment of my function fails with the following error:
"Function failed on loading user code. This is likely due to a bug in the user code."
Here's the function code:
const postmark = require("postmark");
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp()
exports.sendPostmarkEmailFunction = functions.firestore.
document('/postmarklogs/{documentId}').
onCreate((snapShot, context) => {
var serverToken = "_my_client_key_";
var client = new postmark.ServerClient(serverToken);
try {
client.sendEmail({
"From": "_my_depatch_address_",
"To": "_my_receipt_address_",
"Subject": snapShot.data().subject,
"HtmlBody": snapShot.data().message
});
return true;
} catch (error) {
console.log("Error : " + error.ErrorCode + " : " + error.Message);
return false;
}
});
This code works just fine in the Firebase emulator. As far as I can see, the deployment issue is triggered specifically by the const postmark = require("postmark"); line. If I comment this out, the function deploys - but then of course it doesn't work!
Advice would be greatly appreciated.
Postmark needs to be installed in the project's 'functions' folder. I'd installed it into the body of the project and so Postmark was missing from the 'functions/package.json' file that guides deployment's build stage. The 'functions' folder created by firebase init functions is like a project within a project and needs to be treated as such.
I got onto the problem from the deployment "build" logs
Once Postmark had been installed in the 'functions' folder my sendPostmarkEmailFunction function worked perfectly.
In passing, unless you already know this, the Postmark API token really needs to be squirreled securely away in the Firebase environment variable store. Also, while you might be tempted to use an https.onRequest trigger rather than the onCreate() used here, you might like to know that this is likely to land you in endless CORS issues when used with Postmark.

Solana program to send multiple lamport transfers and emit event

I’m building a program intended to manage multiple payments with one call. The program needs to complete the following steps:
Accept a certain amount of lamports
Pay a portion of the received lamports to specified wallets, such that the amount received is exhausted
Emit an event containing the receipt
I’ve built this logic with an Ethereum smart contract and it works perfectly fine, however when attempting to write a Solana program with Solang and #solana/solidity, I’m running into a number of issues.
The first issue I encountered was simply that #solana/solidity seems to not be built for front end use (transactions required a private key as an argument, rather than being signed by a wallet like Phantom) so I built a fork of the repository that exposes the transaction object to be signed. I also found that the signer’s key needed to be manually added to the array of keys in the transaction instruction — see this Stack Overflow post for more information, including the front end code used to sign and send the transaction.
However, after this post I ran into more errors, take the following for example:
Transaction simulation failed: Attempt to debit an account but found no record of a prior credit.
Transaction simulation failed: Error processing Instruction 0: instruction changed the balance of a read-only account
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N invoke [1]
Program data: PO+eZwYByRZpDC4BOjWoKPj20gquFc/JtyxU9NsuG/Y= DEjYtM7vwjNW3HPewJU3dvG4aiov5tUUlrD6Zz5ylBgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADppnQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATEtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVNC02S0gyMV9Sa3RZZVJIb3FKOFpFAAAAAAAAAAAAAAA=
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N consumed 3850 of 200000 compute units
Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N success
failed to verify account 11111111111111111111111111111111: instruction changed the balance of a read-only account
The error messages seemed to be inconsistent, with some attempts throwing different errors despite the only changes in the code being a server restarting or a library being reinstalled.
Although solutions to the previous errors would be greatly appreciated, at this point I’m more inclined to ask more broadly if what I’m trying to do is possible, and, providing the source code, for help understanding what I need to do to make it work.
Below is the working source code for my Ethereum contract:
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
contract MyContract {
event Receipt(
address From,
address Token,
address[] Receivers,
uint256[] Amounts,
string Payment
);
function send(
address[] calldata _receivers,
uint256[] calldata _amounts,
string calldata _payment
) external payable {
require(
_receivers.length == _amounts.length,
"Receiver count does not match amount count."
);
uint256 total;
for (uint8 i; i < _receivers.length; i++) {
total += _amounts[i];
}
require(
total == msg.value,
"Total payment value does not match ether sent"
);
for (uint8 i; i < _receivers.length; i++) {
(bool sent, ) = _receivers[i].call{value: _amounts[i]}("");
require(sent, "Transfer failed.");
}
emit Receipt(
msg.sender,
0x0000000000000000000000000000000000000000,
_receivers,
_amounts,
_payment
);
}
}
The only differences between this code and my Solana program code are types and the method used to transfer lamports. All references to uint256 is replaced by uint64, the placeholder token address is changed from the null address to the system public key (address"11111111111111111111111111111111"), and the payment loop is changed to the following:
for (uint8 i = 0; i < _receivers.length; i++) {
payable(_receivers[i]).transfer(_amounts[i]); // Using .send() throws the same error
}
The code used to then deploy the program to the Solana test validator is as follows, only slightly modified from the example provided by #solana/solidity:
const { Connection, LAMPORTS_PER_SOL, Keypair, PublicKey } = require('#solana/web3.js');
const { Contract } = require('#solana/solidity');
const { readFileSync } = require('fs');
const PROGRAM_ABI = JSON.parse(readFileSync('./build/sol/MyProgram.abi', 'utf8'));
const BUNDLE_SO = readFileSync('./build/sol/bundle.so');
(async function () {
console.log('Connecting to your local Solana node');
const connection = new Connection('http://localhost:8899', 'confirmed');
const payer = Keypair.generate();
async function airdrop(pubkey, amnt) {
const sig = await connection.requestAirdrop(pubkey, amnt * LAMPORTS_PER_SOL);
return connection.confirmTransaction(sig);
}
console.log('Airdropping SOL to a new wallet');
await airdrop(payer.publicKey, 100);
const program = new Keypair({
publicKey: new Uint8Array([...]),
secretKey: new Uint8Array([...])
});
const storage = new Keypair({
publicKey: new Uint8Array([...]),
secretKey: new Uint8Array([...])
});
const contract = new Contract(connection, program.publicKey, storage.publicKey, PROGRAM_ABI, payer);
console.log('Loading the program');
await contract.load(program, BUNDLE_SO);
console.log('Deploying the program');
await contract.deploy('MyProgram', [], program, storage, 4096 * 8);
console.log('Program deployed!');
process.exit(0);
})();
Is there something I’m misunderstanding or misusing here? I find it hard to believe that such simple behavior on the Ethereum blockchain couldn’t be replicated on Solana — especially given the great lengths the community has gone to to make Solana programming accessible through Solidity. If there’s something I’m doing wrong with this code I’d love to learn. Thank you so much in advance.
Edit: After upgrading my solang version, the first error was fixed. However, I'm now getting another error:
Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: instruction changed the balance of a read-only account
I'm not sure which account is supposedly read-only, as it isn't listed in the error response, but I'm pretty sure the only read-only account involved is the program as it's executable. How can I avoid this error?
The error Attempt to debit an account but found no record of a prior credit happens when you attempt to airdrop more than 1 SOL. If you wish to have more than 1 SOL, then airdrop 1 SOL in a loop until you have enough.

UnhandledPromiseRejectionWarning in google translate api with node.js

const projectId = 'natural-nebula-number';
const {
Translate
} = require('#google-cloud/translate').v2;
const translate = new Translate({
projectId,
});
async function quickStart() {
const text = 'Hello, world!';
const target = 'ru';
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
quickStart();
I wrote some code for using google translate api with node.js
i had install #google-cloud/translate. through npm.
and i did copy,paste code in this site google api usage
but i got some error on my command
here is the error message.
(node:440) UnhandledPromiseRejectionWarning: Error: The request is missing a valid API key.
at new ApiError (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:73:15)
at Util.parseHttpRespBody (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:208:38)
at Util.handleResp (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:149:117)
at /mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:477:22
at onResponse (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/retry-request/index.js:228:7)
at /mnt/c/Users/U suk jang/Desktop/testinf/node_modules/teeny-request/build/src/index.js:226:13
i wrote actually full projectid (of couse real number).
but they say they cannot find my api key.
how should i give my api key to google
and where is the google-docs for this problem?
You copy-pasted the code in the link provided, but did you read the article and follow all prerequisite steps? It links to another article, Cloud Translation: NodeJS Client. There you will find that you need to pay special attention top step 4 (authentication) mentioned under the Quickstart paragraph. Without it, the used client library will not find your API key.

How to pass string[] as a parameter to solidity function?

I'm trying to pass a string[] from node.js to solidity function:
function test(string[] memory options) public {}
like this way:
const options = ["a","b","c"]
const contract = this.getContract();
const testFunc = contract.functions['test'];
await testFunc(options);
but got the error: invalid value for array;
Solidity pragma:
pragma solidity 0.6.5;
pragma experimental ABIEncoderV2;
Also, if I call a contract from Etherscan with the same value it works
contract.functions is used in ethers.js (docs). Since your question is tagged web3, my answer is using the web3 library.
Assuming that this.getContract() returns the Contract instance, you can execute a contract method using the contract.methods (docs) object.
Use .send() to send a read-write transaction from your configured wallet, or .call() to make a read-only call.
const options = ["a","b","c"]
const contract = this.getContract();
await contract.methods.test(options).send();
Building on the previous answer and your comment about using ethers, this is how I would do this (I use ethers too - just update your dependencies' versions to save headaches if you can):
const options = ["a","b","c"]
//either this for deployed contract:
const contract = await ethers.getContractAt(contractABI, contractAddress, signer);
//or this, for undeployed contract:
contract = await ethers.getContractFactory("myContract");//your contract's name; //compile first
contract = await contract.deploy();
await contract.deploy();
// simplest foolproofer, can "prettify" for github later:
contract = contract.connect(signer);
//now for the real action:
await contract.test(options);

getting a parse error and cannot find eslint file

I've realized that you can't send messages directly from the client with the FCM v1 API so now I'm using node.js and I wan't to deploy this cloud function, but I am getting a parse error like so:
This is my function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { event } = require("firebase-functions/lib/providers/analytics");
admin.initializeApp(functions.config().firebase);
exports.sendNotificationsToTopic =
functions.firestore.document("school_users/{uid}/events/{docID}").onWrite(async (event) => {
let docID = event.after.id;
let schoolID = event.after.get("school_id")
let title = "New Event!!"
let notificationBody = "A new event has been added to the dashboard!!"
var message = {
notification: {
title: title,
body: notificationBody,
},
topic: schoolID,
};
let response = await admin.messaging().sendToTopic(message);
console.log(response);
});
I did some research and found people were getting similar errors with their projects, and answers were saying to update the version of eslint so it picks up on the shorthand syntax, I can't figure out where to find the eslint file to update the version. Does anybody know where I can find this file?
All I needed to do was show my hidden files in my functions directory. Once I seen the .eslintrc.js file, I simply removed a part of a value from the "eslint" key, and the function deployed perfectly fine.

Resources