How to create signature as an input for type Vec<u8> on smart contract - sign

I'm trying to create a signature for my function in smart contract but it return "invalid type: map, expected a sequence" error.
Here is the code:
async function onSign() {
const nearConfig = getConfig('development')
// Initialize connection to the NEAR testnet
const near = await connect(Object.assign({ deps: { keyStore: new keyStores.BrowserLocalStorageKeyStore() } }, nearConfig))
window.near = near
// Initializing Wallet based Account. It can work with NEAR testnet wallet that
// is hosted at https://wallet.testnet.near.org
window.walletConnection = new WalletConnection(near)
// Getting the Account ID. If still unauthorized, it's just empty string
window.accountId = window.walletConnection.account()
let account = window.accountId;
const realSigner = account.connection.signer
let key2 = await realSigner.keyStore.getKey(account.connection.networkId, account.accountId)
let mess = 'zxczxvzvx';
let encodedMess = str2ab(mess);
let signature = await key2.sign(encodedMess);
console.log(signature);
let a = await wallet.callMethod({
contractId: "dev-1668740733204-48404403176628",
method: "ft_transfer_call",
args: {
"receiver_id": "dev-1669022432132-58804567266197",
"amount": "0",
"memo": "None",
"msg": "create_room",
"_advisor": "dev-1669018198583-29903555965521",
"_amount_per_minute": "1",
"_room_id": "1",
"_minutes_lasts": 5,
"_signature": Buffer.from(signature.signature, 'hex'),
"_signer": "tungleanh.testnet",
}
})
}
Here is the parameters on smart contract:
&mut self,
receiver_id: AccountId,
amount: U128,
memo: Option,
msg: String,
_advisor: Option,
_amount_per_minute: Option,
_room_id: Option,
_minutes_lasts: Option,
_signature: Option<Vec>,
_signer: Option<Vec>,
How can I fix this?

Related

Ethers: invalid object key

I'm tryin send transaction via ethers, seems looks good, but has error...
Connections with wallet ok.
Code bellow:
const { ethers } = require("ethers");
(async () => {
prov2="provider url Alchemy"
const provider = new ethers.providers.JsonRpcProvider(prov2);
let wallet = ethers.Wallet.fromMnemonic("my mnemonic")
const signer = wallet.connect(provider)
const gasPrice = provider.getGasPrice();
let nonce = await provider.getTransactionCount(
wallet.address,
"latest"
);
const recepient = "0x00000000006c3856cbEf3e08E8dF289169EdE581";
let txn = {
type: 2,
chainId: 5,
from: wallet.address,
to: recepient,
value: ethers.utils.parseUnits("0.000001", "ether"),
maxPriorityFeePerGas: ethers.utils.parseUnits("150","gwei"),
maxFeePerGas: ethers.utils.parseUnits("170","gwei"),
nonce: nonce
};
try {
let signedTx = await signer.sendTransaction(txn)
const receipt = await txn.wait();
console.log(receipt);
} catch (e) {
console.log(e.name)
console.log(e.message)
}
})();
And got: invalid object key error ....
I tried googling the error, but got nothing
What can it be?
The error message says "object key error". I suspect that your transaction object.
let txn = {type: 2,...}
is not correct. I checked the https://docs.ethers.io/v5/api/utils/transactions/ and there is no type key property in the transaction object

Flutter aws amplify not returning data when calling graphql api

