How to test contract with multiple accounts / addresses in truffle? - testing

I want to test my truffle contract with multiple msg.sender addresses. Like "the first user sell token, the second user buys this token". For one address I simply write something like contract.buy.value(10 wei)();. But where I could get another address and how to send money from him?
I write my tests on solidity, not on javascript.

as you can see in the Truffle docs, you can specify two different accounts to interact with your deployed smart contract like below (Metacoin example):
var account_one = "0x1234..."; // an address
var account_two = "0xabcd..."; // another address
var meta;
MetaCoin.deployed().then(function(instance) {
meta = instance;
return meta.sendCoin(account_two, 10, {from: account_one});
}).then(function(result) {
// If this callback is called, the transaction was successfully processed.
alert("Transaction successful!")
}).catch(function(e) {
// There was an error! Handle it.
})
This is about how you can do with your own created token.
If you want to transfer Ether between accounts, you can specify accounts in your truffle execution file (a javascript file). And these accounts may come from your configured local blockchain (Ganache, if you are using Truffle Suite to test your smart contract, it will provide you with several accounts and you can configure these by yourself).
Moreover, you may need javascript API to specify the sender and receiver: web3.eth.sendTransaction.
First time to answer a question, hope this will help.

Related

Chainlink VRF v2 Fail

I am running script from official instruction
https://docs.chain.link/docs/chainlink-vrf/example-contracts/
when I run topUpSubscription(10000000)
but keep receiving error here
https://rinkeby.etherscan.io/tx/0xceef45073fc882c19c5be5242ee9777ea19b578193d65519fe9bfeed6c2469fc
You're trying to invoke the function topUpSubscription() that transfers LINK tokens from your contract to the COORDINATOR address.
// Assumes this contract owns link.
// 1000000000000000000 = 1 LINK
function topUpSubscription(uint256 amount) external onlyOwner {
LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subscriptionId));
}
However, your contract doesn't have any LINK tokens. So the transfer fails, causing the main transaction to revert.
You can get testing LINK tokens on their faucet https://faucets.chain.link/rinkeby.

Avoiding entering value of ether in smart contract in Remix Injected Web 3 environment

I'm writing a smart contract so that a metamask wallet can send a certain value of eth to the smart contract. However, every time I tested the smart contract, I have to manually enter an integer. Is there any way I can solve this problem?
nope, sending eth it's not a part of tx data, but it is inside tx details, if you run that function directly on IDE REMIX, or etherscan, you have to insert it manually
anyway if you are planning to make an interface for your contract using web3js, you can manually add tx details like that before sending the tx:
const transaction = {
'to': '0x31B98D14007bDEe637298086988A0bBd31184523', //contract address
'value': 1, //1 eth
'gas': 30000,
'maxFeePerGas': 1000000108,
'nonce': nonce,
};
so the user doesn't need to write it manually

Just got scammed in a honeypot, which part of the code was it?

I just want to know which part of the code was the thing to look after next time to save my ass from getting scammed.
Code: https://bscscan.com/address/0x31d9bb2d2e971f0f2832b32f942828e1f5d82bf9#code
Only the owner of the token was able to sell, no one else. No liquidity pull.
Thank you so much.
Line 277:
require(balances1 || _balances1[sender] , "ERC20: transfer to the zero address");
balances1 is a bool
_balances1 is a mapping (address => bool)
Values of these properties are controllable only by the owner - in functions Renounce, Prize_Fund, and Reflections.
At least one of them needs to be true in order to pass the require() condition.
Without the state of the blockchain in the moment of your transaction (and your transaction details), I can't say it for sure - but it's likely that the balances1 was false, and _balances1[sender] was true only for an authorized (possibly scammer) address.
Which would effectively disallow transfers from anyone except this address.
Also, the transactions list supports my findings. Each of the Transfer events fail with this error message. And it's covered by many Approval events - possibly to not be suspicious (all transactions failed) at the first look.
Both burnAddress and charityAddress are the same address, defined early in the code sample:
address payable public charityAddress = payable(0x000000000000000000000000000000000000dEaD); // Marketing Address
address public immutable burnAddress = 0x000000000000000000000000000000000000dEaD;
The actual sending part can be found on the emit statement, that will emit the transaction to the blockchain:
emit Transfer(address(this), msg.sender, _totalSupply);
This is the constructor, so when the contract is loaded, the only path for it is by the sender, to "this" address, which is the hardcoded one, from any "sender" that bought in.

Why is .call() necessary when I want to see returned values from a smart contract function?

