How can I convert or Encrypt strings into numbers
eg: addedToStage into/as -1820302713
there is no single/main encryption method.There can be many encryption methods.You can create your own encryption methods.here is a simple one that I created.this example ,encrypts string using a number password.(encrypting string into number is a bad practice.I used string to string):
function encrypt(s:String,password:uint):String{
var ret:String="";
for(var i:uint=0;i<s.length;i++){
var added:uint=s.charCodeAt(i)+password;
added=added>uint.MAX_VALUE?added-uint.MAX_VALUE:added;
ret+=String.fromCharCode(added)
}
return ret;
}
function decrypt(s:String,password:uint):String{
var ret:String="";
for(var i:uint=0;i<s.length;i++){
var added:int=s.charCodeAt(i)-password;
added=added<0?added+uint.MAX_VALUE:added;
ret+=String.fromCharCode(added)
}
return ret;
}
now, let's try this interactive code:
trace(encrypt("StackOverFlow.com",50));//¦¨¤x¡©`¡
trace(decrypt("¦¨¤x¡©`¡",50));//StackOverFlow.com
Here I used to convert letters, to other letters with char code +password.you can have your custom methods.
I H☺P E this helps.
Related
Suppose a function that accepts an array of addresses and looks like this:
function setVoters(address[] _inputAddresses) public ownerOnly {
// [...]
}
the same contract that uses the aforementioned function has a variable defined as a mapping:
mapping(address => bool) voter;
Is looping over the array and pushing it to the mapping considered the best option when it comes to gas consumption/expenses or would it be better if the function accepts one address and does the iteration from a given UI via some JavaScript functionality?
option a:
function setVoters(address[] _inputAddresses) public ownerOnly {
// [...]
for (uint index = 0; index < _inputAddresses.length; index++) {
voter[_inputAddresses[index]] = true;
}
}
vs
option b:
function setVoter(address _inputAddress) public ownerOnly {
// [...]
voter[_inputAddress] = true;
}
JavaScript would look like this
// loop condition starts here
await task.methods.setVoter(address[key]).send({
from: accounts[0]
});
// loop condition ends here
The best in terms of gas efficiency is option a, calling a function takes quite a bit of gas, so you would pay less if you did it all in one big tx rather than many small ones.
For constants such as string literals used as URLs that might be used multiple times by a function, which has better performance, defining them at module level, or inside the functions where they are used?
Module-level:
const URL = 'http://example.org';
function foo() {
return URL;
}
Function-level:
function foo() {
const url = 'http://example.org';
return url;
}
Strings are interned in common engines (definitely for literals at least), so it doesn't make any difference. Just write
function foo() {
return 'http://example.org';
}
Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?
For example, in Go we can do:
func vals() (int, int) {
return 3, 7
}
Can this be done in Dart? Something like this:
int, String foo() {
return 42, "foobar";
}
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.
See also either for a way to return a value or an error.
I'd like to add that one of the main use-cases for multiple return values in Go is error handling which Dart handle's in its own way with Exceptions and failed promises.
Of course this leaves a few other use-cases, so let's see how code looks when using explicit tuples:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}
Not quite as concise, but it's clean and expressive code. What I like most about it is that it doesn't need to change much once your quick experimental project really takes off and you start adding features and need to add more structure to keep on top of things.
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}
So, yes, it's not much of an improvement over Java, but it works, it is clear, and reasonably efficient for building UIs. And I really like how I can quickly hack things together (sometimes starting on DartPad in a break at work) and then add structure later when I know that the project will live on and grow.
Create a class:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}
Call it however you want!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
You can create a class to return multiple values
Ej:
class NewClass {
final int number;
final String text;
NewClass(this.number, this.text);
}
Function that generates the values:
NewClass buildValues() {
return NewClass(42, 'foobar');
}
Print:
void printValues() {
print('${this.buildValues().number} ${this.buildValues().text}');
// 42 foobar
}
The proper way to return multiple values would be to store those values in a class, whether your own custom class or a Tuple. However, defining a separate class for every function is very inconvenient, and using Tuples can be error-prone since the members won't have meaningful names.
Another (admittedly gross and not very Dart-istic) approach is try to mimic the output-parameter approach typically used by C and C++. For example:
class OutputParameter<T> {
T value;
OutputParameter(this.value);
}
void foo(
OutputParameter<int> intOut,
OutputParameter<String>? optionalStringOut,
) {
intOut.value = 42;
optionalStringOut?.value = 'foobar';
}
void main() {
var theInt = OutputParameter(0);
var theString = OutputParameter('');
foo(theInt, theString);
print(theInt.value); // Prints: 42
print(theString.value); // Prints: foobar
}
It certainly can be a bit inconvenient for callers to have to use variable.value everywhere, but in some cases it might be worth the trade-off.
Dart is finalizing records, a fancier tuple essentially.
Should be in a stable release a month from the time of writing.
I'll try to update, it's already available with experiments flags.
you can use dartz package for Returning multiple data types
https://www.youtube.com/watch?v=8yMXUC4W1cc&t=110s
you can use Set<Object> for returning multiple values,
Set<object> foo() {
return {'my string',0}
}
print(foo().first) //prints 'my string'
print(foo().last) //prints 0
In this type of situation in Dart, an easy solution could return a list then accessing the returned list as per your requirement. You can access the specific value by the index or the whole list by a simple for loop.
List func() {
return [false, 30, "Ashraful"];
}
void main() {
final list = func();
// to access specific list item
var item = list[2];
// to check runtime type
print(item.runtimeType);
// to access the whole list
for(int i=0; i<list.length; i++) {
print(list[i]);
}
}
I came across quite a common problem that it seems I can't solve elegantly and efficiently in solidity.
I've to pass an arbitrary long array of arbitrary long strings to a solidity contract.
In my mind it should be something like
function setStrings(string [] row)
but it seems it can't be done.
How can I solve this problem?
This is a limitation of Solidity, and the reason is that string is basically an arbitrary-length byte array (i.e. byte[]), and so string[] is a two-dimensional byte array (i.e. byte[][]). According to Solidity references, two-dimensional arrays as parameters are not yet supported.
Can a contract function accept a two-dimensional array?
This is not yet implemented for external calls and dynamic arrays - you can only use one level of dynamic arrays.
One way you can solve this problem is if you know in advanced the max length of all of your strings (which in most cases are possible), then you can do this:
function setStrings(byte[MAX_LENGTH][] row) {...}
December 2021 Update
As of Solidity 0.8.0, ABIEncoderV2, which provides native support for dynamic string arrays, is used by default.
pragma solidity ^0.8.0;
contract Test {
string[] public row;
function getRow() public view returns (string[] memory) {
return row;
}
function pushToRow(string memory newValue) public {
row.push(newValue);
}
}
String arrays as parameters aren't supported yet in solidity.
You can convert the array elements to a byte string and then deserialize that byte string back to the array inside the function. Although this can prove to be quite expensive you can try it if you don't have a choice. You can follow this short article to serialize/deserialize any datatype in solidity.
all solutions you need:-
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract HelloWorld {
string[] strings;
// push one string to array
function pushToStrings(string memory _data) public{
strings.push(_data);
}
//get all the strings in array form
function GetAllStrings() view public returns(string[] memory){
return strings;
}
//get nth string of strings array
function GetNthStrings(uint x) view public returns(string memory){
return strings[x];
}
//push array of strings in strings
function pushStringsArray(string[] memory someData) public{
for (uint i=0; i < someData.length; i++) {
strings.push(someData[i]);
}
}
//change whole strings, take array of strings as input
function changeWholeString(string[] memory someData) public{
strings=someData;
}
}
string array is not available in Solidity
because String is basically array of character
Nested dynamic arrays not implemented
There are two types arrays in solidity: static array and dynamic array.
declaration of array
static array: These has fixed size.
int[5] list_of_students;
list_of_students = ["Faisal","Asad","Naeem"];
we access the values using index number
Dynamic arrays: The size of these arrays dynamically increases or decreases.
int[] list_of_students;
list_of_students.push("Faisal");
list_of_students.push("Asad");
list_of_students.push("Smith");
we can access the value using index number.
push and pop function is used to insert and delete the values. length function is used to measure the length of the array.
It can be done by using
pragma experimental ABIEncoderV2;
at the top of your contract you may then use dynamic arrays of strings. Ex.
string[] memory myStrings;
This is an example contract to manage the array push, get, getAll,
and remove
pragma solidity ^0.8.4;
contract Array {
string[] private fruits = ["banana", "apple", "avocado", "pineapple", "grapes"];
function push(string memory item) public {
fruits.push(item);
}
function get(uint256 index) public view returns (string memory) {
return fruits[index];
}
function remove(uint256 index) public returns (bool) {
if (index >= 0 && index < fruits.length) {
fruits[index] = fruits[fruits.length - 1];
fruits.pop();
return true;
}
revert("index out of bounds");
}
function getAll() public view returns (string[] memory) {
return fruits;
}
}
I need to split a string and convert the results to integers. Is there an easy way to do this?
Here is what I have now:
itemsA = items_str.split("|");
This returns an array with strings, now I need to convert them to integers.
I don't think I can use a "for each" because the string has some undefined values (see the example below)
The original array may look like this:
tmp_arr = new Array();
tmp_arr[1] = 4;
tmp_arr[3] = 5;
items_str = tmp_arr.join("|");
Notice that tmp_arr[0] and tmp_arr[2] are not defined.
Any ideas?
Try something like:
itemsA = itemsA.map(makeInt);
protected function makeInt(value:String, index:int, array:Array):Number {
return parseInt(value);
}
you should give the radix : 10
protected function makeInt(value:String, index:int, array:Array):Number {
return parseInt(value, 10);
}
if you convert a string like "0128" you will have bad surprise.