On button click I have programmed to call a graphql api which is connected to a Lambda function and the function is pulling data from a dynamodb table. The query does not produce any error, but it doesn't give me any results as well. I have also checked the cloudwatch logs and I dont see any traces of the function being called. Not sure on the careless mistake I am making here.
Here is my api
void findUser() async {
try {
String graphQLDocument = '''query getUserById(\$userId: ID!) {
getUserById(userId: \$id) {
id
name
}
}''';
var operation = Amplify.API.query(
request: GraphQLRequest<String>(
document: graphQLDocument,
variables: {'id': 'USER-14160000000'}));
var response = await operation.response;
var data = response.data;
print('Query result: ' + data);
} on ApiException catch (e) {
print('Query failed: $e');
}
}
Here is my lambda function -
const getUserById = require('./user-queries/getUserById');
exports.handler = async (event) => {
var userId = event.arguments.userId;
var name = event.arguments.name;
var avatarUrl = event.arguments.avatarUrl;
//console.log('Received Event - ', JSON.stringify(event,3));
console.log(userId);
switch(event.info.fieldName) {
case "getUserById":
return getUserById(userId);
}
};
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'ca-central-1'});
async function getUserById(userId) {
const params = {
TableName:"Bol-Table",
KeyConditionExpression: 'pk = :hashKey and sk = :sortKey',
ExpressionAttributeValues: {
':hashKey': userId,
':sortKey': 'USER'
}
};
try {
const Item = await docClient.query(params).promise();
console.log(Item);
return {
id: Item.Items[0].pk,
name: Item.Items[0].details.displayName,
avatarUrl: Item.Items[0].details.avatarUrl,
createdAt: Item.Items[0].details.createdAt,
updatedAt: Item.Items[0].details.updatedAt
};
} catch(err) {
console.log("BOL Error: ", err);
}
}
module.exports = getUserById;
Upon button click I get this
Moving my comment to an answer:
Can you try changing your graphQLDocumnet to
String graphQLDocument = '''query getUserById(\$id: ID!) {
getUserById(userId: \$id) {
id
name
}
}''';
Your variable is $userId and then $id. Try calling it $id in both places like in your variables object.
Your flutter code is working fine but in lambda from the aws is returning blank string "" to not to print anything

Transaction reverted during swapExactTokensForTokens (UniswapV2Router02, web3.js)

