I am writing a token smart contract in Remix, but the sellToken always doesn't work and get the error below:
enter image description here
Here is my code:
function sellToken(uint256 amount) public returns (bool){
require(amount > 0, "You should sell some tokens");
require(balance[msg.sender] >= amount, "You should have enough amount of tokens to sell");
balance[msg.sender] -= amount;
uint256 refund = amount * tokenPrice;
payable(msg.sender).transfer(refund);
emit Sell(msg.sender, amount);
return true;
}
Related
Simple. I'm trying to interact with USDC in my Dapp.
async function approveUSDC() {
try {
const USDCContractAdress = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
const USDCContractAbi = [
"function approve(address spender, uint256 amount) public",
];
const address = "0x644F303448a1d14Fa24Bf18200Dd41790f6B9920"; //BGGExchange Contract
const amount = 50000000000000000000n ;
const USDCContract = new ethers.Contract(USDCContractAdress, USDCContractAbi, provider);
const result = await USDCContract.connect(signer).approve(address, amount);
console.log(result);
} catch (error) {
console.log(error);
}
}
Everytime I call the approve function on the USDC smart contract of polygon, the transaction return as revoked. I'm baffled please help.
Can someone please explain how can I make a function that mints a token for 0.1 eth in Solidity and verify it in HardHat? I have done this so far:
HardHat:
[owner] = await ethers.getSigners();
const Nft = await ethers.getContractFactory("contract");
const nft = await Nft.deploy(owner.address);
prov = ethers.getDefaultProvider();
let balance = await prov.getBalance(owner.address);
console.log(balance); <-- evaluates to 10000000000000
await hoodie.mint({ value: ethers.utils.parseEther("0.1") });
console.log(balance); <-- still evaluates to 10000000000000
Solidity:
function mint() payable public returns (uint256) {;
require(msg.value == 0.1 ether || msg.value == 100000000000000000 wei, "Transaction amount has to be 0.1 eth");
_safeMint(msg.sender, token_id);
return token_id;
}
Thanks in advance!
in that case,
you may try adding approve and transferFrom methods.
approve is needed to make you approve the fund transfer
transferFrom is needed to make the fund transfer happen
the contract:
function mint() payable public returns (uint256) {
require(msg.value == 0.1 ether || msg.value == 100000000000000000
wei, "Transaction amount has to be 0.1 eth");
IERC20(*the ETH address here*).approve(msg.sender, msg.value);
IERC20(*the ETH address here*).transferFrom(msg.sender, address(this), msg.value);
_safeMint(msg.sender, token_id);
return token_id;
}
You need to use payable to transfer native token such as ETH or BNB in smart contract.
And then you can call _safeMint() private function with token ID.
You also need to increase token ID after mint.
function mint() payable public returns (uint256) {
require(msg.value == 0.1 ether || msg.value == 100000000000000000
wei, "Transaction amount has to be 0.1 eth");
payable(this).transfer(msg.value);
_safeMint(msg.sender, token_id);
token_id.increament();
return token_id;
}
I've tried to write an ads-script that returns all the child accounts which had zero impression in the latest available hour (3 hours ago)
However the script returns false negative results.
Meaning there was an account with zero impressions, but the script flagged it as non-zero.
What am I missing?
function main() {
Logger.log("now.getHours(); = "+new Date().getHours());
var past = new Date(new Date().getTime() - HOURS_BACK * 3600 * 1000);
var pastHour = past.getHours();
var pastDateStr = getDateStringInTimeZone(past, 'yyyy-MM-dd');
query = "SELECT customer.id, metrics.impressions, segments.hour FROM customer WHERE metrics.impressions = 0 AND segments.hour = " + pastHour + " AND segments.date = '" + pastDateStr + "'";
Logger.log("query " + query);
updateAccountsInParallel();
}
function updateAccountsInParallel() {
// You can use this approach when you have a large amount of processing
// to do in each of your client accounts.
// Select the accounts to be processed. You can process up to 50 accounts.
var accountSelector = AdsManagerApp.accounts();
// Process the account in parallel. The callback method is optional.
accountSelector.executeInParallel('processAccount', 'allFinished', query);
}
/**
* Process one account at a time. This method is called by the executeInParallel
* method call in updateAccountsInParallel function for every account that
* it processes.
*/
function processAccount(query) {
// executeInParallel will automatically switch context to the account being
// processed, so all calls to AdsApp will apply to the selected account.
var customerId = AdsApp.currentAccount();
if (excludedAccountIds.includes(customerId)) return null;
var currentZeroImpressionRows = AdsApp.report(query, { apiVersion: 'v10' });
var rows = currentZeroImpressionRows.rows();
var accounts = [];
while (rows.hasNext()) {
var row = rows.next();
Logger.log(JSON.stringify(row));
accounts = accounts.push(row["customer.id"] + " " + row["customer.descriptive_name"]);
}
// Optional: return a string value. If you have a more complex JavaScript
// object to return from this method, use JSON.stringify(value). This value
// will be passed on to the callback method, if specified, in the
// executeInParallel method call.
return accounts.length > 0 ? account.getCustomerId() + " " + account.getName() : null;
}
/**
* Post-process the results from processAccount. This method will be called
* once all the accounts have been processed by the executeInParallel method
* call.
*
* #param {Array.<ExecutionResult>} results An array of ExecutionResult objects,
* one for each account that was processed by the executeInParallel method.
*/
function allFinished(results) {
var todayZeroCostAccounts = [];
for (var i = 0; i < results.length; i++) {
// Get the ExecutionResult for an account.
var result = results[i];
//Logger.log('Customer ID: %s; status = %s.', result.getCustomerId(),
// result.getStatus());
// Check the execution status. This can be one of ERROR, OK, or TIMEOUT.
if (result.getStatus() == 'ERROR') {
Logger.log("-- Failed with error: '%s'.", result.getError());
} else if (result.getStatus() == 'OK') {
// This is the value you returned from processAccount method. If you
// used JSON.stringify(value) in processAccount, you can use
// JSON.parse(text) to reconstruct the JavaScript object.
var retval = result.getReturnValue();
if (retval != null) {
Logger.log('%s had 0 impressions in that hour.', result.getCustomerId());
todayZeroCostAccounts.push(retval);
}
else
{
Logger.log('%s had positive impressions in that hour.', result.getCustomerId());
}
} else {
// Handle timeouts here.
}
}
}
In Hyperledger Composer, v 19.12, I am trying to use the #returns decorator to return an asset. When I call the function through the REST API though I get a succesful transaction (200 return code) but do not get the Account object in the Response Body. Here is the transaction as defined in the data model file, the associated transaction function, and the Response Body from the REST API call. The Account object is defined in the same model file.
I expect to get an Account JSON object back. What am I doing wrong?
Transaction model
/*
Read only transaction to load account
*/
#commit(false)
#returns(Account)
transaction LoadAccountTx {
o String accountId
}
Transaction function
/**
* function to load account
* #param {org.scsvault.history.LoadAccountTx} loadAccountTx
* #returns {org.scsvault.history.Account} The resulting array of accounts
* #transaction
*/
async function loadAccount(loadAccount)
{
var i = 2;
var factory = getFactory();
var NS = 'org.scsvault.history';
var account = factory.newResource(NS, 'Account', 'ACCOUNT_1');
account.accountType = 'CREDITCARD';
account.balance = 100;
account.openingbalance = 1000;
account.opendate = new Date(2017, i, i);
if (i % 2) {
account.approvalStatus = 'REQUEST_PENDING';
}
else {
account.approvalStatus = 'CREATE';
}
account.status = 'PENDING_APPROVAL';
account.creditlimit = i * 1000;
account.term_months = i;
account.encryptedDescription = account.accountType + ' from Chase';
account.apr = i;
return account;
}
Response Body:
{
"$class": "org.scsvault.history.LoadAccountTx",
"accountId": "ACCOUNT_1",
"transactionId": "09c9eb722fe3adda41fe0a4d1060ab4efff4c2ca9ad817a763dae81374123b4c"
}
EDIT:
To test further, I changed the code above to be a simple string return value and do not receive the test string back throught the REST API.
#returns(String)
transaction LoadAccountTx {
o String accountId
}
/**
* function to load account
* #param {org.scsvault.history.LoadAccountTx} loadAccountTx
* #returns {string} (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/string)
* #transaction
*/
async function loadAccount(loadAccount)
{
return "This is a test string";
}
just adding to what #nicolapaoli wrote: this is fixed in Hyperledger Composer release v0.19.13 FYI - you do get the return value.
I had very similar issue. I've just opened an issue with general example on GitHub here with ref to this question and to the message on Rocketchat as well. Hope this will be fixed soon.
As a part of my final year project in university I'm analysing Twitter data using graph entropy. To briefly outline the purposes:
I want to collect all tweet from a certain area (London) containing keywords "cold", "flu" etc. This part is done using Streaming API.
Then I want to access each of the user's (who tweeted about being ill, collected in previous section) list of followers and following to be able to build a graph for further analysis. And here I'm stuck.
I assume for the second part I should be using Search API, but I keep getting error 88 even for a single user.
Below is the code I use for the first part:
final TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
User user = status.getUser();
long userid = user.getId();
String username = status.getUser().getScreenName();
String content = status.getText();
GeoLocation geolocation = status.getGeoLocation();
Date date = status.getCreatedAt();
if (filterText(content)) {
System.out.println(username+"\t"+userid);
System.out.println(content);
System.out.println(geolocation);
System.out.println(date);
try {
getConnections(userid);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//OTHER LISTENER METHODS
};
twitterStream.addListener(listener);
// London
double lat3 = 51.23;
double lat4 = 51.72;
double lon3 = -0.56;
double lon4 = 0.25;
double[][] bb = { { lon3, lat3 }, { lon4, lat4 } };
FilterQuery fq = new FilterQuery();
fq.locations(bb);
twitterStream.filter(fq);
private static boolean filterText(String tweet) {
return tweet.contains("flu")
|| tweet.contains("cold")
|| tweet.contains("cough")
|| tweet.contains("virus");
}
And this is what I'm trying to complete the second part with:
private static void getConnections(long id) throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(id, lCursor);
System.out.println(twitter.showUser(id).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
}
}while(friendsIDs.hasNext());
}
Any suggestions?
When you receive error 88, that's Twitter telling you that you're being rate limited:
The request limit for this resource has been reached for the current rate limit window.
The search call is limited to either 180 or 450 calls in a 15 minute period. You can see the rate limits here and this documentation explains the rate limiting in detail.
As for how to get around it, you may have to throttle your search calls to the API. Twitter4J provides ways to inspect current limits/exhaustion which may help - see Twitter#getRateLimitStatus().