inititialize_mint instruction failed: invalid account data for instruction - python

first and foremost, I presume that initialize_mint is the process to create a token.
I have this program written that seems to me to be ok without an issue:
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
pubkey::Pubkey,
program::{invoke},
};
use spl_token::{instruction::*};
entrypoint!(process_instructions);
pub fn process_instructions(program_id: &Pubkey, accounts: &[AccountInfo], _: &[u8]) -> ProgramResult{
let account_info_iter = &mut accounts.iter();
let mint_account_info = next_account_info(account_info_iter)?;
let rent_account_info = next_account_info(account_info_iter)?;
let mint_authority_pubkey = program_id.clone();
let freeze_authority_pubkey = program_id.clone();
let decimals = 0;
let token_program_info = next_account_info(account_info_iter)?;
invoke(
&initialize_mint(&token_program_info.key, &mint_account_info.key, &mint_authority_pubkey, Some(&freeze_authority_pubkey), decimals)?,
&[mint_account_info.clone(), rent_account_info.clone(), token_program_info.clone()]
)?;
Ok(())
}
But then when I proceed to call it from the client, I am using this code: edited to include create_account as pointed out by #Jon C
payer_account_meta = AccountMeta(payer_keypair.public_key, True, True)
spl_program_meta = AccountMeta(TOKEN_PROGRAM_ID, False, False)
rent_account_meta = AccountMeta(solana.sysvar.SYSVAR_RENT_PUBKEY, False, False)
mint_keypair = Keypair.generate()
mint_account_meta = AccountMeta(mint_keypair.public_key, False, True)
create_account_params = system_program.CreateAccountParams(payer_account_meta.pubkey, mint_account_meta.pubkey, Token.get_min_balance_rent_for_exempt_for_mint(client), 82, spl_program_meta.pubkey)
client.send_transaction(Transaction().add(
system_program.create_account(create_account_params)
), payer_keypair, mint_keypair)
accounts = [
mint_account_meta,
rent_account_meta,
spl_program_meta
]
transaction = Transaction()
transaction.add(TransactionInstruction(
accounts,
program_id,
bytes([])
))
client.send_transaction(transaction, payer_keypair)
running this give me the error:even after including create_account it still gives thesame error
What is the account data I am getting wrong please?

Very close! You need to create an account before initializing it. You have two options:
create the account in a separate instruction, as seen in the solana-py client: https://github.com/michaelhly/solana-py/blob/f41f020938d1fb257142f18608bcb884adb54479/src/spl/token/core.py#L114
create the account from within your program, using a cross-program invocation, similar to https://solanacookbook.com/references/programs.html#create-a-program-derived-address but using invoke instead of invoke_signed, and without the program-derived address / seeds
Note that this all requires a signature from the mint keypair.
Edit post modification:
It looks like you're still generating a new keypair in mint_account_meta instead of using mint_keypair, so instead of Keypair.generate(), try:
mint_account_meta = AccountMeta(mint_keypair.public_key, False, True)

Related

Minimize Base64

