After truffle test, we are getting this error: rewards tokens for staking: Error: Returned error: VM Exception while processing transaction: revert - truffle

All the contracts are compiling but error is depicted only in truffle test.
decentalBank.tests.js
// const { assert } = require('console')
const RWD = artifacts.require('RWD')
const Tether = artifacts.require('Tether')
const DecentralBank = artifacts.require('DecentralBank')
require('chai')
.use(require('chai-as-promised'))
.should()
contract('DecentralBank', ([owner, customer]) =>
{
let tether, rwd, decentralBank
function tokens(number)
{
return web3.utils.toWei(number, 'ether')
}
before(async () =>
{
//load contracts
tether = await Tether.new()
rwd = await RWD.new()
decentralBank = await DecentralBank.new(rwd.address, tether.address)
//transfer all tokens to DecentralBank (1 million)
await rwd.transfer(decentralBank.address, tokens('1000000'))
//transfer 100 mock tethers to customer
await tether.transfer(customer, tokens('100'), {from: owner})
})
describe('Mock Tether Deployment' , async () =>
{
it('matches name successfully', async () =>
{
let tether = await Tether.new()
const name = await tether.name()
assert.equal(name, 'Tether')
})
})
describe('Reward Token', async () =>
{
it ('matches name successfully' , async () =>
{
let reward = await RWD.new()
const name = await reward.name()
assert.equal(name, 'Reward Token')
})
})
describe('Decentral Bank Deployment', async () =>
{
it ('matches name successfully' , async () =>
{
let reward = await RWD.new()
const name = await reward.name()
assert.equal(name, 'Reward Token')
})
it('contract has tokens', async () =>
{
let balance = await rwd.balanceof(decentralBank.address)
assert.equal(balance, tokens('1000000'))
})
describe('Yeild Farming', async () =>
{
it('rewards tokens for staking', async () =>
{
let result
//check investor balance
result = await tether.balanceof(customer)
assert.equal(result.toString(), tokens('100'), 'customer mock wallet balance');
//check staking for customer of 100 tokens
await tether.approve(decentralBank.address, tokens('100'), {from: customer})
await decentralBank.depositTokens(tokens('100'), {from: customer})
//check updated balance of customer
result = await tether.balanceof(customer)
assert.equal(result.toString(), tokens('100'), 'customer mock wallet after staking 100 tokens')
//check updated balance of decentral bank
result = await tether.balanceof(decentralBank.address)
assert.equal(result.toString(), tokens('0'), 'decentral bank mock wallet balance after staking')
//(ACTUAL CODE)
// check updated balance of customer
// result = await tether.balanceof(customer)
// assert.equal(result.toString(), tokens('0'), 'customer mock wallet after staking 100 tokens')
// //check updated balance of decentral bank
// result = await tether.balanceof(decentralBank.address)
// assert.equal(result.toString(), tokens('100'), 'decentral bank mock wallet balance after staking')
//is staking balance
result = await decentralBank.isStaking(customer)
assert.equal(result.toString(), 'true', 'customer is staking status after staking')
//issue tokens
await decentralBank.issueTokens({from: owner})
//ensure only the owner can issue tokens
await decentralBank.issueTokens({from: customer}).should.be.rejected;
// //unstake tokens
await decentralBank.unstakeTokens({from: customer})
//check unstaking balances
result = await tether.balanceof(customer)
assert.equal(result.toString(), tokens('0'), 'customer mock wallet after unstaking ')
//check updated balance of decentral bank
result = await tether.balanceof(decentralBank.address)
assert.equal(result.toString(), tokens('100'), 'decentral bank mock wallet balance after staking')
//is staking balance
result = await decentralBank.isStaking(customer)
assert.equal(result.toString(), 'false', 'customer is no longer staking after unstaking')
})
})
})
})
DecentralBank.sol
pragma solidity ^0.5.0;
import './RWD.sol';
import './Tether.sol';
contract DecentralBank
{
string public name = 'Decentral Bank';
address public owner;
Tether public tether;
RWD public rwd;
address[] public stakers;
mapping(address => uint) public stakingBalance;
mapping(address => bool) public hasStaked;
mapping(address => bool) public isStaking;
constructor(RWD _rwd, Tether _tether) public
{
rwd = _rwd;
tether = _tether;
owner = msg.sender;
}
//staking function
function depositTokens(uint _amount) public
{
//require staking amount to be greater than zero
require(_amount > 0 ,'amount cannot be 0');
//trasfer tether tokens to this contract address for staking
tether.transferFrom(msg.sender, address(this), _amount);
//update staking balance
stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount;
if(!hasStaked[msg.sender])
{
stakers.push(msg.sender);
}
//update staking balance
isStaking[msg.sender] = true;
hasStaked[msg.sender] = true;
}
//unstake tokens
function unstakeTokens() public
{
uint balance = stakingBalance[msg.sender];
//require the amount to be greater then zero
require(balance > 0, 'Staking balance cant be less than zero');
//transfer the tokens to the specified contract address from our bank
tether.transfer(msg.sender, balance);
//reset staking balance
stakingBalance[msg.sender] = 0;
//update staking status
isStaking[msg.sender] = false;
}
//issue rewards
function issueTokens() public
{
//only owner can call this function
require(msg.sender == owner, 'caller must be the owner');
for(uint i=0; i<stakers.length; i++)
{
address recipient = stakers[i];
uint balance = stakingBalance[recipient] / 9; //9 to create percentage incentive
if(balance > 0)
{
rwd.transfer(recipient, balance);
}
}
}
}
Migrations.sol
pragma solidity ^0.5.0;
contract Migrations {
address public owner;
uint public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted(){
if (msg.sender == owner) _;
}
function setCompleted(uint completed) public restricted{
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
RWD.sol
pragma solidity ^0.5.0;
contract RWD {
string public name = 'Reward Token';
string public symbol = 'RWD';
uint256 public totalSupply = 1000000000000000000000000;
uint decimals = 18;
event Transfer(
address indexed _from,
address indexed _to,
uint _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint _value
);
mapping(address => uint256) public balanceof;
mapping(address=>mapping(address => uint256)) public allowance;
constructor() public
{
balanceof[msg.sender] = totalSupply;
}
function transfer(address _to, uint _value)public returns (bool success)
{
//require that the value is greater or equal for transfer
require(balanceof[msg.sender]>=_value);
//transfer the amount and subtract the balance
balanceof[msg.sender] -= _value;
//add the balance
balanceof[_to] += _value;
emit Transfer(msg.sender ,_to, _value);
return true;
}
function approve(address _spender,uint256 _value) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value )public returns (bool success)
{
require(_value <=balanceof[_from]);
require(_value <=allowance[_from][msg.sender]);
//add the balance for transactionFrom
balanceof[_to]+= _value;
//subtract the balance for transactionFrom
balanceof[_to]-= _value;
allowance[msg.sender][_from]-= _value;
emit Transfer(_from ,_to, _value);
return true;
}
}
Tether.sol
pragma solidity ^0.5.0;
contract Tether {
string public name = 'Tether';
string public symbol = 'USDT';
uint256 public totalSupply = 1000000000000000000000000;
uint decimals = 18;
event Transfer(
address indexed _from,
address indexed _to,
uint _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint _value
);
mapping(address => uint256) public balanceof;
mapping(address=>mapping(address => uint256)) public allowance;
constructor() public
{
balanceof[msg.sender] = totalSupply;
}
function transfer(address _to, uint _value)public returns (bool success)
{
//require that the value is greater or equal for transfer
require(balanceof[msg.sender] >= _value);
//transfer the amount and subtract the balance
balanceof[msg.sender] -= _value;
//add the balance
balanceof[_to] += _value;
emit Transfer(msg.sender ,_to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value )public returns (bool success)
{
require(_value <=balanceof[_from]);
require(_value <=allowance[_from][msg.sender]);
//add the balance for transactionFrom
balanceof[_to] += _value;
//subtract the balance for transactionFrom
balanceof[_to] -= _value;
allowance[msg.sender][_from] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
ERROR: AFTER TRUFFLE TEST COMMAND
Contract: DecentralBank
Decentral Bank Deployment
Yeild Farming
rewards tokens for staking:
Error: Returned error: VM Exception while processing transaction: revert
at Context. (test\decentalBank.tests.js:98:69)
at runMicrotasks ()
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Related

How to resolve "Warning: Could not decode event!"

I have a smart contract for sending money user-to-user.
In this smart contract, I pass the smart contract address from the Kovan network when the user selects a coin.
In this case, I pass the ChainLink contract address to my contract for sending the Chain Link token to the user.
This is ChainLink contract address in the Kovan network: 0xa36085f69e2889c224210f603d836748e7dc0088.
Now I want to test contract functions with this code:
const assert = require("assert");
const Dex = artifacts.require("Dex");
contract("Dex", (accounts) => {
let dex;
let contractOwner = null;
let buyer = null;
beforeEach(async () => {
contractOwner = accounts[0];
buyer = accounts[1];
dex = await Dex.new();
contractOwner = accounts[0];
// sometimes you need to test a user except contract owner
buyer = accounts[1];
});
// it("Add tokens and contract address Success", async () => {
// const tokenInfo = await dex.getTokenContractAddress("USDT");
// assert(tokenInfo == "0xdac17f958d2ee523a2206206994597c13d831ec7");
// })
// it("Add Token", async () => {
// await dex.addToken(web3.utils.fromAscii("LINK"), "0xa36085f69e2889c224210f603d836748e7dc0088", "0xa36085f69e2889c224210f603d836748e7dc0088")
// })
it("Deposit", async () => {
await dex.deposit("0xa36085f69e2889c224210f603d836748e7dc0088", "0x5226a51522C23CcBEFd04a2d4C6c8e281eD1d680", "0xB643992c9fBcb1Cb06b6C9eb278b2ac35e6a2711", 1,
// you were missing this
{ from: accounts[0] });
})
})
I Using Truffle in Project:
Truffle Config:
const HDWalletProvider = require('#truffle/hdwallet-provider');
const fs = require('fs');
const mnemonic = fs.readFileSync(".secret").toString().trim();
const secrets = JSON.parse(
fs.readFileSync('.secrets.json').toString().trim()
);
module.exports = {
networks: {
kovan: {
networkCheckTimeout: 10000,
provider: () => {
return new HDWalletProvider(
mnemonic,
`https://kovan.infura.io/v3/1461728202954c07bd5ed5308641a054`,
0,
20
);
},
network_id: "42",
},
},
// Set default mocha options here, use special reporters, etc.
mocha: {
},
// Configure your compilers
compilers: {
solc: {
version: "0.8.10",
docker: false,
settings: {
optimizer: {
enabled: false,
runs: 200
},
evmVersion: "byzantium"
}
}
},
};
My Contract:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "./UserCoins.sol";
contract Dex {
event Approval(
address indexed tokenOwner,
address indexed spender,
uint256 tokens
);
event Transfer(address indexed from, address indexed to, uint256 tokens);
constructor() {}
function deposit(
address ticker,
address sender,
address recipient,
uint256 amount
) external payable {
IERC20 token = IERC20(ticker);
IERC20(ticker).approve(sender, amount);
// Transfer Token To User
token.transferFrom(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
}
it shows me this error:
Warning: Could not decode event!
execution failed due to an exception. Reverted
How can I solve this problem?
function deposit(address ticker,address sender,address recipient,uint256 amount
)
external payable
this function takes 4 args, you passed all the parameters but since it is payable, you have to also make sure from which account you are calling, so you need to add 5th parameter to the function:
await dex.deposit("0xa36085f69e2889c224210f603d836748e7dc0088", "0x5226a51522C23CcBEFd04a2d4C6c8e281eD1d680", "0xB643992c9fBcb1Cb06b6C9eb278b2ac35e6a2711", "1",
// you were missing this
{from:accounts[0])
In truffle test suite, when you create the contract, it passes the accounts as the first argument to the callback. You have to define accounts in before statement so when you run the tests those will be available on top level.
contract("Dex", (accounts) => {
let contractOwner = null;
let buyer = null;
let _contract = null;
before(async () => {
// Instead of Dex.new() try Dex.deployed()
// I am not sure if "new()" is still supported
_contract = await Dex.deployed();
contractOwner = accounts[0];
// sometimes you need to test a user except contract owner
buyer = accounts[1];
});
}
You need to approve
Inside ERC20.sol you are calling this:
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
}
_transfer(sender, recipient, amount);
return true;
}
So you want DEX to transfer coin from another contract. So this another contract has to approve this transaction first. So I need to have another contract's address to be able to call approve

Web3 send contract methods without metamask

I have a question on my Node-js program, I need to transaction from my account address to contract address.
And this is my contract code:
contract price{
address owner;
constructor() public{
owner = msg.sender;
}
struct pricedata{
uint highprice;
uint lowprice;
uint avgprice;
}
mapping(uint => pricedata) PD;
modifier onlyowner(){
require(msg.sender == owner);
_;
}
function set(uint _ID, uint _highprice, uint _lowprice, uint _avgprcie) public onlyowner{
PD[_ID] = pricedata({
highprice : _highprice,
lowprice : _lowprice,
avgprice : _avgprcie
});
}
function get(uint _ID) public view returns (uint _highprice, uint _lowprice, uint _avgprcie){
pricedata memory pd = PD[_ID];
return (pd.highprice, pd.lowprice, pd.avgprice);
}
}
And this is my node-js code:
state = {web3: null, accounts: null, contract: null ,info:null ,lowprice : 0, highprice : 0, avgprice : 0};
componentDidMount = async () => {
const web3 = await getWeb3();
const accounts = await web3.eth.getAccounts();
const balances = await web3.eth.getBalance(accounts[0]);
var bal = web3.utils.fromWei(balances, 'ether');
this.setState({account : accounts[0], balance : bal});
const networkId = await web3.eth.net.getId();
const deployedNetwork = SimpleStorageContract.networks[networkId];
const instance = new web3.eth.Contract(
SimpleStorageContract.abi,
deployedNetwork && deployedNetwork.address,
);
this.setState({ web3, accounts, contract: instance });
this.runExample();
}
runExample = async () => {
const low = 0 | this.state.lowprice*100;
const high = 0 | this.state.highprice*100;
const avg = 0 | this.state.avgprice*100;
const ran = this.state.randomnumber;
console.log("test:",low,high,avg,ran);
this.state.contract.methods.set(ran, low, high, avg).send({
from : this.state.accounts[0]
});
};
I want to transaction without metamask, I want to auto onclick confirm button, the blue one:
how can I done my function with this.state.contract.methods.set?
I use Ganache to set up my ethereum.
I didn't post all my code on here, if need some more details, please tell me and I will fill it up.
You can import your Ethereum account in Web3.js. Then you don't need to confirm every transaction with Metamask.
const ganache = require('ganache-cli');
const Web3 = require('web3');
//ganache client running on port 7545
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
const getAccounts = async () => {
//To get accounts with private key
let account = await web3.eth.accounts.privateKeyToAccount('0x'+privateKey);
//privateKey is the key that you get from Ganache client
}
getAccounts();

How to handle list model in bloc flutter

I am trying to use BLOC inside my login page.. but I always get paused on exception that say Exception has occurred. _TypeError (type 'List<LoginRespon>' is not a subtype of type 'String') here is the code
isClick == true
? StreamBuilder(
initialData: bloc.inData(_name.text,_password.text),
stream: bloc.loginData,
builder: (context,
AsyncSnapshot snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
print('ppp ');
return Text('ok');
} else
return Text(snapshot.error
.toString());
})
: RaisedButton(
child: Text('Login'),
onPressed: () {
setState(() {
isClick = true;
});
},
),
and here is bloc file
class MyBLoc{
final _repository = Repository();
final _loginController = StreamController<String>();
Stream<String> get loginData => _loginController.stream;
final _name = BehaviorSubject<String>();
final _password = BehaviorSubject<String>();
saving(){
_repository.saving(_name.value,_password.value);
}
inData(String name, String password) async {
// I get paused on exception inside this method...
String result = await _repository.saving(name, password);
_loginController.sink.add(result);
}
dispose(){
_input.close();
_loginController.close();
_password.close();
}
}
final bloc = MyBLoc();
here is my repository file
class Repository{
static final userAPIProvider = UserProvider();
Future saving(String name, String password) => userAPIProvider.saving(name, password);
}
and here is my provider
class UserProvider {
final _url = '...';
Future<List<LoginRespon>> saving(String name, String password) async {
List<LoginRespon> datalogin = [];
try {
bool trustSelfSigned = true;
HttpClient httpClient = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) => trustSelfSigned);
IOClient client = new IOClient(httpClient);
print("cek");
final response = await client.post(_url,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode({
"name": name,
"pas": password,
}));
Map<String, dynamic> responseJson = json.decode(response.body);
if (responseJson["status"] == "200") {
datalogin.add(LoginRespon(
status: responseJson['status'],
data: Data(
name: responseJson['data']['name'],
status: responseJson['data']['status'])));
return datalogin;
} else {
print("ppp");
}
} on Exception {
rethrow;
}
return datalogin;
}}
and for my LoginRespon model is available here how to create a list from json string in flutter
Paused on exception happens inside bloc file in inData method is there a way to resolve this problem Exception has occurred. _TypeError (type 'List<LoginRespon>' is not a subtype of type 'String')
In MyBloc, the returned value is supposed to be String
String result = await _repository.saving(name, password);
But it's not the case with the following line in the repository
Future saving(String name, String password) => userAPIProvider.saving(name, password);
It's returning List<LoginRespon>

Send signed transaction from nodejs to private SmartContract using webjs in Quorum network not working

Context
I have a quorum network mounted following the example of 7nodes. In node 1 I have deployed a smart contract privately, putting the public key of this "BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo=" in the private form.
My goal is to make a transfer to this smart contract, to execute one of its functions. Being a private contract the transfer has to be signed.
All this from a nodejs server.
Code
The smart contract is the following:
pragma solidity ^0.4.19;
contract SimpleStorage {
uint storedData;
uint secondData;
uint TData;
function set(uint x) external {
storedData = x;
}
function setSecond(uint x) external {
secondData = x;
}
function setT(uint x) external {
TData = x;
}
function get() external view returns (uint retVal) {
return storedData;
}
function getSecond() external view returns (uint retVal) {
return secondData;
}
function getT() external view returns (uint retVal) {
return TData;
}
}
The code in nodejs is the following:
const Web3 = require('web3');
const EthereumTx = require('ethereumjs-tx');
const contract = require('truffle-contract');
const simpleStorageInterface = require("./contracts/SimpleStorage.json");
var web3 = new Web3(
new Web3.providers.HttpProvider('http://172.10.4.159:22000')
);
var generalInfo = {
contractAddress: "0x1932c48b2bf8102ba33b4a6b545c32236e342f34",
account: "0xed9d02e382b34818e88b88a309c7fe71e65f419d",
keystore: {"address":"ed9d02e382b34818e88b88a309c7fe71e65f419d","crypto":{"cipher":"aes-128-ctr","ciphertext":"4e77046ba3f699e744acb4a89c36a3ea1158a1bd90a076d36675f4c883864377","cipherparams":{"iv":"a8932af2a3c0225ee8e872bc0e462c11"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"8ca49552b3e92f79c51f2cd3d38dfc723412c212e702bd337a3724e8937aff0f"},"mac":"6d1354fef5aa0418389b1a5d1f5ee0050d7273292a1171c51fd02f9ecff55264"},"id":"a65d1ac3-db7e-445d-a1cc-b6c5eeaa05e0","version":3},
bytecode: "0x608060405234801561001057600080fd5b506101ec806100206000396000f300608060405260043610610078576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680631b03316f1461007d57806322554f34146100a857806360fe47b1146100d35780636d4ce63c14610100578063b698c1291461012b578063f5f3194114610158575b600080fd5b34801561008957600080fd5b50610092610185565b6040518082815260200191505060405180910390f35b3480156100b457600080fd5b506100bd61018f565b6040518082815260200191505060405180910390f35b3480156100df57600080fd5b506100fe60048036038101908080359060200190929190505050610199565b005b34801561010c57600080fd5b506101156101a3565b6040518082815260200191505060405180910390f35b34801561013757600080fd5b50610156600480360381019080803590602001909291905050506101ac565b005b34801561016457600080fd5b50610183600480360381019080803590602001909291905050506101b6565b005b6000600154905090565b6000600254905090565b8060008190555050565b60008054905090565b8060018190555050565b80600281905550505600a165627a7a723058209cc3ec1ccb2383d74522ba2e5974347862883f4c4aa826bb69e6e1cfcc5bdd110029",
interface: [{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"setSecond","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"setT","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getSecond","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getT","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}],
privateFor: "BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo="
}
web3.eth.getAccounts().then(async (_result) => {
// Set web3 default account
web3.eth.defaultAccount = _result[0];
// Get truffle-contract
let myContract = contract(simpleStorageInterface);
// Set provider
myContract.setProvider(web3.currentProvider);
if (typeof myContract.currentProvider.sendAsync !== "function") {
myContract.currentProvider.sendAsync = function() {
return myContract.currentProvider.send.apply(
myContract.currentProvider, arguments
);
};
}
// Instanciate the contract
var contractInstance = new web3.eth.Contract(simpleStorageInterface.abi, generalInfo.contractAddress);
// Function data
let encodedABI = contractInstance.methods.set(123).encodeABI();
let nonce = await web3.eth.getTransactionCount(web3.eth.defaultAccount);
// Transaction
let tx = {
nonce: web3.utils.toHex(nonce),
from: generalInfo.account,
to: generalInfo.contractAddress,
gas: 2000000,
gasPrice: 0,
data: encodedABI,
privateFor: [generalInfo.privateFor]
}
let decrypt = web3.eth.accounts.decrypt(generalInfo.keystore, "");
// Remove 0x from private key
var privateKey = decryptKey.privateKey.substring(2);
var bufferPK = new Buffer(privateK, 'hex');
// Generate transaction using "ethereumjs-tx"
var transaction = new EthereumTx(tx);
// Sign transaction
transaction.sign(bufferPK);
// Send signed transaction
web3.eth.sendSignedTransaction("0x" + transaction.serialize().toString('hex'), (_err, _res) => {
if(_err){
console.error("ERROR: ", _err);
} else {
console.log("Success: ", _res);
}
}).on('confirmation', (confirmationNumber, receipt) => {
console.log('=> confirmation: ' + confirmationNumber);
})
.on('transactionHash', hash => {
console.log('=> hash');
console.log(hash);
})
.on('receipt', receipt => {
console.log('=> reciept');
console.log(receipt);
})
.on('error', console.error);
});
Question and problem
The transaction is executed successfully, but the new value "123" is not changed in the smart contract. Only if I unlock the account before the transaction await web3.eth.personal.unlockAccount (account, "") works really, but I do not want to be blocking and unblocking the account for security reasons.
A correct transfer would be the following:
{
blockHash: "0xe5a2df3f592392c71f9995d697721c046f60c81d2988418b0c7b929cb17a0cee",
blockNumber: 2190,
from: "0xed9d02e382b34818e88b88a309c7fe71e65f419d",
gas: 90000,
gasPrice: 0,
hash: "0x24df9e01d9fdb7acc7a2842dcdd1d93a37e7be7885ef469a262d8a690f7143f3",
input: "0xb0101ef545cf42bb490bca4fac873ea06d989abf1fbdc89f7dfd09014c085f163c371efa5acac2b43c9dec5cb20bd11e853069a99f4bcb938d6fdcd6f2918333",
nonce: 31,
r: "0x9851006a766b4bd75051cdba9c06b6d251125d68894983eee3a4c1a53a03d77a",
s: "0x1696039cedf14a82147c858bc17896664c9c74bda313307dbf9386b7d6893938",
to: "0x1932c48b2bf8102ba33b4a6b545c32236e342f34",
transactionIndex: 0,
v: "0x25",
value: 0
}
Mine looks like this:
{
blockHash: "0x6a2aacceabe984b2c368fa9ca7c245065924dd6d88e30f81311e2a5a7e2aeab8",
blockNumber: 2119,
from: "0xed9d02e382b34818e88b88a309c7fe71e65f419d",
gas: 2000000,
gasPrice: 0,
hash: "0x4a918c1641478c1f229e7cdfff93669a6e08b37555eafe871fc3b05717cbcb79",
input: "0x60fe47b1000000000000000000000000000000000000000000000000000000000000007b",
nonce: 30,
r: "0xac64a34de4bf0c2d3f1d8da6af3d38ee12be38846f744004eeef460ad94b528e",
s: "0x10e642925665877c4e2571a2f835af68c025417574462ffc4864e6128e4a4deb",
to: "0x1932c48b2bf8102ba33b4a6b545c32236e342f34",
transactionIndex: 0,
v: "0x1c",
value: 0
}
The difference is the property "v", the value that is being fixed in my transfer is not correct, it has to be 0x25 or 0x26 to identify them as private transfers. I do not understand why these values are not setting well, helpme please.

Convert Azure Function to WebAPI call Azure Storage

I've been trying to convert the functions in this https://blog.jeremylikness.com/build-a-serverless-link-shortener-with-analytics-faster-than-finishing-your-latte-8c094bb1df2c to a WebAPI equivalent. This is my webapi call:
[HttpPost]
public async Task<IActionResult> PostAsync([FromBody] ShortRequest shortRequest)
{
_logger.LogInformation($"ShrinkUrl api called with req: {shortRequest}");
if(!Request.IsHttps && !Request.Host.Host.Contains("localhost"))
return StatusCode(StatusCodes.Status400BadRequest);
if (string.IsNullOrEmpty(shortRequest.Input))
return StatusCode(StatusCodes.Status404NotFound);
try
{
var result = new List<ShortResponse>();
var analytics = new Analytics();
// determine whether or not to process analytics tags
bool tagMediums = analytics.Validate(shortRequest);
var campaign = string.IsNullOrWhiteSpace(shortRequest.Campaign) ? DefaultCampaign : shortRequest.Campaign;
var url = shortRequest.Input.Trim();
var utm = analytics.TagUtm(shortRequest);
var wt = analytics.TagWt(shortRequest);
_logger.LogInformation($"URL: {url} Tag UTM? {utm} Tag WebTrends? {wt}");
// get host for building short URL
var host = Request.Scheme + "://" + Request.Host;
await _tableOut.CreateIfNotExistsAsync();
if (_keyTable == null)
{
_logger.LogInformation($"Keytable is null, creating initial partition key of 1");
_keyTable = new NextId
{
PartitionKey = "1",
RowKey = "KEY",
Id = 1024
};
var keyAdd = TableOperation.Insert(_keyTable);
await _tableOut.ExecuteAsync(keyAdd);
}
// strategy for getting a new code
string getCode() => Utility.Encode(_keyTable.Id++);
// strategy for logging
void logFn(string msg) => _logger.LogInformation(msg);
// strategy to save the key
async Task saveKeyAsync()
{
var operation = TableOperation.Replace(_keyTable);
await _tableOut.ExecuteAsync(operation);
}
// strategy to insert the new short url entry
async Task saveEntryAsync(TableEntity entry)
{
var operation = TableOperation.Insert(entry);
await _tableOut.ExecuteAsync(operation);
}
// strategy to create a new URL and track the dependencies
async Task saveWithTelemetryAsync(TableEntity entry)
{
await TrackDependencyAsync(
"AzureTableStorageInsert",
"Insert",
async () => await saveEntryAsync(entry),
() => true);
await TrackDependencyAsync(
"AzureTableStorageUpdate",
"Update",
async () => await saveKeyAsync(),
() => true);
}
if (tagMediums)
{
// this will result in multiple entries depending on the number of
// mediums passed in
result.AddRange(await analytics.BuildAsync(
shortRequest,
Source,
host,
getCode,
saveWithTelemetryAsync,
logFn,
HttpUtility.ParseQueryString));
}
else
{
// no tagging, just pass-through the URL
result.Add(await Utility.SaveUrlAsync(
url,
null,
host,
getCode,
logFn,
saveWithTelemetryAsync));
}
_logger.LogInformation($"Done.");
//return req.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
_logger.LogError("An unexpected error was encountered.", ex);
//return req.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
return null;
}
And this is the function params:
[FunctionName("ShortenUrl")]
public static async Task<HttpResponseMessage>([HttpTrigger(AuthorizationLevel.Function, "post")],HttpRequestMessage req,
[Table(Utility.TABLE, "1", Utility.KEY, Take = 1)]NextId keyTable,
[Table(Utility.TABLE)]CloudTable, TraceWriter log)
The azure function takes care of ensuring that the keyTable contains the next Id in the counter but I cannot figure out how to do the same in the webapi call.
Any ideas?

Resources