I am attempting to swap ETH for DAI using the Uniswap Router, but am facing a problem where the transaction gets reverted, along with the following message: Transaction has been reverted by the EVM.
I am testing this on the Rinkeby Testnet.
Here is the full message, along with the accompanying block information:
Transaction has been reverted by the EVM:
{
"blockHash": "0xfaa3effa60d646ef4db959cba460dac74aafd1c0b667c91758be71a735f949ce",
"blockNumber": 9146763,
"contractAddress": null,
"cumulativeGasUsed": 1678679,
"effectiveGasPrice": "0x3b9aca09",
"from": "0xbd8b57fdbd794f125a9d6a3a7bd8958d46201b37",
"gasUsed": 30348,
"logs": [],
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"status": false,
"to": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d",
"transactionHash": "0x7c5b33a7a751430ba0e0347a29b01a12db0b1da71a17a36deb4c773ea5ff483c",
"transactionIndex": 6,
"type": "0x0"
}
at Object.TransactionError (../node_modules/web3-core-helpers/lib/errors.js:87:21)
at Object.TransactionRevertedWithoutReasonError (../node_modules/web3-core-helpers/lib/errors.js:98:21)
at ../node_modules/web3-core-method/lib/index.js:394:57
I will also provide the NodeJS code I am running:
import Web3 from "web3";
const IERC20 = require('#uniswap/v2-periphery/build/IERC20.json')
const IPair = require('#uniswap/v2-core/build/IUniswapV2Pair.json')
const IFactory = require('#uniswap/v2-core/build/IUniswapV2Factory.json')
const IRouter = require('#uniswap/v2-periphery/build/IUniswapV2Router02.json')
export class TransactionService {
async transact() {
const privKey = "<privkey ommitted>";
var web3 = new Web3('https://rinkeby.infura.io/v3/<infura-rinkeby-path>');
var factory = new this.web3.eth.Contract(IFactory.abi, "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f");
var address = "0xbd8B57fdBD794f125a9D6A3A7bd8958D46201b37";
var daiExchangeAddress = "0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735";
var ethExchangeAddress = '0xc778417E063141139Fce010982780140Aa0cD5Ab';
var rinkebyRouterAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';
var router = new this.web3.eth.Contract(IRouter.abi, rinkebyRouterAddress);
var token0 = new this.web3.eth.Contract(IERC20.abi, ethExchangeAddress) //henceforth T0
var token1 = new this.web3.eth.Contract(IERC20.abi, daiExchangeAddress) //and T1
var pair = new this.web3.eth.Contract(IPair.abi,
(await factory.methods.getPair(token0.options.address, token1.options.address).call()));
const gasPrice = await web3.eth.getGasPrice()
const gasNeeded = (0.15*10**6)*2
const path = [token0.options.address,token1.options.address]
var amountIn = 999999999999;
var tx0 = {
to: token0.options.address,
gas: gasNeeded,
data: token0.methods.approve(router.options.address,amountIn).encodeABI()
}
var signedTx0 = await web3.eth.accounts.signTransaction(tx0, privKey);
var receipt0 = await web3.eth.sendSignedTransaction(signedTx0.rawTransaction)
console.log(
`Tx mined\n`+
`Tx hash: ${receipt0.transactionHash}\n`
)
const tx1 = {
to: router.options.address,
gas: gasNeeded,
data: router.methods.swapExactTokensForTokens(
amountIn,
0,
path,
address,
(Date.now() + 250)
).encodeABI()
}
var signedTx1 = await web3.eth.accounts.signTransaction(tx1, privKey);
var receipt1 = await web3.eth.sendSignedTransaction(signedTx1.rawTransaction);
}
}
As you can see, there are two transactions made. Anapprove and a swapExactTokensForTokens. The contract ABI can be found here. Some documentation on the Router02 is here. The contract itself can be found here. Thank you for any help you can provide.
try to approve to pair address, instead of router address
var tx0 = {
to: token0.options.address,
gas: gasNeeded,
data: token0.methods.approve(pair,amountIn).encodeABI()

Session leak on spanner insert from cloud function

I'm trying to insert data into spanner through cloud function, using post request. I thing that I'm doing everything as described in the documentation, and i just can't understand what causes the next error:
"Error: 1 session leak(s) detected.
at _requests.onIdle.then (/srv/node_modules/#google-cloud/spanner/build/src/session-pool.js:193:25)
at <anonymous>"
And there is my cloud function
const {Spanner} = require('#google-cloud/spanner');
module.exports.http = (req, res) => {
const projectId = 'project-id';
const instanceId = 'instance-id';
const databaseId = 'database-id';
const spanner = new Spanner({
projectId: projectId,
});
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
let sqlResponse = "";
database.runTransaction(async (err, transaction) => {
if (err) {
res.status(500).send(JSON.stringify({message: err, requestBody: req.body}));
return;
}
try {
const data = req.body;
const [rowCount] = await transaction.runUpdate({
sql:
'INSERT Feedbacks (age, comment, gender, rating) VALUES (#age, #comment, #gender, #rating)',
params: {
age: data.age.toString(),
comment: data.comment,
gender: data.gender,
rating: data.rating.toString(),
},
});
sqlResponse = 'Successfully inserted ' + rowCount + ' record into the Feedbacks table.';
await transaction.commit();
res.status(200).send(JSON.stringify({message: sqlResponse, requestBody: req.body}));
} catch (err) {
res.status(500).send(JSON.stringify({message: err, requestBody: req.body}));
} finally {
database.close();
}
});
};
Your code appears to be correct. As noted by #Mayeru in the comments for your question, the first thing to confirm is that you're inserting a new record with a unique value specified for the column that is your table's primary key column.
Another possibility that could be causing the issue you are encountering is that you are trying to test the function using the "Testing" UI of the Cloud Console's Cloud Functions > "Function details" section. If so then you may be either using an empty request body or a malformed request body when you click the "Test the function" button. In the "Triggering event" textarea that appears above the "Test the function" button, make sure you have entered a valid JSON request body which includes the elements and values that your INSERT statement expects.
For example a "Triggering event" JSON request body like the following should work:
{"singerId":"1001","firstName":"Test","lastName":"Singer"}
Using the following "nodeInsert" function that's similar to the code you've shared:
const {Spanner} = require('#google-cloud/spanner');
module.exports.nodeInsert = (req, res) => {
const projectId = 'my-project';
const instanceId = 'my-instance';
const databaseId = 'my-database';
const spanner = new Spanner({
projectId: projectId,
});
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
let sqlResponse = "";
database.runTransaction(async (err, transaction) => {
if (err) {
res
.status(500)
.send(JSON.stringify({message: err, requestBody: req.body}));
transaction.end();
console.error('Transaction terminated.');
return;
}
try {
const data = req.body;
const parsedSingerId = parseInt(data.singerId, 10);
const [rowCount] = await transaction.runUpdate({
sql:
'INSERT Singers (SingerId, FirstName, LastName) VALUES (#singerId, #firstName, #lastName)',
params: {
singerId: parsedSingerId,
firstName: data.firstName,
lastName: data.lastName,
},
});
sqlResponse = 'Successfully inserted ' + rowCount + ' record into the Singers table.';
await transaction.commit();
res
.status(200)
.send(JSON.stringify({message: sqlResponse, requestBody: req.body}));
} catch (err) {
res
.status(500)
.send(JSON.stringify({message: err, requestBody: req.body}));
transaction.end();
console.error('Transaction terminated.');
} finally {
database.close();
}
});
};

Failing to send an ERC20 token using web3.js

I've been struggling to send a token transaction using web3 still after I've read several posts and guides. I'm using human-standard-token-abi to get the ERC20 abi. I'm just trying to transfer 10 ZRX from one address of mine to another.
Here's the function that is failing.
var Tx = require('ethereumjs-tx');
const abi = require('human-standard-token-abi')
import * as Web3 from 'web3';
const fromAddress = '0xB03...'.toLowerCase();
const secondaryAddress = '0xF75...'.toLowerCase();
const zrxAddress = '0xe41d...';
deposit(zrxAddress, secondaryAddress, '10');
function deposit(tokenAddress:string, depositAddress:string, amount:string) {
var count = web3.eth.getTransactionCount(fromAddress);
var contract = web3.eth.contract(abi).at(tokenAddress);
console.log('Contract Address :' + contract.address);
try {
var rawTransaction = {
"from": fromAddress,
"nonce": web3.toHex(count),
"gasPrice": "0x04e3b29200",
"gasLimit": "0x7458",
"to": contract.address,
"value": "0x0",
"data": contract.transfer(depositAddress, size),
"chainId": "0x01"
}
console.log(rawTransaction);
var privKey = new Buffer(key, 'hex');
var tx = new Tx(rawTransaction);
console.log(tx);
//tx.sign(privKey);
var serializedTx = tx.serialize();
} catch (err) {
console.log('\n\nfailed to build');
console.log(err);
}
try {
console.log('\n\nAttempting to send tx');
web3.eth.sendTransaction(tx, function(err, hash) {
if(!err)
console.log(hash);
else
console.log(err);
});
} catch (err) {
console.log('\nfailed to send');
console.log(err);
}
}
I'm currently failing at just building the raw transaction. Here is the error output.
Error: invalid address
at inputAddressFormatter (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/formatters.js:279:11)
at inputTransactionFormatter (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/formatters.js:101:20)
at /home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:90:28
at Array.map (<anonymous>)
at Method.formatInput (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:88:32)
at Method.toPayload (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:116:23)
at Eth.send [as sendTransaction] (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:141:30)
at SolidityFunction.sendTransaction (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/function.js:170:26)
at SolidityFunction.execute (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/function.js:256:37)
at deposit (/home/jall/ZeroExTrading/lib/Transfer.js:56:30)
It seems to be rejecting one of the addresses I'm feeding it but I'm not sure which one. When I log out the tokenAddress, contract.address, and my two addresses they're all defined. But in the web3 source code I added a print statement to see which address it was saying is invalid and the address it gets is 'undefined'.
Your data portion in the tx object is not correct (there may be other issues as well, but that part stands out). You need to pass in the encoded string for your method call. You're actually trying to call the transfer method when setting data.
var rawTransaction = {
"from": fromAddress,
"nonce": web3.toHex(count),
"gasPrice": "0x04e3b29200",
"gasLimit": "0x7458",
"to": contract.address,
"value": "0x0",
"data": contract.transfer.getData(depositAddress, amount),
"chainId": "0x01"
}
(I also changed size to amount. Not sure where size came from.)