I cannot figure out how to use #truffle/contract to interact with contracts deployed by package #openzeppelin/truffle-upgrades (ProxyAdmin and AdminUpgradeabilityProxy). I have deployed my contracts to Ganache:
Deploying 'MetaToken'
---------------------
> transaction hash: 0xac159783380d929e6de5eb9f2a8cd90146997d340aa6ac1dd0762a97ae3a7379
> Blocks: 0 Seconds: 0
> contract address: 0x5aab2dF75BeB13891a640B193C823bE02F11f752
> block number: 3
> block timestamp: 1601252702
> account: 0x43076f318858988550F85Ec308FfC832253f8c9E
> balance: 99.96601856
> gas used: 1464575 (0x1658ff)
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.0292915 ETH
Deploying 'ProxyAdmin'
----------------------
> transaction hash: 0xd1d9d3d2272ef3611b66dbf96fe8eaa8ccbc16f595e478f544b657c244f2e33d
> Blocks: 0 Seconds: 0
> contract address: 0x34De0046a5FbA24b9aFd32687990e60517FE95F6
> block number: 4
> block timestamp: 1601252703
> account: 0x43076f318858988550F85Ec308FfC832253f8c9E
> balance: 99.94841932
> gas used: 879962 (0xd6d5a)
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.01759924 ETH
Deploying 'AdminUpgradeabilityProxy'
------------------------------------
> transaction hash: 0x4e0a725865e6ce322b3479623c07e8a05c2cacdc2e5025b2f400972a5d12b43d
> Blocks: 0 Seconds: 0
> contract address: 0x2FCe57853cB98fCd6491ddebc8430E970CA333b5
> block number: 5
> block timestamp: 1601252704
> account: 0x43076f318858988550F85Ec308FfC832253f8c9E
> balance: 99.93331538
> gas used: 755197 (0xb85fd)
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.01510394 ETH
This is the code that I've tried:
Web3 = require("web3")
var provider = new Web3.providers.HttpProvider("http://localhost:7545");
var contract = require("#truffle/contract");
var fs=require("fs");
var DeployJson=fs.readFileSync("/path/metatoken/node_modules/#openzeppelin/upgrades-core/artifacts/AdminUpgradeabilityProxy.json");
var DeployJs=JSON.parse(DeployJson);
var AdminUpgradeabilityProxy=contract({abi: DeployJs.abi, unlinked_binary: DeployJs.bytecode, address: "0x2FCe57853cB98fCd6491ddebc8430E970CA333b5"});
AdminUpgradeabilityProxy.setProvider(provider);
let i = await AdminUpgradeabilityProxy.deployed()
But it throws an error:
Error: Contract has not been deployed to detected network (network/artifact mismatch)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at Function.deployed (/path/metatoken/node_modules/#truffle/contract/lib/contract/constructorMethods.js:84:11)
at Object.checkNetworkArtifactMatch (/path/metatoken/node_modules/#truffle/contract/lib/utils/index.js:249:13)
Network is the same (Ganache).
What am I doing wrong?
Andrew B Coathup from OpenZeppelin helped to get this right. The trick is to copy built artifacts of ProxyAdmin and AdminUpgradeabilityProxy from npm package into the truffle project.
cp node_modules/#openzeppelin/upgrades-core/artifacts/* build/contracts
Then the truffle console will be able to load those, so you can interact them like usual:
let proxyAdmin = await ProxyAdmin.at("0x254dffcd3277C0b1660F6d42EFbB754edaBAbC2B")
proxyAdmin.owner()
Visit this topic for additional info:
https://forum.openzeppelin.com/t/how-to-interact-with-proxy-and-proxyadmin-on-truffle-console/3964/2
The deployed() method from truffle-contract will look for the deployment address stored in the contract artifact (ie the DeployJson in your code). This value is only set if you deploy your contract via a migration, and most importantly, it's set on the artifact of the implementation contract. In this case, it would be the MetaToken.
To interact with the deployed instance, you'd need to do something like:
const MetaToken = artifacts.require('MetaToken');
const instance = await MetaToken.deployed();
Or, to bypass the deployed() mechanic and attaching directly:
const MetaToken = artifacts.require('MetaToken');
const instance = await MetaToken.at('0x2FCe57853cB98fCd6491ddebc8430E970CA333b5');
This will return an instance of a truffle-contract at the proxy address (0x2FCe57853cB98fCd6491ddebc8430E970CA333b5) with the MetaToken ABI, which is what you probably want.
If you want to interact with the Proxy to upgrade it or change the owner, you should do so through the upgrades plugin methods.
Related
Good day, everyone! I'm currently taking a 16-hour freecodecamp course on Solidity, Blockchain, and Smart Contracts, and I'm having trouble sending a simple signed transaction to Ganache and I keep getting this Value error message "ValueError: {'message': 'insufficient funds for gas * price + value', 'stack': 'Error: insufficient funds for gas * price + value\n at TransactionPool.prepareTransaction (/home/fingergod/.nvm/versions/node/v17.8.0/lib/node_modules/ganache/dist/node/1.js:2:131154)', 'code': -32003}".
P.S. I've already set my gas price to "gasPrice" while building transactions to be: "gasPrice": w3.eth.gas _price
from solcx import compile_standard, install_solc
import json
from web3 import Web3
import os
from dotenv import load_dotenv
load_dotenv()
install_solc("0.8.13")
with open("./SimpleStorage.sol", "r") as file:
simple_storage_file = file.read()
# compile solidity file
Compiled_solFile = compile_standard(
{
"language": "Solidity",
"sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
"settings": {
"outputSelection": {
"*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourcecode"]}
}
},
},
solc_version="0.8.13",
)
# print(Compiled_solFile)
with open("compiled_code.json", "w") as file:
json.dump(Compiled_solFile, file)
# get bytecode
bytecode = Compiled_solFile["contracts"]["SimpleStorage.sol"]["simpleStorage"][
"evm"
]["bytecode"]["object"]
# get abi
abi = Compiled_solFile["contracts"]["SimpleStorage.sol"]["simpleStorage"]["abi"]
# print(abi)
# for conneecting to ganache
url = "hTTP://127.0.0.1:8545"
w3 = Web3(Web3.HTTPProvider(url))
chain_id = 1337
my_address = "0x15f029FEB462294b117AD56b1736c551c64a4D80"
private_key = os.getenv("PRIVATE_KEY")
print(private_key)
# Create the contract in python
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
print(SimpleStorage)
# get the nonce/latest transaction count
nonce = w3.eth.getTransactionCount(my_address)
print(nonce)
# 1. Build the transacion(needs;chainid,address,nonce)
# 2. Sign the transaction(needs;transaction,privatekey)
# 3. Send the signed transaction
# 1.
transaction = SimpleStorage.constructor().buildTransaction(
{
"chainId": chain_id,
"gasPrice": w3.eth.gas_price,
"from": my_address,
"nonce": nonce,
}
)
print(transaction)
# 2.
signed_txn = w3.eth.account.signTransaction(transaction, private_key=private_key)
print(signed_txn)
# 3.
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
Any assistance would be highly appreciated. I've been stranded here for the past two days.
I think this has to do with your gasLimit value due to gas * price being equal to how much gas you are sending and not how much gas the operation costs. You might have seen from the course you are taking, but as a reminder; when you are sending a transaction to a contract, you are sending the amount of gas which is specified in the gasLimit attribute independent of how much it will cost. That means you are actually sending Wei equal to the gasLimit * gasPrice + value. Try to set your gasLimit attribute (in hex format for consistency) in transaction object to a value lower than your network default and maybe the gasPrice as well.
This should be an issue with insufficient account balance. Try sending the same transaction using an high-level function like transact() to see if it succeeds. If so, you can replicate the gasLimit and gasPrice from the tx details for your build_transaction().
Another note: You can omit the "gasPrice": w3.eth.gas_price line, because you are assigning the network default value, which is done automatically if you omit it, so there is no point to it unless you are going to assign another custom value.
I need to create a cloudwatch alarm in Account 1 and attach it to Route53 Health check. This Cloudwatch alarm is based on a metric in Account 2.
The Cloudwatch Cross account is enabled it Account 1 and the role has the trust policy to assume Account 2:
resource "aws_cloudwatch_metric_alarm" "internal_lb_response_time" {
alarm_name = "int-alb-response-time"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "2"
threshold = "10"
alarm_description = "This metric monitors the target response time"
treat_missing_data = "notBreaching"
metric_query {
id = "target_response_time_internal_lb"
return_data = true
account_id = "34999999999"
metric {
namespace = "AWS/ApplicationELB"
metric_name = "TargetResponseTime"
period = "60"
stat = "p95"
dimensions = {
LoadBalancer = var.internal_alb
}
}
}
tags = merge(var.tags,{ "Name": "int-alb-response-time"})
}
When I apply this in terraform, I get this error:
Error: failed creating CloudWatch Metric Alarm (int-alb-response-time): ValidationError: One or more metrics in your request are Forbidden.
│ status code: 400, request id: 82184b29-3bc0-4a61-a95d-309855375041
│
When I comment the line :
account_id = "34999999999"
The alarm gets created in account 1 but no data points are showing.
How to create a cross account cloudwatch alarm ?
Below is the snip of the script: Using Brownie in VS Code
Error: "Gas estimation failed: 'execution reverted'. This transaction will likely revert. If you wish to broadcast, you must set the gas limit manually."
from brownie import AdvancedCollectible, accounts, config
from scripts.helpful_scripts import get_breed
import time
STATIC_SEED = 123
def main():
dev = accounts.add(config["wallets"]["from_key"])
advanced_collectible = AdvancedCollectible[len(AdvancedCollectible) - 1]
transaction = advanced_collectible.createCollectible(
STATIC_SEED, "None", {"from": dev, "gas_limit": 50000}
)
print("Waiting on second transaction...")
# wait for the 2nd transaction
transaction.wait(1)
time.sleep(35)
requestId = transaction.events["requestedCollectible"]["requestId"]
token_id = advanced_collectible.requestIdToTokenId(requestId)
breed = get_breed(advanced_collectible.tokenIdToBreed(token_id))
print("Dog breed of tokenId {} is {}".format(token_id, breed))
I think this has already been answered here. To summarize it, you probably have vrf_coordinator version error. Try the rinkeby's values from the official docs.
I had the same issue. But Patrick is correct, I did not have any Link tokens inside of my newly created contract on Rinkeby network...So I commented out most of the lines of the code in create_collectible.py to import and apply the fund_advanced_collectible() function once more on my contract:
from helpfulscripts import fund_advanced_collectible
def main():
dev=accounts.add(config['wallets']['from_key'])
advanced_collectible= AdvancedCollectible[len(AdvancedCollectible)-1]
# transaction=advanced_collectible.createCollectible(STATIC_SEED,"None", {"from": dev})
# transaction.wait(1)
# time.sleep(35)
# requestID=transaction.events["requestedCollectible"]["requestID"]
# tokenID=advanced_collectible.requestIDToTokenID(requestID)
# breed=get_breed(advanced_collectible.tokenIDToBreed(tokenID))
# print('Dog breed of {} is {}.'.format(tokenID, breed))
fund_advanced_collectible(advanced_collectible)
With a reminder of the function definition of fund_advanced_collectible from helpfulscripts.py:
def fund_advanced_collectible(nft_contract):
dev=accounts.add(config['wallets']['from_key'])
link_token=interface.LinkTokenInterface(config['networks'][network.show_active()]['link_token'])
link_token.transfer(nft_contract, 100000000000000000,{"from":dev})
Once the transaction was confirmed, I could verify in https://rinkeby.etherscan.io/address that my contract had 0.1 Link and so when executing your code again, the error disappeared...
I am trying to retrieve data from mysql database using rails. it is working fine but it does not return the data which are near to boundary dates. for example
if params[:from] and params[:to]
fr = nil;
fr = DateTime.parse(params[:from]) unless params[:from].empty?
to = nil
to = DateTime.parse(params[:to]) unless params[:to].empty?
if !fr.nil? and !to.nil?
puts "------------------"
puts fr
puts to
#m = #m.where(start: fr..to)
end
end
#m.size
Logs info
App 30303 stdout: ------------------
App 30303 stdout:
App 30303 stdout: 2015-04-12T16:26:16+02:00
App 30303 stdout:
App 30303 stdout: 2015-04-13T16:26:16+02:00
App 30303 stdout:
App 30303 stdout: 0
I am sure that there is data for and hour before
268129 | 2015-04-13 15:21:53 | 2015-04-13 15:21:53 |
where first is id, second column is start date
So for sure date are correct as I can see in logs and particular user has data also. I am trying to extract data from last 24 hours.
Any suggestions?
ok so the problem is that the code uses a time zone while the database seems to hold a datetime object without timezone info, so we need to tell rails to take that time and assume it's normal utc time, hopefully this works.
if params[:from] && params[:to]
Time.use_zone('UTC') do
fr = Time.parse params[:from]
to = Time.parse params[:to]
end
#m = #m.where(start: fr..to)
end
end
#m.size
I'm encounter a strange error and I don't know how to fix it. I'm creating test entities in Bootstrap.groovy:
def init = { servletContext ->
if (Environment.current != Environment.TEST) {
servletContext.reloadId = new Date().getTime() // for reloading css
// create some insurance companies
InsuranceCompany ozp = InsuranceCompany.findOrSaveWhere(code: "207", acronym: "OZP", name: "Oborová zdravotní pojišťovna zaměstnanců bank, pojišťoven a stavebnictví")
InsuranceCompany vzp = InsuranceCompany.findOrSaveWhere(code: "111", acronym: "VZP", name: "Všeobecná zdravotní pojišťovna České republiky")
InsuranceCompany vozp = InsuranceCompany.findOrSaveWhere(code: "201", acronym: "VOZP", name: "Vojenská zdravotní pojišťovna České republiky")
Patient miladavrana = Patient.findOrSaveWhere(title: "JUDr", firstName: "Milada", lastName: "Vraná", RC: "0307080846", insuranceCompany: vozp,address: new Address(street: "5.Května", number: 568, city: "Korouhev", PSC: 16422))
Patient jiristarecek = Patient.findOrSaveWhere(title: "", firstName: "Jiří", lastName: "Stareček", RC: "9457174705", insuranceCompany: cpzp,address: new Address(street: "Nad Schody", number: 180, city: "Velký Valtinov", PSC: 51521))
}
Actually the bootstrap file is quite longer, it has almost 1000 lines of test data. Everything works ok if I comment 2/3 of those data. When I have all of these data uncomment and grails is trying to create it, it fails:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000000262b036, pid=4152, tid=8016
#
# JRE version: 6.0_29-b11
# Java VM: Java HotSpot(TM) 64-Bit Server VM (20.4-b02 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# j BootStrap$_closure1.doCall(Ljava/lang/Object;)Ljava/lang/Object;+87
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
#
--------------- T H R E A D ---------------
Current thread (0x000000000d985800): JavaThread "pool-7-thread-1" [_thread_in_Java, id=8016, stack(0x000000000bcf0000,0x000000000bdf0000)]
siginfo: ExceptionCode=0xc0000005, reading address 0x0000000138c797cf
Registers:
RAX=0x000000000bdedd78, RBX=0x000000000bdedd78, RCX=0x00000000d9d1e488, RDX=0x00000000d9d0abff
RSP=0x000000000bdedd88, RBP=0x000000000bdeddb8, RSI=0x000000000d985800, RDI=0x000000000ee83ed0
R8 =0x0000000000000004, R9 =0x00000000d4b4e890, R10=0x000000006dfc4f80, R11=0x000000000ee83f38
R12=0x0000000000000000, R13=0x00000000d9d1d8ce, R14=0x000000000bdee5b0, R15=0x000000000d985800
RIP=0x000000000262b036, EFLAGS=0x0000000000010287
this is part of the log the error generates. I'm using Grails 2.0.1 & MySQL 5.5.21 as a database. Anyone could hep or has this error before? Thank you very much.
Cheers,
Lojza
Try increasing the heap allocation to your JVM through JAVAOPTS.