So, I have a code in C# that converts the Image to base64 and vice versa. Now, I want to send the generated base64 to python.
Here's my existing code.
var startProcess = new ProcessStartInfo
{
FileName = pythonInterpreter,
Arguments = string.Format($"\"{pythonPathAndCode}\" {b64stringCSharp}"),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
using (Process process = Process.Start(startProcess))
{
error = process.StandardError.ReadToEnd();
testResult = process.StandardOutput.ReadToEnd();
lblTestOutput.Text = testResult;
lblError.Text = error;
}
This code is working just fine when I'm trying to send a small value of string to python. But when it comes in sending base64 value, an exception error appeared.
System.ComponentModel.Win32Exception: 'The filename or extension is too long'
Take note that the code is working perfectly fine when I'm sending only 32,000 string and less but base64 consist of exactly 98,260.
Is there a way to minimize this base64?
This is my python code:
import sys
inputFromC = sys.stdin
print("Python Recevied: ", inputFromC)
The maximum length for a command + arguments in Windows is 32767 characters (link). This is consistent with that you're seeing.
I recommend sending the image over the process's standard input instead. Something like:
var startProcess = new ProcessStartInfo
{
FileName = pythonInterpreter,
Arguments = string.Format($"\"{pythonPathAndCode}\""),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
using (Process process = Process.Start(startProcess))
{
process.StandardInput.Write(b64stringCSharp);
process.StandardInput.Close();
error = process.StandardError.ReadToEnd();
testResult = process.StandardOutput.ReadToEnd();
lblTestOutput.Text = testResult;
lblError.Text = error;
}
Obviously, modify your Python script to read from standard input, rather than a command-line argument.

How change one value to another in one place and use it in couple functions?

I'm writing test automation for API in BDD behave. I need a switcher between environments. Is any possible way to change one value in one place without adding this value to every functions? Example:
I've tried to do it by adding value to every function but its makes all project very complicated
headers = {
'Content-Type': 'application/json',
'country': 'fi'
}
what i what to switch only country value in headers e.g from 'fi' to 'es'
and then all function should switch themselves to es environment, e.g
def sending_post_request(endpoint, user):
url = fi_api_endpoints.api_endpoints_list.get(endpoint)
personalId = {'personalId': user}
json_post = requests.post(url,
headers=headers,
data=json.dumps(personalId)
)
endpoint_message = json_post.text
server_status = json_post.status_code
def phone_number(phone_number_status):
if phone_number_status == 'wrong':
cursor = functions_concerning_SQL_conection.choosen_db('fi_sql_identity')
cursor.execute("SELECT TOP 1 PersonalId from Registrations where PhoneNumber is NULL")
result = cursor.fetchone()
user_with_no_phone_number = result[0]
return user_with_no_phone_number
else:
cursor = functions_concerning_SQL_conection.choosen_db('fi_sql_identity')
cursor.execute("SELECT TOP 1 PersonalId from Registrations where PhoneNumber is not NULL")
result = cursor.fetchone()
user_with_phone_number = result[0]
return user_with_phone_number
and when i will change from 'fi' to 'es' in headers i want:
fi_sql_identity change to es_sql_identity
url = fi_api_endpoints.api_endpoints_list.get(endpoint) change to
url = es_api_endpoints.api_endpoints_list.get(endpoint)
thx and please help
With respect to your original question, a solution for this case is closure:
def f(x):
def long_calculation(y):
return x * y
return long_calculation
# create different functions without dispatching multiple times
g = f(val_1)
h = f(val_2)
g(val_3)
h(val_3)
Well, the problem is why do you hardcode everything? With the update you can simplify your function as:
def phone_number(phone_number_status, db_name='fi_sql_identity'):
cursor = functions_concerning_SQL_conection.choosen_db(db_name)
if phone_number_status == 'wrong':
sql = "SELECT TOP 1 PersonalId from Registrations where PhoneNumber is NULL"
else:
sql = "SELECT TOP 1 PersonalId from Registrations where PhoneNumber is not NULL"
cursor.execute(sql)
result = cursor.fetchone()
return result[0]
Also please don't write like:
# WRONG
fi_db_conn.send_data()
But use a parameter:
region = 'fi' # or "es"
db_conn = initialize_conn(region)
db_conn.send_data()
And use a config file to store your endpoints with respect to your region, e.g. consider YAML:
# config.yml
es:
db_name: es_sql_identity
fi:
db_name: fi_sql_identity
Then use them in Python:
import yaml
with open('config.yml') as f:
config = yaml.safe_load(f)
region = 'fi'
db_name = config[region]['db_name'] # "fi_sql_identity"
# status = ...
result = phone_number(status, db_name)
See additional useful link for using YAML.
First, provide an encapsulation how to access the resources of a region by providing this encapsulation with a region parameter. It may also be a good idea to provide this functionality as a behave fixture.
CASE 1: region parameter needs to vary between features / scenarios
For example, this means that SCENARIO_1 needs region="fi" and SCENARIO_2 needs region="es".
Use fixture and fixture-tag with region parameter.
In this case you need to write own scenarios for each region (BAD TEST REUSE)
or use a ScenarioOutline as template to let behave generate the tests for you (by using a fixture-tag with a region parameter value for example).
CASE 2: region parameter is constant for all features / scenarios (during test-run)
You can support multiple test-runs with different region parameters by using a userdata parameter.
Look at behave userdata concept.
This allows you to run behave -D region=fi ... and behave -D region=es ...
This case provides a better reuse of testsuite, meaning a large part of the testsuite is the common testsuite that is applied to all regions.
HINT: Your code examples are too specific ("fi" based) which is a BAD-SMELL.

How to access a smart contract function protected by access rights using Web3py?

I have a smart contract address for security tokens, and certain functions of it are protected by access rights, for which I have an address to access those functions, however I am not able to figure out, how to call that function by specifying the rights.
from web3 import HTTPProvider, Web3, exceptions
w3 = Web3(HTTPProvider('https://ropsten.infura.io/RPw9nHRS7Ue47RaKVvHM'))
contract_address = '0x635209612bf0e830ac348ef30357ee4f0e5bf560'
provider_abi = [{"anonymous":False,"inputs":[{"indexed":False,"name":"addr","type":"address"},{"indexed":False,"name":"propertyKey","type":"bytes32"},{"indexed":False,"name":"propertyValue","type":"bytes32"}],"name":"PropertySet","type":"event"},{"constant":False,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"},{"name":"_propertyValue","type":"bytes32"}],"name":"setProperty","outputs":[{"name":"","type":"bool"}],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"}],"name":"getProperty","outputs":[{"name":"","type":"bytes32"}],"payable":False,"stateMutability":"view","type":"function"}]
instance = w3.eth.contract(
address=Web3.toChecksumAddress(contract_address),
abi = provider_abi
)
user_address = "0x25BEADE120E501D7b984498D196eFe4AbE6a11F6"
country_key = "country"
country_byte_32 = Web3.toHex(Web3.toBytes(text=country_key))
print(country_byte_32) # Prints 0x636f756e747279
country_val = "IN"
country_val_byte_32 = Web3.toHex(Web3.toBytes(text=country_val))
print(country_val_byte_32) # Prints 0x494e
try:
result = instance.call().setProperty(user_address,country_byte_32,country_val_byte_32)
print(result) # Prints False
except exceptions.MismatchedABI as ve :
print(ve)
import traceback
print(traceback.format_exc())
Can someone tell me, how do I provide the access right address?
To put the value in the form field you can do it like this
result = instance.call({"from": user_address }).setProperty(user_address,country_byte_32,country_val_byte_32)