In my contract I have this function (solc 0.8.4):
function makeDecision(address person) external returns (string memory name, bool approved) {
require(msg.sender == loanOfficer, "Only the loan officer can initiate a decision.");
require(bytes(applicants[person].name).length != 0, "That person is not in the pool of applicants.");
if (applicants[person].credScore > 650 && applicants[person].credAge > 5) {
applicants[person].approved = true;
}
return (applicants[person].name, applicants[person].approved);
}
When I go into my truffle console and call my function this way loanContract.makeDecision(accounts[1]) everything works fine, but I get a tx receipt as the response.
When I call my function this way via truffle console loanContract.makeDecision.call(accounts[1]) I get the expected response from my function. I am wanting an explanation that tells me why this difference in response occurs so that I understand what is going on on a deeper level. I hate using things without understanding why they work.
If it helps, my contract (which is named LoanDisbursement) was initialized in the console like so: let loanContract = await LoanDisbursement.deployed() and my accounts variable: let accounts = await web3.eth.getAccounts()
any tips would help since I am still learning and diving into this ecosystem. I've not been able to find any decent documentation on this functionality as of yet. Thanks.
Truffle contract functions create a transaction - and return the transaction data.
The call function doesn't create a transaction, it just makes a call. So it cannot return transaction receipt and the authors of Truffle decided to return the function value instead.
Without transaction, the state of your contract is not changed. Which is probably not what you want, and you should always create a transaction when you need to save state changes to the blockchain.
Truffle doesn't return the function value when you're creating a transaction. Using Truffle, there are two approaches that they recommend:
Reading event logs that the transaction produced
Add an event to your function emit MadeDecision(applicants[person].name, applicants[person].approved);, and then access it in your JS code in result.logs.
Calling a getter in a subsequent call.
Tx setValue(5) and then call getValue(). Or in your case:
Tx makeDecision(0x123) and then call applicants[0x123] (assuming applicants is public).

Issues during implementation of custom ETH settler

I have investigated and played with corda-settler project. Following the recommendations within the documentation, I have created a custom ethereum module (with an outline similar to the ripple module), providing the option to settle obligations using off-ledger payments in ETH. The implementation (https://github.com/vladichhh/corda-settler)
consists of the following significant pieces:
flows
MakeEthPayment
services
ETHClient
ETHService
types
EthPayment
EthSettlement
token
registered DigitalCurrency for ETH
oracle
added logic for ETH payment verification
MakeEthPayment.kt
#Suspendable
override fun makePayment(obligation: Obligation<*>, amount: Amount<T>): EthPayment<T> {
// get ETHService client
val ethClient = serviceHub.cordaService(ETHService::class.java).client
val recipient = obligation.settlementMethod?.accountToPay.toString()
val amountToSend = amount.quantity.toString()
// trigger ETH transfer
val txHash = ethClient.sendEth(recipient, amountToSend)
// return the payment
return EthPayment(txHash, amount, PaymentStatus.SENT)
}
ETHClient.kt
fun sendEth(recipient: String, amount: String): String {
val weiAmount: BigInteger = Convert.toWei(amount, Convert.Unit.GWEI).toBigInteger()
val credentials: Credentials = WalletUtils.loadCredentials(walletPassword, walletFile)
val transactionReceipt: TransactionReceipt = Transfer
.sendFunds(web3j, credentials, recipient, BigDecimal(weiAmount), Convert.Unit.WEI)
.send()
return transactionReceipt.transactionHash
}
In order to send the required ETH amount to the specified recipient account, we have to do some Ethereum specific stuff:
we are connecting to Ethereum public blockchain environment, using “web3j” library
in order to trigger am Etherem transaction and transfer specified ETH amount, "web3j" requires an access to the file, containing encrypted sender's wallet
thus we have to provide password (to decrypt wallet) and location of the file, containing encrypted sender's wallet
And here are the issues:
I got the exception that the file could not be found, no matter where I am putting it. I have checked even the “swift” implementation and tried to use the class loader to load my file, but without success.
I suppose, the file with encrypted sender’s wallet should be located on one of the following places:
corda-settler/ethereum/src/main/resources/file.tmp
corda-settler/cordapp/src/main/resources/file.tmp
Finally I have hardcoded the location in that way:
/Users/vladimirhristov/WebstormProjects/Corda/corda-settler/cordapp/src/main/resources/file.tmp
and seems that the file was found but got another exception:
java.lang.OutOfMemoryError - screenshot
Seems that the operation of wallet decryption is highly consuming, which breaks maybe the flow. There is an option to reduce the algorithm complexity of the wallet generation, which will reflect in lower resources required to decrypt the same wallet at the next step, but this will reduce the security as well.
And here are my three basic questions ...
How could I specify (location/mechanism) and make flow to find successfully my file, containing the sender’s encrypted wallet ?
How could I access a files in the flow, or if there is another mechanism to attach only the file with encrypted wallet and pass the decryption to core Corda ?
Do I need just to increase node resources (tuning JVM params increasing -Xms/-Xmx) in order to avoid OutOfMemoryError ?
Content of the file (containing encrypted sender’s wallet):
file.tmp
{"version":3,"id":"ecb51768-8564-498a-bb11-3a5a5c8dc0bb","address":"2bafc482bd227dfd5ba250521a00be3a4cc88bbd","crypto":{"ciphertext":"e0511415792dfa7221ba1b8f32b8ec98e1410f45e612e2100df1aceddfdb22bd","cipherparams":{"iv":"7ffa2af08f502c63d57e62440ad77539"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"dklen":32,"salt":"8051a5df1c02eb3eba81d2920fbb84b76b948a1248bbba62ffff684e733948cf","n":131072,"r":8,"p":1},"mac":"be23fe0e261ba38892581d80afd0c86563748377b5cc702b6ed3285a13cceff6"}}
I will appreciate any help! Thanks in advance :)
VERY strange that Corda is giving you an out of memory error when running that flow.
I'd actually say that we'd need to be able to see the code for the flow in order to know how it could have run out of memory.
Are you running it in a container? Just make sure that you're meeting the requirements to run a JVM with an application on top.
tl;dr use a 8GB RAM machine to run your Corda node on the latest version of corda that should hopefully solve this issue.
Here's the docs page on the memory requirements;
https://docs.corda.net/docs/corda-enterprise/4.5/node/performance-results.html#sizing