Python Maya - If objectType returns "No object name specified"

I am trying to get maya to check if the listed object is a blendshape node or not.
This is my code:
def bake(self, *args):
self.items["selection"] = cmds.ls(sl = True)
self.items["shapes"] = cmds.listRelatives(self.items["selection"], ad = True)
shapes = ()
for i in self.items["shapes"]:
bs = cmds.listConnections(i, type = "blendShape", exactType = True)
if cmds.objectType(bs, isType = "blendShape"):
print bs
It returns # Error: RuntimeError: file X:/Documents/maya/scripts\jtBakeCharacter.py line 16: No object name specified
Line 16 is: if cmds.objectType(bs, isType = "blendShape"):
Except that I AM specifying an object name, that object name is bs .. I have printed the result of bs and it has many objects listed. Many.
The code is redundant. You don't need most of the lines. The listConnections already ensures that you have only blendshapes. The exact problem is that you are calling something like:
cmds.objectType([])
for some of those extra shapes. And this is illegal. But mostly you code can be encapsulated as follows:
selected = cmds.ls(sl = True, dag=True ,shapes = True)
blends = cmds.listConnections(selected , type = "blendShape", exactType = True)
for item in blends:
print item
But this may not catch your intent perfectly, but shows how may extra steps you take. In reality you don't need the line if cmds.objectType(bs, isType = "blendShape"): for anything
Joojaa's answer is elegant, but you can get it down even shorter by using the default selection behavior:
blendshapes = cmds.ls(cmds.listHistory(pdo=True), type='blendShape') or []
for item in blendshapes:
print item
(In the quest to make it even shorter I'm not checking for the selection, so this one fails if nothing is selected).
PS: if you need to get to the blendshape from one of the upstream shapes, instead of the deformed shape, you can use listHistory (f=True)
You could try this:
from pymel.core import *
for obj in selected():
shapeNode = obj.getChildren()[0]
for output in shapeNode.outputs():
if nodeType(output) == "blendShape":
print obj, "is a blendshape"

Can I use Win32 COM to replace text inside a word document?

I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported.
I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?
Thanks!
I like the answers so far;
here's a tested example (slightly modified from here)
that replaces all occurrences of a string in a Word document:
import win32com.client
def search_replace_all(word_file, find_str, replace_str):
''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
wdFindContinue = 1
wdReplaceAll = 2
# Dispatch() attempts to do a GetObject() before creating a new one.
# DispatchEx() just creates a new one.
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
app.Documents.Open(word_file)
# expression.Execute(FindText, MatchCase, MatchWholeWord,
# MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
app.Selection.Find.Execute(find_str, False, False, False, False, False, \
True, wdFindContinue, False, replace_str, wdReplaceAll)
app.ActiveDocument.Close(SaveChanges=True)
app.Quit()
f = 'c:/path/to/my/word.doc'
search_replace_all(f, 'string_to_be_replaced', 'replacement_str')
See if this gives you a start on word automation using python.
Once you open a document, you could do the following.
After the following code, you can Close the document & open another.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "test"
.Replacement.Text = "test2"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
The above code replaces the text "test" with "test2" and does a "replace all".
You can turn other options true/false depending on what you need.
The simple way to learn this is to create a macro with actions you want to take, see the generated code & use it in your own example (with/without modified parameters).
EDIT: After looking at some code by Matthew, you could do the following
MSWord.Documents.Open(filename)
Selection = MSWord.Selection
And then translate the above VB code to Python.
Note: The following VB code is shorthand way of assigning property without using the long syntax.
(VB)
With Selection.Find
.Text = "test"
.Replacement.Text = "test2"
End With
Python
find = Selection.Find
find.Text = "test"
find.Replacement.Text = "test2"
Pardon my python knowledge. But, I hope you get the idea to move forward.
Remember to do a Save & Close on Document, after you are done with the find/replace operation.
In the end, you could call MSWord.Quit (to release Word object from memory).
If this mailing list post is right, accessing the document's text is a simple as:
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = 0
MSWord.Documents.Open(filename)
docText = MSWord.Documents[0].Content
Also see How to: Search for and Replace Text in Documents. The examples use VB and C#, but the basics should apply to Python too.
Checkout this link: http://python.net/crew/pirx/spam7/
The links on the left side point to the documentation.
You can generalize this using the object model, which is found here:
http://msdn.microsoft.com/en-us/library/kw65a0we(VS.80).aspx
You can also achieve this using VBScript. Just type the code into a file named script.vbs, then open a command prompt (Start -> Run -> Cmd), then switch to the folder where the script is and type: cscript script.vbs
strFolder = "C:\Files"
Const wdFormatDocument = 0
'Select all files in strFolder
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} Where " _
& "ResultClass = CIM_DataFile")
'Start MS Word
Set objWord = CreateObject("Word.Application")
Const wdReplaceAll = 2
Const wdOrientLandscape = 1
For Each objFile in colFiles
If objFile.Extension = "doc" Then
strFile = strFolder & "\" & objFile.FileName & "." & objFile.Extension
strNewFile = strFolder & "\" & objFile.FileName & ".doc"
Wscript.Echo "Processing " & objFile.Name & "..."
Set objDoc = objWord.Documents.Open(strFile)
objDoc.PageSetup.Orientation = wdOrientLandscape
'Replace text - ^p in a string stands for new paragraph; ^m stands for page break
Set objSelection = objWord.Selection
objSelection.Find.Text = "String to replace"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "New string"
objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
objDoc.SaveAs strNewFile, wdFormatDocument
objDoc.Close
Wscript.Echo "Ready"
End If
Next
objWord.Quit

Categories

Resources